output
stringlengths 34
25.7k
| instruction
stringlengths 81
31k
| input
stringclasses 1
value |
---|---|---|
You can do this by using the Powershell Extensions module.
$item = get-item master:\content\Demo\Int\Home
$device =Get-Device -Default
$contentDataSource = get-item master:\content\Demo\Int\Home\about-us\employee-stories\adam-najmanowicz
$ImageDataSource = get-item master:\content\Demo\Int\Data\Images\d56cf7e777a2496aa6489a7bffc03539
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Content
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -Parameter @{FieldName ="Title"} -DataSource $contentDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Image
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -DataSource $ImageDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Subtitle
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -DataSource $contentDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Title
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main
Source: Adam Najmanowicz Gist.
This should serve as a good starting point. Here is the documentation of the Add-Rendering function:
https://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/content/appendix/commands/Add-Rendering.html
| How can I programmatically add a rendering to all of my content items?
I need to add a rendering to all of the pages in my Sitecore tree (i.e., items that have renderings, have a layout set, and live under /sitecore/Content). Content items that don't have renderings or a layout set don't need the rendering. I want to add this rendering to the layoutHeader placeholder on my pages and the rendering does not require a data source.
Is this something that's possible with the Sitecore API or Sitecore PowerShell? If so, how would I go about it? I'm working with Sitecore 8.1 Update-3.
| |
I know that this is an old post, but I was looking through and just wanted to add some information to help anyone who is actually still hoping to implement similar behavior to this.
At a high-level, @MarkCassidy is correct that there is no OOTB mechanism for what you are describing. However, you could achieve a limited version of this functionality by leveraging eventing or the item provider pipelines, combined with a little extra logic.
Lingo
Branch = Branch
Implementor = subtree created from branch
Corresponding Item = item in implementor that corresponds to item in branch
Corresponding Field = field of corresponding item in implementor corresponding to field of item in branch
Functionality to Implement
Before we start coding, let's consider the functionality that we can and plan to implement:
Item in branch has field or presentation change -> change applied to corresponding item in implementors of the branch
If corresponding item doesn't exist in implementor then no action is taken
If a field is changed and the original value of the field does not match the value of the corresponding field in the implementor then no action is taken (do not overwrite changes)
Item renames should not be applied to implementors
The above logic includes both the Renderings and Final Renderings fields (Shared Layout and Final Layout), so long as no changes have been made to either.
For simplicity, we will skip the following enhancements, but they could be added with limited additional effort:
Field comparison supports token resolution (e.g. $name)
Deleted item support (would require an additional event-handler; see below for more)
Rendering property change detected by reviewing content of deltas
Comparison of deltas in corresponding item to allow applying changes even after corresponding item's presentation details have been changed (this one would likely take more than a little effort, but it is still doable, with limitations)
Calling our Logic
Before we get into specifics, let's figure out how we will be calling this logic. For starters, we know that we want the logic to run when a branch template is "changed." We can detect that a branch template has "changed" by listening for when the branch template item or one of its descendants has been saved. However, note that it is possible that the branch template or one of its descendants will be saved without any actual changes. This extra call to our logic should not result in any side-effects.
Listening for Changes
Now that we know that we want to listen for the branch items or one of its descendants to be saved, we can pick the "listening" mechanism. This is a crucial step, as the information that we have about the item being changed will vary based on the mechanism that we choose. For example, the item:saved event will show us the changed item, but we won't be able to compare it with its previous state (i.e. before it was changed).
There is really only one good candidate for listening mechanisms in this case: the item:saving event.
The item:saving Event
The item:saving event has been around for a long time and its use is fairly well-documented online. The item:saving event is viable for our use-case because while one of its parameters is an updated "copy" of the item being saved (i.e. an item that looks like the unmodified item, except that it has all of the changes that were made and are being saved), yet the changes haven't actually been saved. This means that we have access to both of the following:
The "updated item", and thus the changes, by looking at the item retrieved from the event's parameters
The unmodified item, and thus a point of comparison, by retrieving the item from the database using the same ID as the "updated item" (remember that the updated item hasn't been saved yet)
While this is all well and good, there are two major drawbacks of using the item:saving handler for our use-case:
In order to get the unmodified item for comparison, we need to retrieve the item from the database by performing an extra item-get (yuck, but not the end of the world)
In order to actually see the changes that were made, all of the fields of the updated item will need to be compared with the unmodified item and any that differ can be considered "modified" (BIG yuck!)
The good news, is that - as previously mentioned - using this event has been pretty well-documented and should be pretty straightforward.
The only change that this handler will not support is if an item is deleted/archived. In this case, we would need to add an additional handler to support accounting for those changes. Once our initial logic is written, that extra handler will be pretty straightforward, so I will skip that functionality for the purpose of this post.
The Code/Logic
Obviously, this is a pretty complex piece of functionality, so I'm not actually going to code it here (being lazy :P), but I will walk you through the high-level of what you will want to do:
Set up your event handler to run the rest of your logic and configure it to fire on item:saving.
When hit, handler first checks to see if the item is or is part of a branch template and returns if it is not
Retrieve the unmodified version of the item from the database and compare the fields to create a Dictionary<KeyValuePair<string, string>, string> with the KeyValuePair<FieldName, OriginalValue> as a key and ModifiedValue as the value. This will be the changesDictionary If the populated changesDictionary is empty, then return.
Find all of the items created from that item's branch (links database, content search, etc)
For each of the returned items, select the corresponding item to the item in the branch that was changed. If the corresponding item is missing, return null
Filter out null items from the list (i.e. filter out implementors that are missing the corresponding item)
For each Key in the changesDictionary iterate through the remaining items and if the value of the Key.Key field (corresponding field) is the same as the Key.Value (unmodified branch field value) then update the field to the changesDictionary[Key] (modified value) inside of an EventDisabler (for performance reasons; not to avoid side-effects)
While this will work, there is a fairly large risk of performance degradation when saving branch items. Fortunately, this isn't something that happens often after initial development.
| What's the best way to update items created from a branch template
When you create items based on a branch template, those items will contain a copy of the content, renderings etc. of the branch at the time the items were created - any changes applied to the branch template, once the items have been created, will not automatically appear on the created items.
Assuming that I want to update all the previously created items, with any new changes found in the branch template since the item creation (including sub-items, renderings etc.), what would be the best strategy for doing so? The strategy should take into account that renderings that might have been added previously, but later removed by a content editor, should not be re-added back to the item. Preferably, the update strategy functionality should be something that is executable from within the content editor in Sitecore.
| |
No. But it won't take all that much custom development to achieve.
A full detailed answer would be blog post sized; so am just posting the general principle here for inspiration.
Your problem is; the Rules Engine operates on an if-else-then basis, and it does so by-component. You have no control over component relationships. Reasons for this are many; but looking at the underlying XML structure in the __Renderings field will pretty much tell the tale.
What you can do however, is create a simple "Item Renderer" component of your own. Its datasoure would be little more than a simple Treelist or Multilist control. In that - you will select your datasource items to be rendered and - given you do have control over this in both Treelist and Multilist - you can control their individual ordering as well.
The Item Renderer would then loop through items, in the order listed, and render the item. How? Well there are several ways - but the __Renderers field is an obvious candidate. I've also used the __Controller and __Action fields on items to achieve this, but this limits your rendering choices to purely Controller Renderings.
With this in place; all you need to do is create multiple variations of the "Item Renderer" datasource Multilist and use those in your Rules Engine based personalisation.
Not an ideal solution and plenty of room for improvement; but hopefully gets you thinking a little bit outside the box and help you along :-)
| Can I change the order of components in placeholder based on personalization?
I've seen a few examples on how you can use personalization in Sitecore to personalize the way a component (rendering / sub-layout) is displayed on your webpage. However, most of these guides explain how you can show/hide a component, given a certain criteria is met. In my case I would like to change the order, in which the components are sorted inside a placeholder.
Is that this something that can be achieved using personalization, is this out-of-the-box functionally, or does it require custom development to do so?
| |
If you simply want to render out a partial view (either view rendering or controller rendering), from another view or layout, you could use the Sitecore MVC extension methods:
Render view rendering:
Html.Sitecore().ViewRendering("Path to the View")
Render controller rendering:
Html.Sitecore().Controller("Controller Name", "Controller Action")
If you are using Sitecore 8.1 (or above) and want to include the Area part, I would recommend taking a look at the following blogpost, in order to see how this works:
https://ctor.io/new-in-sitecore-8-1-mvc-areas/
| Is there any alternative to @Html.RenderAction in Sitecore?
I want to load partial view using
@Html.RenderAction("AccountNav", "Navigation", new { Area = "areassomething" })
but it throws an error.
Is there any alternative?
Is the semantic correct?
I have requirement such that I have to use something like this.
| |
When you set a conditional rendering, the data for the condition and action is stored inside the Layout. Here is an example of a rendering with an "Alternative Datasource" rule that is applied if the current date is Wednesday:
<r xmlns:p="p" xmlns:s="s" p:p="1">
<d id="{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}">
<r uid="{B343725A-3A93-446E-A9C8-3A2CBD3DB489}">
<rls>
<ruleset>
<rule uid="{EB08864D-C3BA-4130-A22B-ECF765D368E5}" s:name="Alternative Datasource">
<actions>
<action uid="D3AF4C7A8CF14BC59601B2E88CE2ECFC" s:id="{0F3C6BEC-E56B-4875-93D7-2846A75881D2}" s:DataSource="{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}" />
</actions>
<conditions>
<condition uid="86296CD54FE94F96B27C153C3318B5C7" s:id="{1F15625B-8BDC-4FD2-8F0C-6EE2B8EF0389}" s:day="{8A19F2AA-ABB9-4496-A64E-56CDBE1C2D4C}" />
</conditions>
</rule>
<rule uid="{00000000-0000-0000-0000-000000000000}" s:name="Default">
<conditions>
<condition uid="CE7C9CE0A8534636BCD0DCC373A8B661" s:id="{4888ABBB-F17D-4485-B14B-842413F88732}" />
</conditions>
<actions />
</rule>
</ruleset>
</rls>
</r>
</d>
</r>
Your intuition is right that this is connected to the "Set Data Source" action behind the scenes. The reference can be spotted here:
<action uid="D3AF4C7A8CF14BC59601B2E88CE2ECFC" s:id="{0F3C6BEC-E56B-4875-93D7-2846A75881D2}" s:DataSource="{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}" />
s:id represents the ID of the Action Item ("Set Data Source")
s:DataSource represents the value of the parameter DataSource to be passed to the action.
Both of these parameters can be changed. For example to change the action so that it instead uses the "Set Placeholder" action and on execution sets the Placeholder value to "sidebar", you would use this:
<action uid="D3AF4C7A8CF14BC59601B2E88CE2ECFC" s:id="{9F2C4C80-8472-4296-9D41-D42A383B90DD}" s:Placeholder="sidebar" />
If this is saved and run on the published site, it absolutely works. However, there are two large drawbacks it seems, one of which you've spotted:
No UI support. The rule will still show in the UI and conditions on it can be edited without affecting the altered action, but there is otherwise no indication there is a special rule in place.
Previewing the rules in Editing mode do not appear to work. If you use the drop-down to view the alternate rule, it won't have any visible effect. This may just apply to the "Set Placeholder" action, however.
If UI support is not a problem for a solution then this could be useable.
Note that the tests for the above were performed in Sitecore 8.2 Initial Release.
| How to invoke other actions in Conditional Renderings?
Another question here (Can I change the order of components in placeholder based on personalization?) got me thinking - maybe there was a way to actually dynamically assign a placeholder to a rendering through personalization.
And a bit of digging - turns out, maybe there is.
So there seem to be baked-in Conditional Rendering actions for everything one could wish for - the problem is the GUI. It basically only allows for us to select the conditions (if date has passed, if xDB is enabled and so on) - and then select "Associated Content" for the rendering. Presumably this is the "Set Data Source" action behind the scenes.
Any ideas as to how we can reach the other actions? or will we just have to wait for an UI update?
| |
A big question, so I will answer just a slice of it, what Personally Identifiable Information IPII) does xDB store out of the box. I'm tempted to say nothing: as an implementer, you have the option to identify a contact, and to tag that contact with information via the contact facet mechanism. xDB ships with predefined facets for personal information such as name and email, and this is extensible so you can add facets to record whatever information you like. But this requires customization. Sitecore provides the data storage and API.
What Sitecore xDB will do out of the box is create a visitor cookie to track that device over time (SC_ANALYTICS_GLOBAL_COOKIE). The API provides a mechanism to "identify" the visitor, by tagging it with an arbitrary string value, such as an email address. Identifying a visitor allows XDB to link this cookie to other visitor cookies with the same identification, which in turn enables sharing personalization, analytics, and session state. Again, this requires an API call.
Without developer setup, Sitecore xDB records each page visit associated with the visitor cookie. Since Sitecore 8.1, IP addresses are hashed, and there is a configuration option to suppress retention altogether, or to select the hashing mechanism. See Sitecore's documentation on IP hashing.
| Sitecore, personal data and General Data Protection Regulation (GDPR)
Across Europe new privacy legislation has been introduced; GDPR.
In a nutshell it says that the following are the responsibility of not only the customer but also the supplier:
Seeking consent from data subjects where personal data is stored on their behalf
Providing robust processes and tools to enable the “right to be forgotten” (i.e. data about an individual must be able to be completely deleted, and evidence produced that this has been done)
Setting out clear, unambiguous retention periods for the data we store, and a defined business need for retaining specific types of data
Reporting breaches if and when they occur
The legislation is in force now but will be enforced from May 2018 with significant fines applied in cases of non-compliance or breach.
Indeed in the sectors the company I work for (mostly Government and Charities) we're seeing this crop up more and more in RFP documents.
This has a potentially large impact on Sitecore's personalisation and the xDB going forward.
So finally to my question(s):
Does anyone have an idea of what Sitecore road-map is for GDPR? So I can explain back to customers how Sitecore will deal with this.
Are any partners looking at this at the moment? Both in terms of how Sitecore can be compliment now (perhaps purging users from xDB) or thinking about using pseudonymisation?
Finally is anyone aware of a detailed guide of what Personally Identifiable Information Sitecore stores in XDB out of the box
Big broad sweeping question, but one our InfoSec crew are increasingly curious about.
Update for Sitecore 9
The right to be forgotten - fulfilled by Sitecore 9 by allowing anonymisation of a contact - it will delete all personal identifiers for the user but keep an anonymous record.
Opt-outs - There is a solution to remove a contact from all email lists now (without removing them from service emails - password resets etc.)
Personal information - You can add an attribute for PII contact details now which stops it being indexed and searchable.
Reference
https://www.codehousegroup.com/insight-and-inspiration/biz-stream/how-upgrading-to-sitecore-9-can-help-compliance-with-gdpr
https://www.sitecore.net/resources/index/white-papers/sitecore-and-gdpr
Update for Sitecore 6, 7, 8
Reference
https://www.sitecore.com/resources/index/white-papers/gdpr-compliance-with-your-sitecore-implementation
| |
Props to @rosscartwright, @cassidydotdk, and @jammykam for getting us to the answer at lightning speed and for the helpful links.
The issue was a feature of Sitecore called AlwaysStripLanguage that is controlled by a Sitecore Setting in the Language group that controls the activation of a processor in the <preprocessRequest /> pipeline called Sitecore.Pipelines.PreprocessRequest.StripLanguage.
Turns out that this component will not only remove URL prefixes it recognises as a language registered on the site (in /sitecore/system/Languages), but it will respond to any code that maps to a culture known to Windows.
For a list of the known culture codes check this ISO 639-2 Language Code List - you will notice that in our case the issue was the Cherokee language.
There is also an article on Sitecore Community - Prevent the Sitecore ASP.NET CMS from Interpreting URL Path Prefixes as Language Names that is a port of an old article by @JohnWest.
In our case we have replaced the default processor with a new one that only removes a language if it is configured in the list of languages for the site. Note that as it states in John's article, these processors run before there is a site context as the Site Resolver is in the httpRequestBegin pipeline that runs later. Mileage will vary - build yourself a solution that suits your use case.
I will upload our solution to the Sitecore Marketplace in due course so if you're looking for it, have a poke around in there.
| Why does my marketing URL redirect me to the site root?
[Question transposed from Slack]
We are trying to create a site with a virtualFolder of /chr. When we navigate to home page in the site, the system redirects us back to the site root. We have checked aliases, mod_rewrite/helicon ape/urlRewrite, and ignoreUrlPrefixes and all that stuff to no avail.
We have noticed the following works with no issue:
/ch-r
/chr1
/chs
Does anyone have any idea what is going on here?
| |
The link to the instructions page is unreachable to me. So I'm just going to explain how I've done it.
In the core db:
Create a new layout under /sitecore/layout/Layouts/Custom Applications/ and set the path to the aspx page, starting from the website root (e.g. /path/to/page.aspx (note the forward slash at the start))
Create an item under /sitecore/content/Applications/ with the /sitecore/templates/Sitecore Client/Applications/Application template. Fill in a Display name, choose an Icon and optionally a Tool tip.
Open the presentation details of the new item and choose the earlier created layout as Layout.
Under /sitecore/content/Documents and settings/All users/Start menu/Programs, create a new item based on the /sitecore/templates/Sitecore Client/Applications/Application shortcut template.
Set the Application link and a Display name. The raw value for Application looks like this in my case:
<link text='' linktype='internal' style='' alt='' querystring='' id='{3585E982-D30B-43EB-93A9-F5F9450FB450}' url="/Applications/Sales"/>
Make sure you have built the codebehind for your aspx page and that the binary is in the bin folder.
| Difficulties setting up Application shortcuts in Sitecore 8.1
I'm attempting to set up a shortcut in the Sitecore (8.1) start menu to an application (basically a custom .aspx page sitting within the /sitecore folder). I've roughly followed these instructions (and have paid attention to this gotchya), but in detail I have done the following (all in the core database):
Created a new Layout with the Path set to the relative URL of my .aspx page
Created a new Application and assigned the new Layout in the Presentation Details
Created a new Application Shortcut (within /sitecore/content/Documents and settings/All users/Start menu/Programs) linking to the Application item (making sure the raw value of the Application link includes the url attribute)
Sure enough, the shortcut appears in the start menu, but clicking it does nothing. I've checked the network trace and the following is returned:
{"commands":
[
{"command":"SetAttribute","value":"/temp/iconcache/people/16x16/astrologer.png","id":"globalHeaderUserPortrait","name":"src"},
{"command":"SetPipeline","value":"6CD9455F4EA6498F978F96D5A1CDD5E6"},
{"command":"Eval","value":"scForm.browser.closePopups(\"Shell RunShortcut\")"}
]
}
Does anyone have any suggestions about what I might be doing wrong here?
| |
A very large log file is symptomatic of the problem of no backups taking place. Under normal circumstances SQL log files get truncated on backup.
It is quite normal that a CI environment gets quite many updates, and if your SQL is running in "Full" mode, this will grow your transaction log.
I would propose setting it to "simple". It will be slightly quicker and you'd not have unlimited growth.
Full Recovery Model without log backups is bad.
So, that's the most common reason for uncontrolled log growth? Answer:
Being in Full Recovery mode without having any log backups.
This happens all the time to people.
Why is this such a common mistake?
Why does it happen all the time? Because each new database gets its
initial recovery model setting by looking at the model database.
Model's initial recovery model setting is always Full Recovery Model -
until and unless someone changes that. So you could say the "default
Recovery Model" is Full. Many people are not aware of this and have
their databases running in Full Recovery Model with no log backups,
and therefore a transaction log file much larger than necessary. This
is why it is important to change defaults when they don't work for
your organization and its needs)
Source: https://dba.stackexchange.com/questions/29829/why-does-the-transaction-log-keep-growing-or-run-out-of-space
| How can I remove / delete Sitecore database log (*.ldf) files
Is there any special procedure to clear up large log files in Sitecore databases?
Our integration server has a huge (25GB) log file which I would like to dispose of, but not sure of the procedure.
On an aside, is a very large log file symptomatic of any particular problems?
| |
There's already answer to similar problem on Stack Overflow: https://stackoverflow.com/questions/21452260/sitecore-tree-list-datasource-versionexist
In a nutshell, what you need to do:
Create DataView which will be responsible for filtering non-existing items
LanguageFilteringMasterDataView : MasterDataView
Override method GetChildItems where you can filter out non-existing items
protected override void GetChildItems(ItemCollection items, Item item)
Register data view in configuration under dataviews node
<dataviews>
<dataview name="LanguageFilteredMaster" assembly="sc70" type="sc70.Controls.LanguageFilteringMasterDataView" Parameters=""/>
</dataviews>
and finally create custom TreeList control which will inherit from TreeList and connect your data view there
public class LanguageFilteringTreelist : TreeList
{
private const string DataViewName = "LanguageFilteredMaster";
protected override void OnLoad(EventArgs args)
{
base.OnLoad(args);
var dataContext = this.FindDataContext();
if (dataContext != null)
{
dataContext.DataViewName = DataViewName;
}
}
protected virtual DataContext FindDataContext()
{
if (this.Controls.Count <= 0)
{
return null;
}
var child = this.Controls[0];
return child.Controls.OfType<DataContext>().FirstOrDefault();
}
}
UPDATES from @josedbaez
The solution works on 8.1. The only difference from the original answer (so others know) is the javascript code. You do not need to make that change anymore as Sitecore now appends selected language to html like: <input id="FIELD9318757_all_Language" type="hidden" value="en-CA"> <input id="FIELD9318757_all_Language" type="hidden" value="en-CA">
Do not forget to register your new field type as MultilistField to the <fieldtypes> configuration (Found in "App_Config/FieldTypes.config" by default) so that the items referenced by the field are added to Link Database.
e.g. <fieldType name="LanguageFilteringTreelist" type="Sitecore.Data.Fields.MultilistField,Sitecore.Kernel" />
| How to filter items by language in Treelist field
On a multilingual site, how can I make a treelist field to only show items of selected language in the editor -so editors can't select items that do not have versions or shouldn't exist on their site.
We are needing this for a "taxonomy" field but some (could be lots) of them will only apply to specific language versions.
Is there a way to modify existing treelist so it can achieve this? Or if the answer is to create a new one, what should I override? Can't figure out what to modify.
| |
I'm sure I came across an example of linked drop downs in WFFM in the past but can't find find it now. This might be a good basis to start from: http://sitecoreguild.blogspot.co.uk/2013/06/sitecore-country-and-region-dropdowns.html
However you will obviously need to inherit from the right classes for your dropdowns to work, there is a good example here: https://divamatrix.wordpress.com/2011/12/20/wffm-custom-field-type-made-easy/
| WFFM: dynamically populated dependent drop lists
I have the requirement to create two lists: the second one being dynamically populated with Sitecore data after the user selects a value from the first one.
I tried using some Rules for WFFM but can't seem to match any with what I want to have as results.
I would like to have something like countries in the first list. After selecting a value, the second list will dynamically populate the regions depending on the country selected - if the country has regions, else a N/A single element will be added.
What is the best way and approach for doing this dependent drop lists functionality for a WFFM form (Sitecore 8.1 - webforms)?
| |
I wouldn't use Sitecore Powershell Extensions for this. SPE doesn't have anything for interacting with the clipboard and also doesn't execute custom JS from scripts (yet!).
Additionally, there already exists a command within Sitecore for copying the path to the clipboard, so all you need to do is assign it to a new button in the context menu.
John West has blogged about this here - https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/repost-add-a-command-to-the-sitecore-item-context-menu - but to summarise:
Create a new item of template System/Menus/Menu item under the item /Sitecore/Content/Applications/Content Editor/Context Menues/Default in the Core database.
This item should have the message field set to clipboard:copypathtoclipboard(id=$Target).
The command should then be executable from the context menu.
This message actually invokes a command, which is specified in Commands.config as Sitecore.Shell.Framework.Commands.Clipboard.CopyPathToClipboard,Sitecore.Kernel.
However, this command provided by Sitecore operates in Internet Explorer only. It specifically checks the browser and hides the menu option if it fails:
if (context.Items.Length != 1 || !UIUtil.IsIE())
return CommandState.Hidden;
This is because traditionally only IE had support for interfacing with the OS clipboard. Other browsers had to make use of Flash solutions.
However, there looks to be more modern solutions for handling clipboard usage in other browsers, if that is important to you. For instance there is this library - https://github.com/zenorocha/clipboard.js
If supporting other browsers is important, you will need to implement your own custom command. I would look at the source for the CopyPathToClipboard type and implement something similar that executes your custom JS when executed.
| How to create Sitecore Context Item to copy Item Path using SPE?
How to create Sitecore Context Item to copy Item Path using Sitecore PowerShell Extensions.
Like in below screen we have for Layout Copy Renderings and Quick download package. Sometimes it requires to copy item path and paste in the item's field such as Image field types.
It would be really quick for editors if they can copy Item Path or Item ID with right-click instead of opening the item and going back & forth many times.
| |
You can do this by making sure that your renderings are set to Vary by User. This adds the user to the cacheKey string like this "_#user:" + Context.GetUserName();
You can then use the following code to clear the html cache for that user:
// Need to clear the cache for the header and the user profile....
var htmlCache = CacheManager.GetHtmlCache(Context.Site);
// Remove all cache keys that contain the currently logged in user.
var cacheKeyPart = $"_#login:True_#user:{Context.GetUserName()}";
htmlCache.RemoveKeysContaining(cacheKeyPart);
For more detailed information have a look at this post: http://www.sitecorenutsbolts.net/2016/04/26/Advanced-Cache-Clearing/
| How do I clear the HTML cache for a specific user?
We have an action that updates some user profile information that is displayed in components that are cached with a vary by user setting. Is there a way to clear the cache for only that one user?
| |
You can try to open the standard values item with the Experience Editor and add the renderings you like.
If that doesn't work out, create an item based on the template, add the renderings and manually copy the values over to the standard values item.
| Predicting the placeholder for a dynamic placeholder
I am using the Dynamic Placeholders from Fortis, but need to setup a page template where the Dynamic Placeholders contains renderings. I am setting the page template up, by setting layout detail on the standard values of the page template.
I have been unable to succeed in this, since the dynamic placeholder is postfixed by a GUID which is generated. Is there a way to predict this GUID? According to the documentation, the GUID is generated using the following logic:
Dynamic Placeholders simply use the rendering ID to create a unique
placeholder name. If more than one dynamic placeholder with the same
name is in a rendering it will also append on an incrementing number
I tried another approach, by using a home brewed dynamic placeholder library, which just prepended the dynamic placeholder with a sequential number, e.g. row1, row2, row3. But this approach makes the content editors unable to move rows in the experience editor, since the content inside the row is tied to a fixed number, which changes when the rows are moved.
Disclaimer: This is posted at stackoverflow as well.
| |
One option is to hook into Sitecore's user:updated event (and optionally user:updated:remote). This event is raised when a user has been updated, the remote event handler is raised when a user was updated on a remote Sitecore instance.
EDIT: As pointed out in the comments by @SzymonKuzniak, you can also hook into the roles:usersAdded[:remote] event to specifically handle added roles. Likewise, there is also the roles:rolesRemoved[:remote] event.
Create a new configuration file and put it in App_Config\Include:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<events>
<event name="user:updated">
<handler type="Custom.UserUpdatedEventHandler, Custom" method="OnUserUpdated"/>
</event>
<event name="user:updated:remote">
<handler type="Custom.UserUpdatedEventHandler, Custom" method="OnUserUpdatedRemote"/>
</event>
</events>
</sitecore>
</configuration>
Create a class UserUpdatedEventHandler in the Custom namespace:
public class UserUpdatedEventHandler
{
public void OnUserUpdated(object o, EventArgs args)
{
var sitecoreArgs = (SitecoreEventArgs)args;
var membershipUser = (MembershipUser)sitecoreArgs.Parameters[0];
// Check user and roles
// Send e-mail
}
public void OnUserUpdatedRemote(object o, EventArgs args)
{
var sitecoreArgs = (SitecoreEventArgs)args;
var userRemoteEventArgs = (UserUpdatedRemoteEventArgs)sitecoreArgs.Parameters[0];
var userName = userRemoteEventArgs.UserName;
// Check user and roles
// Send e-mail
}
}
| How to send email, when users roles change - User Manager customization
I've been tasked with an interesting challenge. The client wants a user to be sent an email informing them when they have been assigned to a specific role by an Admin.
What will be the best way to go about this?
Is it possible to do this via Workflows? Or will other methods be required?
| |
Are you logged in as an Admin? Admins are not subject to workflow enforcement.
| Workflow not being applied
According to Sitecore's official documentation in order to set a workflow for items created from a template one have to set Default Workflow in the template's standard values.
Well I did just that and... nothing is happening. More specifically all the newly created items are created without workflow fields being set. Any ideas why?
I just set the Default Workflow field on the template's __StandardValues; all other workflow related fields are left empty.
What else is needed for the Workflow to be attached to new items? Why is the workflow not being initiated?
| |
I typically disable caching for my local environment by setting the HTML cache lifetime to 1 second using the following config patch:
<setting name="Caching.HtmlLifetime">
<patch:attribute name="value">00:00:01</patch:attribute>
</setting>
To make this specific to your local environment, you can patch it in using a configuration transforms or using a tool like Slow Cheetah
| Disable HTML cache for development
I am currently making code changes to a view rendering in Sitecore, and when a deploy these changes to my local environment, they were not visible. I realized that the rendering was marked as Cacheable, so I was seeing a previously cached version.
Besides unchecking Cacheable on the renderings I'm currently working on, what would be the best way to disable HTML caching for development?
| |
Ok. Well. Would definitely be possible to set something up with Unicorn for this - albeit it a highly unusual configuration. Steps I would take would look something like this:
Set up Unicorn on the CM box to serialize all of the web content you want to regularly push across to CD
This will ensure, the file system always has a copy of everything that is being published on CM
I would then use the same config on CD
Then, come time to publish:
Script a "publish". Since I'm no good with SPE, I would probably use gulp. Steps would or could be something like:
Zip up the Unicorn folder
FTP upload it (or any other means of transfer) to CD server
Delete CD servers Unicorn/** folder
Unzip uploaded file to CD servers Unicorn folder
Run Unicorn sync via its remote script capability
Rough outline at least. There could be any number of unforeseen consequences of this setup I'm not seeing right now; I've never attempted to set anything up like this.
Also; having all of these tools available on CD (Unicorn, Remote Scripting) might actually be a bigger security risk than a 1 way port SQL opening - but that's just my opinion of course.
| Publishing without SQL
What approach should I use to enable a customer to deploy content (just items) from their CM environment to a CD environment, where the CD environment would not allow any SQL ports through the firewall? Something like zipping up a package or serialization files, uploading that over HTTP, unpacking and installing it, and then clearing caches? It would be even better if this could be a single SQL transaction. Has anyone ever done anything like this? Maybe I'm missing something obvious. Could TDS, Sitecore Ship, Unicorn, SSC, or anything else assist here?
Because the customer might want to use the publishing service (https://dev.sitecore.net/Downloads/Sitecore_Publishing_Service.aspx) after they get to 8.2, any solution probably not depend on publishing pipelines. I'm not familiar enough with any of these technologies to make a recommendation.
Feel free to tell me to RSomeFM or blog posts or something. I would be happy to do some development; mostly looking for architectural and toolset suggestions.
| |
Pipeline Method:
Option 1:
Deep in the bowels of Experience Editor, you will find that eventually, the Move Component button is enabled/disabled based on the Allowed Renderings set on the placeholder. You could add a processor to the getPlaceholderRenderings to weed out the rendering you are looking for so that it acts like a static rendering. But keep in mind, that will cause Experience Editor to act like you can't put more of that control in the placeholder.
Option 2: Another Pipeline called getChromeData is what Experience Editor uses to control almost the entirety of the look and feel of itself. This controls the features for placeholders, fields, edit frames, and sublayouts/renderings. Mucking with a processor in this option might be the best from an upgrade-ability point of view
God-Mode Method:
For more control over the use of the options in Experience Editor, like the Move Component, another option is to create your own click method and either change the default rendering button, or create your own button.
You can achieve this by looking in the Core Database and finding this item:
The particular chrome:rendering:sort command is actually handled in the RenderingChromeType.js file in the "Page Modes" application within the /sitecore/shell directory.
handleMessage: function(message, params, sender) {
switch (message) {
case "chrome:rendering:sort":
this.sort();
break;
You can augment this Javascript file to do what you want. However, beware that editing this javascript file could lead to upgrade stress in the future.
Another option that could be available to you is to create your own custom command, and patch it in. For example, if you set the click to be chrome:common:edititem({command:"webedit:validatesortablerendering"}) where webedit:validatesortablerendering is a custom command that you patch in, you can test the rendering type first (basically it would be the template type of the datasource item). If this is not a rendering that can be sorted, then abort further action. If it is, then call the Sitecore Javascript trigger to act on the event chrome:rendering:sort
In Summary:
There are a few ways to shave this yak. I think Pipeline Method Option 2 might be the best option, but it really depends on what your overall objective is and how destructive you want to be to Sitecore.
| Disabling 'Move Component' in Experience Editor for a specific rendering
Is it possible to disable an option, Move Component, in the Experience Editor, for a specific rendering?
I have looked at the rendering and rendering options, but neither gave the possibility. I have also looked into user rights, but to no avail.
I have attached a picture of the button:
| |
Not sure if it is possible to call RegisterForEventValidation from inside RuleAction.
You can try different approach. Instead of adding your values from javascript add all possible values into dropdown on WFFM form designer and then hide some of them with javascript. Thanks to this you will not have to register any values for valudation.
| ClientScript.RegisterForEventValidation in a custom RuleAction class
I managed to have my dependent droplists (WFFM dependent drop lists) populated via a custom WFFM RuleAction by using a lot of JavaScript but now since I add dynamically the values in my second droplist when I submit the WFFM form I get the error:
Invalid postback or callback argument.
As I read on stack some questions and answers I came to the conclusion that I need to register all my dynamic values I add to this list by using ClientScript.RegisterForEventValidation(unique id, value) but it seems this has to be made in a Render() method of the control.
I searched a method to overwrite or to make a call to some method in my custom RuleAction but haven't found anything.
Does anyone knows how can I make the call to RegisterForEventValidation method in a RuleAction class or at least disable the droplist validation so I could press the submit button and don't get the validation error?
Edit:
I found a way I could get my values registered but I get an error:
Demo code:
public class ChangingDropListPopulatesDropList<T> : RuleAction<T> where T : ConditionalRuleContext
{
public override void Apply([NotNull] T ruleContext)
{
Assert.ArgumentNotNull(ruleContext, nameof(ruleContext));
if (((ruleContext.Control == null) || !ruleContext.Control.Visible) && (ruleContext.Model == null))
{
return;
}
if (ruleContext.Control != null)
{
...
ruleContext.Control.SetRenderMethodDelegate(this.RenderCustom);
}
}
protected void RenderCustom(System.Web.UI.HtmlTextWriter writer, System.Web.UI.Control Container)
{
}
}
The error I get is:
The Controls collection cannot be modified because the control
contains code blocks (i.e. <% ... %>).
| |
If your content authors are strictly following WorkFlow, use scheduled Incremental publishes.
If workflow is not strictly used, use user manual publishes (Smart Publish), and try to cover related item publishes to reduce number of cache clears.
For multisite, if you publish item of site-A. It will clear html cache for all sites. It should clear cache for site-A only.
For this, you must customize the publish:end:remote event. For that, find the root item got published (on CD server), identify which site the item related is, and clear HTML cache for that site only. This case is nicely explained in "Sitecore Cookbook for Developers". Still, here is the code for that (Add this processor to the event and replace existing one):
protected void ClearCache(object Sender, EventArgs args) {
PublishEndRemoteEventArgs pubArgs = (PublishEndRemoteEventArgs) args;
string rootID = pubArgs.RootItemId.ToString();
Database db = Database.GetDatabase(pubArgs.TargetDatabaseName);
Item rootItem = db.GetItem(rootID);
if (rootItem != null)
ClearHtmlCache(rootItem);
}
private static void ClearHtmlCache(Item rootItem) {
List<SiteInfo> sites = Factory.GetSiteInfoList();
var selectedSites = sites
.Where(s => rootItem.Paths.Path.ToLower().StartsWith(
s.RootPath.ToLower()) && s.Database.ToLower() == "web");
foreach(SiteInfo site in selectedSites) {
ClearSiteHtmlCache(site);
}
}
private static void ClearSiteHtmlCache(SiteInfo site) {
string cacheName = site.Name + "[html]";
Cache cache = CacheManager.FindCacheByName(cacheName);
if (cache != null)
cache.Clear();
}
| How should I configure publishing on Sitecore 8.2+?
What are the best practices for publishing configuration on Sitecore these days, especially given the performance improvements on 8.2 when using the new publishing service?
Scheduled incremental publishes?
Workflow based publishes?
Allow manual user publishes?
Something else?
This is a multi-site scenario that will have ongoing site builds even after initial launch. So content will be updated frequently. I would like to minimize HTML cache clears and as much as possible make it easy for authors to ensure they publish all needed items.
| |
The matching can happen immediately. Here's how it works:
In a very basic case, you might have 2 values that are being considered: color and shape. A visitor can prefer red over green, and circles over triangles. There are 4 combinations: red circles, red triangles, green circles and green triangles.
A visitor starts with no preference:
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
The more pages the visitor views that are labeled as red, the more the visitor's color score goes in that direction.
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
If the visitor views green pages, that starts to affect the visitor's color score:
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
Notice in the above diagrams that the visitor is only moving up and down.
The same sort of thing happens when the visitor views pages that suggest a preference for circles or triangles. The visitor starts with no preference:
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | S | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
The more pages the visitor views that are labeled as triangle, the more the visitor's shape score goes in that direction.
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | | | S |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
If the visitor views circle pages, that starts to affect the visitor's score:
+--------------+--------+---------------+---------+-----------------+----------+
| red | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | | S | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
Now imagine you have two pattern cards: P1 strongly prefers red, and slightly prefers circles. P2 has no shape preference and a slight preference for green.
+--------------+--------+---------------+---------+-----------------+----------+
| red | | P1 | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly red | | | C | | |
+--------------+--------+---------------+---------+-----------------+----------+
| neutral | | | | S | |
+--------------+--------+---------------+---------+-----------------+----------+
| mostly green | | | P2 | | |
+--------------+--------+---------------+---------+-----------------+----------+
| green | | | | | |
+--------------+--------+---------------+---------+-----------------+----------+
| circle | mostly circle | neutral | mostly triangle | triangle |
+--------+---------------+---------+-----------------+----------+
Sitecore needs to determine whether the visitor's combined color and shape score is a better match for P1 or P2. Sitecore does this by using math. It calculates the physical distance between the color score and the shape score from P1 and from P2. Whichever distance is shorter, that is the match.
In this simple example you can see that P1 is 2 steps from the visitor's color score (1 step up and 1 step left), and is 4 steps from the shape score (2 steps up and 2 steps left).
P2 is also 2 steps from the visitor's color score (2 steps down), but only 2 steps from the shape score (1 step left and 1 step down).
It takes 6 steps to get from the visitor's profile scores to P1 and 4 steps to get to P2. So P2 is the better match.
It's easy enough to calculate the distance when you are dealing with 2 dimensions (color and shape). But imagine having 5 or 6 or more. This is where linear algebra comes in. Sitecore handles the math, but the basic idea is the same.
For those of you mathematically inclined, by default, Sitecore calculates the squared euclidean distance to determine the best match. This is implemented in a Sitecore.Analytics.Patterns.IPatternDistance. If you have a different approach you want to use, you can create a custom implementation of this interface.
| How does Sitecore "match" a pattern card for personalization?
I understand the basic concepts of pattern cards and profile keys. But how does Sitecore determine that a user matches a particular pattern card? How many pages tagged with that card does a user need to browse before matching it? And what if the user browses pages tagged with other pattern cards?
| |
An options could be not to use courier, but to use TDS delta builds, considering the fact that you already use TDS, by going back to a certain date in time. This will also keep the packages small.
You could, by the way, use TDS package deployer to automatically install these packages as well.(https://github.com/HedgehogDevelopment/SitecorePackageDeployer)
| How should Courier be used as part of a CI build?
I am looking at an existing setup of Sitecore that is using Courier as part of a continuous-integration process.
The process is currently:
Commits to a particular branch kicks off a Team City build
The build contains a TDS project of serialized items
Courier is executed to generate an .update package that compares the current state of serialized items to a copy of last state of serialized items
The .update packaged is NuGet packed along with the Website build for Octopus Deploy
Finally, the current serialized items are copied to be compared against during the next build
The advantage of this is that the .update packages generated are very lean. However, they completely depend on the previous Octopus Deploy deployment having succeeded as they are assuming the current state of items in Sitecore. If a build fails, or is even skipped, then successive builds won't be correct.
Is this a typical use of Courier, even with this problem?
A more robust method could be to just package and deploy all serialized items and then use Courier as part of the deployment process (rather than build) to generate an .update package at deployment, perhaps against a previous collection of serialized items that was known to be installed without error.
Is there a means of doing this efficiently that compares to the live database without having to rely on a previous set of serialized items?
| |
In the Media Library there is a “List Manager” folder present in the Vanilla installation of Sitecore 8.1 Update-3. You can plainly see it here:
If this folder goes missing, or is not present, the CSV Upload Wizard will error out like described in the question.
This situation occurred after an upgrade was completed in a stage environment, but then a package containing client media library items was "overwritten" removing this and some other System items.
| List Manager errors on any CSV Upload
In Sitecore 8.1 List Manager (and confirmed in Sitecore 8.2), the List Manager CSV Import Wizard Dialog appears as though to throw an error, even though no error message box appears. The only way to notice that an error is occurring is that the upload dialog box is outlined in red and that the Next Button is not accessible.
How do you fix this error?
| |
I have never seen this before but here are some ideas I would try:
Compare the security provider configuration on Coveo's admin tool against a working box looking for misconfigurations;
Set this coveo user(temporarily) as a sitecore admin and see if this fixes the issue;
Another thing I would try would be to go to the security configuration on the admin tool(http://youradminhosturl:8081/Configuration/Security/Security.aspx?sm=Roles) and add the coveo user as system administrator with full access on the index browser.
| Coveo user in a new Sitecore 8.1 update 3 instance gets locked consistently
I have cleared the security cache on Coveo several times, verified the certs, the encryption key and the Coveo license.
I have also verified the password hash and physically gotten on the master and the mirrors of Coveo to reach the CM server in the config.
But yet we see a lot of traffic going to the core db to authenticate the Coveo user.
Has anyone else had these issues before?
Sitecore 8.1 update 3
Coveo July 2016 release (8388)
| |
The AutoMap and AutoMapSource fields are used to configure automatic mapping of the contact identifiers:
When configured, one does not have to select a File field manually in a dropdown. The auto-mapped field is hidden on UI and the value for that field is taken from another field marked as AutoMapSource.
By default, 'Email address' is used as a source for the contact Identifier field.
| List Manager CSV Upload Import Field AutoMap settings not working
In Sitecore 8.1 (and 8.2) List Manager, we want to customize the data that we upload through CSV into custom Contact facets.
This question is not asking how to add facets, and assumes that I have already correctly added facets to my contact model.
In order to do so, we have to add a ImportModelField item under the ImportModel on the ImportWizardDialog box.
Question: I have not been able to figure out how/why the AutoMap or AutoMapSource check boxes exists. Does anyone know how to use this appropriately?
Findings Thus Far:
When AutoMap is checked, the field is hidden from the Map modal above. However, the data stored in the facet (noted by DataField) ends up being an email address, no matter how I attempt to map it.
When AutoMapSource is checked, it doesn't appear as though anything really auto maps since I have to map the field anyways through the Map dialog.
When both are checked, I just get an email address where I would've expected data from the CSV.
ASSUMPTIONS
I have validated that the CSV file uploads as expected into the associated facets when I manually map the File field to the Sitecore Field.
I assume and would expect that if my "FieldName" and CSV Header are identical, it should map. (It appears this is a false assumption)
| |
Typically empty + null values are not stored in the Lucene index, it's really designed for queries that are finding data rather than the absence of it. If you searched for +fieldName:* then that should find documents which have an entry (and therefore value) for fieldName.
I'm not entirely sure how the query-builder maps the query, it looks like judging by your example what you'd want is +custom:fieldName|*
If this doesn't work, Sitecore does have a mechanism of allowing you to specify a string value that takes the place of empty / null when indexing, therefore giving you something to search for. To do this you will need to add the field to the index manually in your indexing configuration, specifying the string to use as the "empty" value:
<field fieldName="title" storageType="NO" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String"
nullValue="NULLVALUE" emptyString="EMPTYVALUE" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider" />
You should then be able to filter these documents out of a search using -custom:title|NULLVALUE -custom:title|EMPTYVALUE.
A drawback with this approach is that you want these two strings to be values that your field value will never genuinely be!
More information can be found here - https://doc.sitecore.net/sitecore_experience_platform/developing/developing_with_sitecore/search_and_item_buckets/queries_for_null_or_empty_strings
| Filtering results when field is empty with query builder fields
How I can use sitecore query fields to filter and not bring results if a specific field is empty?
I have tried something like this:
location:{41c52cce-69cc-444d-b505-044addf0d9e1};-custom:title|''
I have also tried double quotes but I get the same result
thanks
| |
If you want to get the building query and attach filters to the search you can do something like this:
Coveo.$('#search').on("buildingQuery", function(e, args) {
args.queryBuilder.advancedExpression.add('@Model.ToCoveoFieldName("templatename") == "MyTemplate"');
}).coveoForSitecore('init', CoveoForSitecore.componentsOptions);
in this case you can change the advanced expression with what you need.
If you want to monitor the state of your custom facet and perform custom actions based on the state change you can do something like this:
$('.CoveoFacetDropdown').on('state:change', function() {
//execute new query
$('#search').coveo('executeQuery');
});
| Refining/executing query with Coveo
Going by the examples out of the box in Coveo, I always see this bit to construct the query:
Coveo.$(function() {
Coveo.$('#search')
.on(Coveo.QueryEvents.buildingQuery,
function(e, args) {
I want to add essentially my own faceting system to this, but not using OOTB facets necessarily, mostly due to design. I have "tabs" that are dropdowns essentially, with checkboxes, and after the user selects whatever series of boxes they'll go with, they click an "apply" button.
When the button is clicked, I know using Coveo.$("search").coveo("executeQeury") will kick off a new query, but I'm confused as to how to access the query builder for either refining my starting point, or just generating a new query based on the "facets" involved.
I feel like I'm missing something obvious, but any help would be appreciated. Thanks.
| |
So this depends on what you mean by predictive search.
If you mean a simple autocomplete, then yes. Sitecore provide an n-gram analyzer for both Lucene and Solr. To use this, add a new field to the index and map the field to use the n-gram analyzer instead of the default. You will need a custom computed field and an update to the schema.xml - see this post for more detail: http://www.ehabelgindy.com/sitecore-7-solr-search-auto-complete-using-ngram/
If you mean a full predictive and smart search "like" Google, then not out of the box with Sitecore. There are a few options to be able to do this tho.
Coveo
The most straightforward would be to use Coveo for Sitecore. Coveo offers a few cool features that you can plug into Sitecore, predictive search/auto complete looks to be included in that.
Custom Implementation
You can roll your own implementation of this using either the Lucene or Solr indexes. I would suggest that you use Solr for this as it has some nice features in the API that you would have to implement yourself with Lucene.
Doing a custom implementation is pretty complex tho, you would need a custom index, custom crawler to make sure that the correct page content was included etc...
Although I'd like to put the whole answer here, its would be a bit long, so here are some links to instructions:
http://www.cominvent.com/2012/01/25/super-flexible-autocomplete-with-solr/
If you can be more specific with the requirements, we can tailor the answer to your needs.
| Do we have predictive search capability within Sitecore?
I'm looking for predictive search for content page in Sitecore.
Something similar, what google search provide. Do we have anything like this?
| |
You can configure Sitecore to respond to requests with different home nodes based on the url.
To do so, you need to perform the following steps:
Configure DNS appropriately.
Add a binding in IIS for each hostname.
Copy or rename the config file App_Config/Include/SiteDefinition.config.example to App_Config/Include/SiteDefinition.config
Modify the config file from step 3 with a new <Site> node for each site.
For example:
<!-- this entry will respond to http://site1.hostname.com/mysite with the /Sitecore/sites/mysite/home node -->
<site name="SiteName" patch:before="site[@name='website']"
hostName="Site1.hostname.com"
virtualFolder="/mysite"
physicalFolder="/"
rootPath="/sitecore/sites/mysite"
startItem="/home"
database="web"
domain="extranet"
allowDebug="true"
cacheHtml="true"
htmlCacheSize="50MB"
enablePreview="true"
enableWebEdit="true"
enableDebugger="true"
disableClientData="false"/>
For more information see: https://sdn.sitecore.net/Articles/Administration/Configuring%20Multiple%20Sites/Configuring%20Sites%20in%20web,-d-,config%20File.aspx
| How do I configure Sitecore to serve multiple sites?
I want to configure my instance of Sitecore to respond with different sites at different urls. How can I do this?
| |
I don't have Sitecore 7.5 with WFFM module installed but this is listed as known bug in Sitecore knowledge base site.
It was fixed in WFFM 8.0 Update-2 as mentioned in the link above.
[Fixed in WFFM 8.0 Update-2] It is not possible to translate form in Form Designer. 'Language' dropdown doesn't show languages (24964).
| Why can't I select a different language for a form in WFFM?
I have Sitecore 7.5 with Webforms for Marketers 2.5. I want to create a form in the French language. However I can't seem to select French as a language. When I open up the form designer there is a button and a dropdown to select a language other than English. However when I click on it nothing happens. I have a number of languages installed in this Sitecore instances. I have EN, de-DE, es-ES, fr-FR and zh-CN. I click on the button or the dropdown to select a language and literally nothing happens. No error message or anything. But also no way to select a different language for the form. Am I doing something wrong? Below is a screen shot of the button/dropdown in the form designer.
| |
As a workaround, please perform the following steps:
Create a backup before making any changes.
Serialize the problem item (Developer > Serialize > Serialize Item).
Open the created file (Data\serialization\dbname\itempath\itemname.item) with a text editor and set the master parameter:
Master: {00000000-0000-0000-0000-000000000000}
Save changes.
Revert the item in Sitecore (Developer > Serialize > Revert Item).
For more information see sections 2.2.2 (Serializing Items) and 2.4.2 (Reverting Items) of the Sitecore Serialization Guide.
| How do I fix a broken 'Created from' reference when the branch no longer exists?
We're using Branches in Sitecore 8.1 rev. 160519 when creating new pages. However, at some point a branch item was lost in all of our environments, possibly because of a bad package, since the item doesn't exist in the recycle bin.
This has resulted in a number of items displaying when we scan for broken links, since the Created from field is no longer pointing to a valid item, and is displaying the following in the Content Editor:
"[branch no longer exists] - {00000000-0000-0000-0000-000000000000}"
The pages themselves work without issue, so this seems to be an issue just behind the scenes, that doesn't actually impact rendering. However, we would like to fix these broken references.
How can we go about correcting this broken link? We've recreated the branch, so ideally we'd like to point to that, or just remove the reference (as that seems to be fine, based upon other items in Sitecore).
I've tried looking at the items via an older version of Razl (2.5) as well as the current version of Sitecore Rocks.
| |
This agent uses the database referenced by the reporting connection string. Check if you see a Properties table in this database. If the table is missing, you can create it with this SQL statement:
CREATE TABLE [dbo].[Properties](
[PropertyId] [uniqueidentifier] NOT NULL,
[Key] [nvarchar](100) NOT NULL,
[Value] [ntext] NOT NULL,
PRIMARY KEY CLUSTERED
(
[PropertyId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
A missing table may indicate that there are more incorrect things. Solving this may popup other errors. Make sure you have executed all steps when you performed the upgrade, especially those related to databases.
If the table is there, make sure the user defined in the connection string has access to it. You can test this by signing in with a SQL client (e.g. MS SQL Management Studio) with the username and password from the reporting connection string. Try to execute the select statement from the error.
| Invalid object name 'Properties' Exception when executing agent experienceAnalytics/reduce/agent
We are getting the following error message in our Sitecore log file. We can not tell if this is breaking anything though, as the site appears to work as expected.
This is occurring after an upgrade from 7.2 to 8.1 U3.
8608 19:42:09 ERROR Exception when executing agent experienceAnalytics/reduce/agent
Exception: System.Exception
Message: Invalid object name 'Properties'.
Source: Sitecore.Kernel
at Sitecore.Data.DataProviders.Sql.DataProviderCommand.ExecuteReader()
at Sitecore.Data.DataProviders.Sql.DataProviderReader..ctor(DataProviderCommand command)
at Sitecore.Data.DataProviders.Sql.SqlDataApi.<>c__DisplayClass12.<CreateReader>b__10()
at Sitecore.Data.DataProviders.NullRetryer.Execute[T](Func 1 action, Action recover)
at Sitecore.Data.DataProviders.Sql.SqlDataApi.CreateReader(String sql, Object[] parameters)
at Sitecore.Analytics.Aggregation.SqlReportingStorageProviderProperties.GetProperties()
at Sitecore.Analytics.Aggregation.SqlReportingStorageProviderProperties.get_Item(String key)
at Sitecore.ExperienceAnalytics.Reduce.TimestampStore.get_LastRun()
at Sitecore.ExperienceAnalytics.Reduce.ReduceAgent.IsDue()
at Sitecore.ExperienceAnalytics.Reduce.ReduceAgent.Execute()
at Sitecore.Analytics.Core.BackgroundService.Run()
Nested Exception
Exception: System.Data.DataException
Message: Error executing SQL command: SELECT [Key], [Value] FROM [Properties]
Nested Exception
Exception: System.Data.SqlClient.SqlException
Message: Invalid object name 'Properties'.
Source: .Net SqlClient Data Provider
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource 1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Sitecore.Data.DataProviders.Sql.DataProviderCommand.ExecuteReader()
| |
Because Sitecore does not provide you the hooks to validate the transaction you're after, your best bet is to hide the security features and manage them in code. Here's a few suggestions that aren't too onerous to implement.
Prerequisite: Lock Sitecore Users out of Security Features
Make sure no one has access to Sitecore Client Securing
Make sure no one has the Administer right on any Items.
Create Security Privileges as part of Item Creation
There are probably some basic conventions to your security scheme. Assuming something Helix/Habitat like, you probably have roles to manage Tenants, Site Groups and Sites.
When a new scope object is created (Tenant, Site, etc) consider creating the security roles for it as part of the Item Created process, then assigning the new roles the appropriate rights. This could either be done with an Item Created/Saved rule or a Branch Template. All that's left is to assign users to roles.
Consider some sort of Security Facade
You could create some sort of settings Items that represent actual Security roles and using a system of multilist fields on Items that need securing, allow content authors to perform security themselves through the facade. On Item:Saved, you then read these fields and make the necessary changes through the actual Security API.
| Restricting Item Access Rights to Roles - Prevent Users from being assigned Access Rights directly
Best practice is to assign access rights to roles rather than users. So I would like to block changes that apply access rights for users. Sitecore does not seem to trigger the saveUI pipeline on access right changes, so I think I should use an event handler. One of my concerns is that SheerUI might not always be available. This seems to work, though I haven't tried it from an API call with no SheerUI context.
One issue is that if a UI user has made significant security changes, they will lose their work because I do not think I can confirm, only alert, and then in the case of Security Editor, the UI does not refresh.
Please comment on this approach, especially anyone who has experience with SheerUI from an event handler. Is this just a bad idea, or is there some better way?
namespace Whatever.Tasks
{
using System;
using Sitecore.Diagnostics;
using Sitecore.Data.Items;
using Sitecore.Events;
using Sitecore.Globalization;
using Sitecore.Security.AccessControl;
using Sitecore.Security.Accounts;
using Sitecore.SecurityModel;
using Sitecore.Web.UI.Sheer;
public class PreventUserAccessRights
{
protected void OnItemSaving(object sender, EventArgs args)
{
// data being saved
Item itemInMemory = Event.ExtractParameter(args, 0) as Item;
Error.AssertNotNull(itemInMemory, "itemInMemory");
// probably not needed
using (new SecurityDisabler())
{
// ignore event if no changes to security field
Item itemInDatabase = itemInMemory.Database.GetItem(itemInMemory.ID);
if (itemInDatabase == null || itemInMemory[Sitecore.FieldIDs.Security]
!= itemInDatabase[Sitecore.FieldIDs.Security])
{
foreach (AccessRule accessRule
in AccessRuleCollection.FromString(itemInMemory[Sitecore.FieldIDs.Security]))
{
if (accessRule.Account.AccountType == AccountType.User)
{
// block the save
SitecoreEventArgs scEventArgs = args as SitecoreEventArgs;
if (scEventArgs != null)
{
scEventArgs.Result.Cancel = true;
}
string msg = Translate.Text(
"Hey bro, you cannot assign access rights for users, only roles: ") + accessRule.Account.Name;
// try to alert the user
try
{
SheerResponse.Alert(msg);
}
catch (Exception ex)
{
// maybe thrown if SheerUI missing?
throw (new ApplicationException(msg));
}
if (scEventArgs == null)
{
// unlikley/impossible case,
// but would still want to prevent the save
throw (new ApplicationException(msg));
}
return;
}
}
}
}
}
}
}
| |
An alternative to using .net code or storing logs in the database:
We used the forfiles command for things like this. Place the command(s together) in a batch file and have that executed as a scheduled task on the server. Works fast and puts no extra load on your .net application.
You can delete files with it (based on date), adding zip functionality (e.g. with 7zip) should be fairly easy.
E.g. to delete all .log files in a path, last modified as least 5 days ago:
forfiles /S /P <path> /M *.log /D -5 /C "cmd /c del /q @path"
In the command (cmd) you could
More info on the parameters: https://technet.microsoft.com/en-us/library/cc753551(v=ws.11).aspx
| Zipping/archiving old log files?
Some time ago I wrote a blog post about rolling the Sitecore logs:
Now I'm on a project that wants to keep their logs for 3 years, but doesn't want to use disk space. I modified it from an initialize pipeline processor to an agent and to compress the logs to a different directory.
Is there a better way than current solution as below? Or alternative solutions that would work outside the Asp.Net process?
<agent type="Whatever.Tasks.LogFileManager" method="Run" interval="00:00:30"/>
<minAge>00:00:30</minAge>
namespace Whatever.Tasks
{
using System;
using System.IO;
using Sitecore.IO;
using Sitecore.Configuration;
using Sitecore.Zip;
public class LogFileManager
{
// files must be this old
public TimeSpan MinAge { get; set; }
public void Run()
{
// where the logs are
string logDirectory = FileUtil.MapPath(Settings.LogFolder);
// where the zip files go
string archiveDirectory = Path.Combine(
FileUtil.MapPath(Settings.DataFolder),
"logArchive");
// where the log files will go temporarily (possibly avoided)
string tempDirectory = Path.Combine(
archiveDirectory,
Sitecore.DateUtil.IsoNow);
if (!Directory.Exists(tempDirectory))
{
Directory.CreateDirectory(tempDirectory);
}
foreach (string file in Directory.GetFiles(logDirectory))
{
// check min age only if needed
if (this.MinAge > TimeSpan.Zero)
{
FileInfo fileInfo = new FileInfo(file);
DateTime check = fileInfo.LastWriteTimeUtc > fileInfo.CreationTimeUtc
? fileInfo.LastWriteTimeUtc
: fileInfo.CreationTimeUtc;
if (DateTime.UtcNow - check < this.MinAge)
{
continue;
}
}
try
{
File.Move(file, tempDirectory + "\\" + Path.GetFileName(file));
}
catch (IOException)
{
// locked, probably to ASP.NET?
}
}
// if there are no files in the temporary directory,
// don't create the zip file.
if (Directory.GetFiles(tempDirectory).Length > 0)
{
string zipFile = tempDirectory + ".zip";
using (ZipWriter zipWriter = new ZipWriter(zipFile))
{
foreach (string file in Directory.GetFiles(tempDirectory))
{
using (FileStream fileStream = File.OpenRead(file))
{
zipWriter.AddEntry(FileUtil.GetFileName(file), fileStream);
}
}
}
}
Directory.Delete(tempDirectory, true /*recursive*/);
}
}
}
| |
This one supports 8.0+ https://marketplace.sitecore.net/SearchResults#qr=helpfullcore - it works similar to the original Wildcard module, but doesn't use the rules engine to process the tokens.
You can view the documentation on it here: https://vladimirhil.com/2016/02/22/wildcards-module-for-sitecore-7-using-content-search-api/
| Availability/Upgradeability of Wildcard Module for Sitecore 8+
I'm trying to get hold of a version of the Wildcard Module for Sitecore 8.1. Unfortunately the version on the Marketplace (https://marketplace.sitecore.net/en/Modules/Wildcard_module.aspx) only goes up to v6.5.
Is there a version of the Wildcard Module that is updated for Sitecore 8 or above? or an alternative option to use for Wildcards with Sitecore 8+?
How can I use wildcards with Sitecore 8+?
| |
We use a bunch of Marketplace Modules within our solutions usually. The way we use them heavily depends on how well the module is maintained but the general procedure that we use is to source code control the DLL's and any patch configs associated with the module.
This allows the bits and configs to get transferred to each environment by deployment processes.
As for items, we generally will install the package once on each authoring environment and then do the appropriate publishing as described in Module documentation of any.
| Should we source control Sitecore modules?
Once the right Sitecore module has been chosen, we need to sync all environments including developer, dev, test, prod etc.
I'm thinking whether we should include items on to TDS and patch files on configuration etc.
Is this a best practice or should we avoid it? Also not sure, how we could include to module Dlls? (I guess just include a reference to it in the web project?)
| |
If you have not already used a base template with presentation, this will be tricky. Normally I would have a base page template with some core presentation elements and then all other page templates would inherit from that - also I try to have very few page templates.
For your problem you are probably going to have to add the element to the standard values on your page templates.
You could script this with Sitecore PowerShell Extensions using something similar to this:
$item = get-item master:\content\Demo\Int\Home
$device =Get-Device -Default
$contentDataSource = get-item master:\content\Demo\Int\Home\about-us\employee-stories\adam-najmanowicz
$ImageDataSource = get-item master:\content\Demo\Int\Data\Images\d56cf7e777a2496aa6489a7bffc03539
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Content
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -Parameter @{FieldName ="Title"} -DataSource $contentDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Image
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -DataSource $ImageDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Subtitle
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main -DataSource $contentDataSource
$rendering = get-item master:\layout\Sublayouts\ZenGarden\Basic\Title
Add-Rendering -Item $item -Device $device -Rendering $rendering -Placeholder main
Source: Adam Najmanowicz Gist.
This should serve as a good starting point. Here is the documentation of the Add-Rendering function:
https://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/content/appendix/commands/Add-Rendering.html
Credit to @pascal-mathys for this answer on this question
| Best way to add rendering in base template and inherit
We are 80% from the completion of the project. And noticed that we need to create a couple of renderings that must exist on all pages.
I thought the best place to do this would be presentation detail of base template standard values. However, it appears that when you add rendering you need to also choose layout as well.
Questions:
Are Sitecore templates designed to inherit the presentation details of base templates?
If above is yes, how do we handle a scenario where inherited templates can have different layouts?
If no, what's the best way to solve this issue?
I've faced this issue a couple of times, where I ended up adding the rendering to all the page templates one by one :-).
Any best practices appreciate.
| |
Are you using shared database user for mongoDB? Make sure to grant it read rights.
Refer:
https://blog.horizontalintegration.com/2015/04/09/sitecore-8-xdb-using-shared-users-on-mongodb/
| "not authorized on config to execute command" Error when rebuild path analyzer from historical data
When trying to rebuild path analyzer from historical data the following error appears in log file:
16916 2016:09:21 08:50:19 ERROR [Path Analyzer] BuildMapAgent failed
Exception: MongoDB.Driver.MongoCommandException
Message: Command 'count' failed: not authorized on config to execute command { count: "chunks", query: { ns: "usd_analytics.Interactions" } } (response: { "ok" : 0.0, "errmsg" : "not authorized on config to execute command { count: \"chunks\", query: { ns: \"usd_analytics.Interactions\" } }", "code" : 13 })
Source: MongoDB.Driver
at MongoDB.Driver.Operations.CommandOperation`1.Execute(MongoConnection connection)
at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command, ReadPreference readPreference, IBsonSerializer resultSerializer, IBsonSerializationOptions resultSerializationOptions)
at MongoDB.Driver.MongoCollection.RunCommandAs[TCommandResult](IMongoCommand command, ReadPreference readPreference)
at MongoDB.Driver.MongoCollection.Count(CountArgs args)
at Sitecore.Analytics.Processing.Tasks.MongoDbSequenceFactory2.CreateInteractionSequence(InteractionHistoryRangeDefinition range)
at Sitecore.Analytics.Processing.Tasks.MongoDbSequenceFactory2.GetSequence[TKey](ObjectRangeDefinition range)
at Sitecore.Analytics.Processing.Internals.SchedulerFactory.InitializeScheduler[TWorkItem](Guid taskId, ObjectRangeDefinition range)
at Sitecore.Analytics.Processing.TaskManager.StartDistributedProcessing[TWorkItem](ObjectRangeDefinition query, DistributedWorker`1 worker, TaskOptions options)
at Sitecore.PathAnalyzer.Processing.Agents.BuildMapAgent.ScheduleRebuild(List`1 definitions)
Any ideas of how to solve this error?
| |
This might be slightly off topic, but I can give you a bit of background info.
In EXM 3.3 you can move/change the email open handler by modifying the configuration setting EXM.OpenHandlerPath in Sitecore.EmailExperience.Core.config.
The EXM 3.3 open handler does not require the tracker. It creates an interaction using the interaction registry. See Register interactions using the interaction registry.
There is a way in EXM 3.3 to convert legacy query strings into the new query string format. This is done in the transformQueryString parameter, but you'll need to enable the DecryptLegacyQueryString processor. The email open handler is already using this pipeline, but the legacy querystring processor is disabled by default.
| What are the implications of setting EnableTracking to True for "modules_shell" site?
In ECM 2.2, the RegisterEmailOpened.aspx was located in sitecore_modules directory, which is mapped to the Sitecore site "modules_shell". In EXM 3.3, this page is moved to /sitecore/ and made an ashx. Okay, cool...
Method #1: Use URL Rewrite to redirect to the new location. For whatever reason, whether it's stupidity or lack of regex understanding, I could not get a rewrite rule to redirect. Aborted.
Method #2: Created an aspx page in the same location to force a redirect. Turns out, this is the method I REALLY want to do, because before doing the redirect, I've realized that I need to do work to convert the query params from ECM 2.2 to EXM 3.3 query params before going to the new EXM 3.3 location -- Therefore, this is actually the method I want to use. but having complications.
Issue: The complications are that I need to instantiate the Sitecore Analytics Tracker in order to identify the user and create an Xdb Contact record if one doesn't exist. But "modules_shell" has EnableTracking set to false in the Site Definition.. (to wit I'm assuming is for a reason), meaning that the "startAnalytics" pipeline aborts out before creating the Tracker.
Research: I thought it was because I have a blank for Analytics.The hostname for the longest, but it's actually not even getting to that point. That may still be an issue, and figuring out how I need to set Analytics.Hostname for a multisite environment is my next research question.
Is there any reason why I WOULDN'T want to set EnableTracking true on the modules_shell site in Sitecore?
| |
ClusterName is a value of the cluster address to which a server belongs. The name should be identical for all content delivery servers that are in the same cluster. I usually use a string here, not a hosname. I believe this has nothing to do with multisites URLs.
EXM documentation states:
Ensure that the value of the Analytics.ClusterName setting is the hostname of the content delivery server. This is required for a scaled environment to avoid contacts being locked when running EXM. If there is more than one content delivery server in your environment, use the same value for each server.
In addition, make sure that the content management server can reach the content delivery server through HTTP using the hostname that you have specified in the Analytics.ClusterName setting of the content delivery server.
The way I see it, as long as the hostname there is accessible by the CMS, you are safe.
Regarding Hostname, it should be left empty when using multisites. This was the reply I got from sitecore support when asked them about it.
Analytics.HostName is a value of the global address (e.g. www.domain.com). This value should be the same for all CDs. But please note that for the multi-site solution the value should be blank (for all CDs). For more details please see the following known issue: https://kb.sitecore.net/articles/792020
| Analytics Tracker Config: What is the Proper Configuration for Multisite?
In Sitecore 8.0+, the invention of the Sitecore.Analytics.Tracker was introduced to provide Session based Analytic tracking to be sent to xDB. This is maintained in the config file Sitecore.Analytics.Tracking.config.
There are two settings:
Analytics.ClusterName
Analytics.Hostname
In a multisite configuration with multiple content delivery servers running behind a load balancer, what should the values of these settings be, in order to get Tracker to initialize appropriately?
Scenario 1:
Sitecore Sites Config Each Site has Different Start Item:
<site name="a" hostname"aaa.com" ... EnableTracking="true" ... />
<site name="b" hostname"bbb.com" ... EnableTracking="true" ... />
<site name="c" hostname"ccc.com" ... EnableTracking="true" ... />
3 Content Delivery Servers
Single IIS Site with bindings for each domain (aaa.com,bbb.com,ccc.com)
<setting name="Analytics.ClusterName" value="default-cd-cluster" />
<setting name="Analytics.HostName" value="" />
Each domain is different from the other.
Result: Error Received Under this scenario when running Tracker.StartAnalytics(). I get the following Stack Trace:
Tracker.Current is not initialized
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Tracker.Current is not initialized
Source Error:
Line 37: {
Line 38: if (!Tracker.IsActive)
Line 39: Tracker.StartTracking();
Line 40: }
Line 41:
Source File: D:\AgencyCode\XYZClientName-com\src\XYZClientName.Library\Abstractions\Contacts\ContactFactory.cs Line: 39
Stack Trace:
[InvalidOperationException: Tracker.Current is not initialized]
Sitecore.Analytics.Pipelines.StartAnalytics.StartTracking.Process(PipelineArgs args) +304
(Object , Object[] ) +74
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
Sitecore.Analytics.Pipelines.StartAnalytics.StartAnalyticsPipeline.Run() +293
XYZClientName.Library.Abstractions.Contacts.ContactFactory..ctor() in D:\AgencyCode\XYZClientName-com\src\XYZClientName.Library\Abstractions\Contacts\ContactFactory.cs:39
XYZClientName.Library.Factories.Contacts.SitecoreContactFactory..ctor() +49
XYZClientName.Library.Managers.XYZClientNameContactManager..ctor() in D:\AgencyCode\XYZClientName-com\src\XYZClientName.Library\Managers\XYZClientNameContactManager.cs:170
XYZClientName.Web.sitecore_modules.Shell.EmailCampaign.RegisterEmailOpened..ctor() in D:\AgencyCode\XYZClientName-com\web\XYZClientName.Web\sitecore modules\Shell\EmailCampaign\RegisterEmailOpened.aspx.cs:17
ASP.sitecore_modules_shell_emailcampaign_registeremailopened_aspx..ctor() +16
__ASP.FastObjectFactory_app_web_xrzs0hqx.Create_ASP_sitecore_modules_shell_emailcampaign_registeremailopened_aspx() +31
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +133
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +44
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +378
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137
Scenario 2:
Sitecore Sites Config Each Site has Different Start Item:
<site name="a" hostname"aaa.com" ... EnableTracking="true" ... />
<site name="b" hostname"bbb.com" ... EnableTracking="true" ... />
<site name="c" hostname"ccc.com" ... EnableTracking="true" ... />
3 Content Delivery Servers
Single IIS Site with bindings for each domain (aaa.com,bbb.com,ccc.com)
<setting name="Analytics.ClusterName" value="default-cd-cluster" />
<setting name="Analytics.HostName" value="aaa.com" />
Each domain is different from the other.
Result: Tracker is initialized and working for aaa.com. Fails to load on bbb.com and ccc.com.
| |
To update the text next to the Documentation link, you need to edit the Title field just under it. See this screen shot for an example. Probably best not to use markup in that field:
I'll have to leave adding another contributor to someone else as I couldn't see how to do that either!
| How to Add contributors to published Sitecore marketplace module
I have published a module in Sitecore marketplace. But now I can't add contributors or edit some of the text notes for the module.
How can I do this?
| |
So I had an issue with this custom Web API hosted inside my Sitecore solution, that will be used by a third party to call upon some Authentication and Authorization functionality. I did the following things to make it work:
I mistakenly named my API as ApiController which is actually a built-in Abstract class, so changed it to CustomerAPIController
Removed Cors, as this was no more required.
Inherit from Sitecore.Services.Infrastructure.Web.Http.ServicesApiController
Added this controller in the allowed list.
The third party would send some JSON (along with username, password, deviceId) without any Credentials (to access our API) and we need to have someway to accept these parameters, process/validate it and create and JWT along with Response Status message (200, 401 etc)
| How do I control access to Custom Item Web API controllers?
I am creating a Web API (Controller) inside my Sitecore solution by inheriting ServicesApiController and EnableCors attribute. This service will be called from any IPhone/Android Application (currently not sure how they will call).
For initial testing, I created an external console application and calling this API controller inside this.
Then I am loading my Sitecore page and attaching my solution to this (w3wp.exe) process in debug mode, also a breakpoint on my API method.
It is getting called successfully till I am in debugging mode. My external console application is unable to call this API controller method when it is not in debugging mode. I am unaware of any settings that I need to do to get this service called from an external application, while it is hosted in upper environments (Prod/QA).
Are there any configuration settings that I need to modify (only for this API controller and method) without compromising the security for other items?
| |
Found the solution. I used fieldNameFormat="PREFIX_{0}" in my fieldMap.
This way Sitecore couldn't map my object to the Solr object.
| Field values are being fetched as null while reading the data with SolrContentSearchManager with Solr custom FlatDataCrawler
I'm busy creating a Crawler using FlatDataCrawler for custom non-sitecore data.
Inserting the data into Solr works, but when i'm reading the data with SolrContentSearchManager my entities are inserted with null field values.
I debugged through Sitecore pdb's to find where Sitecore initializes my custom objects (inherited from IIndexable) when I use IProviderSearchContext (This is the CreateElementInstance method in the DefaultDocumentMapper class.)
My field values are available when I debug, but IIndexDocumentPropertyMapperObjectFactory is null so it would never insert these values in my object.
See here:
In my configuration I use the same indexDocumentPropertyMapper configuration as the default Solr configuration.
| |
Sitecore.Social lives in \App_Config\Include\Social and is controlled by the various configs that live there.
If you do not want to use the module at all, you can completely disable it by doing the following:
Delete the Social folder.
Delete all Sitecore.Social.*.dll from \bin
I've tested this on Sitecore 8.1U3 and Sitecore 8.2.
Hope this helps!
| How to keep Sitecore.Social from complaining about Ninject?
Sitecore Social loves to fill my logs with this:
Sitecore.Social: Ninject, Version=3.2.0.0, Culture=neutral, PublicKeyToken=c7192dc5380945e7 is not loaded. Couldn't determine the Social channels.
We're not using the module at all. Is there an easy way to disable it without breaking things (and without adding Ninject)?
| |
Hmm. You don't mention if you're using InProc or mongo session states. But it might not be relevant.
Sitecore overrides the default ASP.NET SessionIdManager manager - not entirely sure why. What is clear however, that it is in this puppy it is controlled, whether a new Session ID should be issued on timeout. So 2 things to try:
Add this attribute to your <sessionState> element. regenerateExpiredSessionId="true"
And if that doesn't work:
remove this attribute from the <sessionState> element. sessionIDManagerType="Sitecore.SessionManagement.ConditionalSessionIdManager"
Only option 1 would be a suitable end-all solution to your issue. If you have to take Sitecore's ConditionalSessionIdManager out of comission, it strongly suggest you have an issue that needs to be brought to Sitecore Support.
| Session_Start not called unless browser is closed
We have some logic that we trigger based on a new session starting by using Session_OnStart in Global.asax. This is fine, except that for some reason this is not being called when a page is viewed after the session times out but the browser is not closed.
Is Sitecore doing something to artificially extend the session infinitely while the browser is open?
Is there another hook we should look at?
Using Sitecore 8.0
| |
I'm not sure if you're updating Glass Mapper at the same time, but I don't believe the Glass.Mapper.Sc.Mvc-5 package is required as of v4 (Apr 2015).
If you have a look at the v4 release notes they have simplified things down to one Nuget package: Glass.Mapper.Sc, which also includes the .Mvc dll that you require. If your Nuget package install doesn't add it automatically, you can find it at <your project>\packages\Glass.Mapper.Sc.Core.4.2.1.188\lib\Mvc5x\Glass.Mapper.Sc.Mvc.dll (where Mvc5x is the version of MVC you are using).
I have Glass Mapper working in 8.2, however when I installed the .Mvc-5 Nuget package you mentioned, I can replicate your Could not resolve type name: Glass.Mapper.Sc.Pipelines.Response.GetModelFromView issue.
If you can't get your project running without this .Mvc-5 Nuget package (you should be able to) let us know what appears to be missing / broken.
| Attempt by method 'Glass.Mapper.Sc.Utilities.get_IsPageEditor()' to access method 'Sitecore.Context+PageMode.get_IsPageEditor()' failed
Just updated a simple instance of Sitecore 8.1 to 8.2, the actual solution contains a simple demo, some templates, items, nothing too complex. All went fine as I followed all the steps from the upgrade document but now when I try to get into Sitecore I get the following:
Attempt by method 'Glass.Mapper.Sc.Utilities.get_IsPageEditor()' to
access method 'Sitecore.Context+PageMode.get_IsPageEditor()' failed.
Is there a fix for this error somewhere? from the details below it seems to be from Glass and not Sitecore or my code.
EDIT:
After I removed all Glass packages from packages folder, removed entries from packages.config, removed all configs and then reinstalled a clean version of Glass.Mapper.SC and Glass.Mapper.Sc.MVC-5 via nuget on my solution now I get:
Could not resolve type name:
Glass.Mapper.Sc.Pipelines.Response.GetModelFromView,
Glass.Mapper.Sc.Mvc (method:
Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode
configNode, String[] parameters, Boolean assert)).
I checked with dotPeek and indeed there isn't such method, but not sure why then there is this entry in Glass config:
<mvc.getModel>
<processor patch:before="*[@type='Sitecore.Mvc.Pipelines.Response.GetModel.GetFromItem, Sitecore.Mvc']" type="Glass.Mapper.Sc.Pipelines.Response.GetModel, Glass.Mapper.Sc.Mvc"/>
<processor patch:before="*[@type='Sitecore.Mvc.Pipelines.Response.GetModel.GetFromItem, Sitecore.Mvc']" type="Glass.Mapper.Sc.Pipelines.Response.GetModelFromView, Glass.Mapper.Sc.Mvc"/>
</mvc.getModel>
Then if I remove this again from config I get another error:
Method not found: 'Glass.Mapper.Sc.SitecoreContext
Glass.Mapper.Sc.SitecoreContext.GetFromHttpContext(System.String)'.
Did anyone managed to have Glass working on a Sitecore 8.2 solution? I am not sure what else can I do to make it work fine.
My package entries:
<package id="Glass.Mapper.Sc" version="4.2.1.188" targetFramework="net452" />
<package id="Glass.Mapper.Sc.Core" version="4.2.1.188" targetFramework="net452" />
<package id="Glass.Mapper.Sc.Mvc-5" version="3.3.1.48" targetFramework="net452" />
Glass.Mapper.Sc.Mvc.config:
<sitecore>
<settings></settings>
<pipelines>
<mvc.getModel>
<processor type="Glass.Mapper.Sc.Pipelines.Response.GetModel, Glass.Mapper.Sc.Mvc" />
</mvc.getModel>
</pipelines>
</sitecore>
Glass.Mapper.Sc.config:
<sitecore>
<settings></settings>
<pipelines>
<mvc.getModel>
<processor patch:before="*[@type='Sitecore.Mvc.Pipelines.Response.GetModel.GetFromItem, Sitecore.Mvc']" type="Glass.Mapper.Sc.Pipelines.Response.GetModel, Glass.Mapper.Sc.Mvc" />
<processor patch:before="*[@type='Sitecore.Mvc.Pipelines.Response.GetModel.GetFromItem, Sitecore.Mvc']" type="Glass.Mapper.Sc.Pipelines.Response.GetModelFromView, Glass.Mapper.Sc.Mvc" />
</mvc.getModel>
<getChromeData>
<processor type="Glass.Mapper.Sc.Pipelines.GetChromeData.EditFrameBuilder, Glass.Mapper.Sc" patch:before="processor[1]" />
</getChromeData>
</pipelines>
<events>
<event name="publish:end">
<handler type="Glass.Mapper.Sc.Events.PublishEnd.GlassCacheClear, Glass.Mapper.Sc" method="ClearCache" />
</event>
<event name="publish:end:remote">
<handler type="Glass.Mapper.Sc.Events.PublishEnd.GlassCacheClear, Glass.Mapper.Sc" method="ClearCache" />
</event>
</events>
</sitecore>
| |
I would suggest switch to Database Tasks (/sitecore/system/Tasks/Schedules/), it has out-of-box mechanism to handle scheduled tasks for load balanced environments.
The benefit you will have is, it will get invoked only from one of multiple sitecore instance (whatever instance gets first chance) as it maintains state (flag) of Last Run.
For example, if the scheduler was run from instance A at 9:00:00. Now, assume that after few minutes, instance B checks to run it, before that it will check the last run time and will compare with the Schedule field (To check frequency of scheduler), and skip its execution as it's already been executed by machine-A.
Make sure to make it Async to avoid time-overlapping between two instances as Last run field considers Task ending time. So, if you set it as Async, the starting and end time will be same, and will give more accuracy.
Reference for using it - http://www.degdigital.com/insights/how-to-create-sitecore-scheduled-task/
| Scheduled tasks on load balanced CM server
How can I configure scheduled tasks in Sitecore to only run on one of the machines in a load balanced content management (CM) environment?
I have a task configured via a config include and am using Sitecore 8.0.
| |
If you don't want FilePath based language resolving, simple do below setting in Sitecore.config:
<setting name="Languages.AlwaysStripLanguage" value="false" />
This will do nothing but ignoring the StripLanguage processor from preprocessRequest pipeline.
By default first item (after domain name), Sitecore checks whether it's a language or not. If it's a registered language of .NET, Sitecore will consider it a language, else will consider it as an Item inside Home. So, above configuration should fix your issue.
| How to prevent Sitecore resolving the Language based on the URL
Our site is resolving some relative urls as languages, where it should be resolving items instead.
e.g.
mydomain.com/eu should be resolving the item EU under the home item.
Instead, Sitecore is resolving the home item with the language as Basque (EU)
What is an effective way to prevent this from happening?
| |
Here is the my final solution after the leads from other answers here. I use the media:request event along with the lesser known AddOnSendingHeaders method on Request object that basically gives me a final chance to change headers before IIS sends the request to the client.
public class ChangeFileName
{
public void OnMediaRequest(object sender, EventArgs args)
{
SitecoreEventArgs eventArgs = args as SitecoreEventArgs;
MediaRequest mediaRequest = eventArgs?.Parameters?[0] as MediaRequest;
if (mediaRequest == null)
{
return;
}
MediaItem mediaItem = MediaManager.GetMedia(mediaRequest.MediaUri).MediaData.MediaItem;
if(mediaItem == null)
{
return;
}
HttpRequest request = mediaRequest.InnerRequest;
request.RequestContext.HttpContext.Response.AddOnSendingHeaders(context =>
{
if (CheckFileType(mediaItem))
context.Response.Headers["Content-Disposition"] = FixFileName(context.Response.Headers["Content-Disposition"]));
});
}
}
Then of course, I had to add the event handler to the config:
<event name="media:request">
<handler type="MyAssembly.ChangeFileName, MyAssembly" method="OnMediaRequest"/>
</event>
| Change default file name when downloading from Media Library
I store user uploaded files in Media Library, which can later be downloaded by admins. When saving files, I change the file names to guarantee uniqueness, but later when admins download them I want them to see the original or user friendly file name.
This is the line of code behind the download button:
HttpContext.Current.Response.Redirect(MediaManager.GetMediaUrl(mediaItem));
Sitecore uses media item name and the extension stored in Extension property to construct the default file name. It does not use the display name, nor the title or any other field.
I know that the file name is reflected in the content-disposition header and looks like attachment;FileName.doc. I want to know if there is any way I can modify that header in the response of the file download so I can have a chance to include my own logic.
I know, I can create my own custom download handler, but my specific question is regarding intercepting media download requests in Sitecore, which is the preferable method.
| |
Does azure search uses Lucene as search engine?
Azure Search is Microsoft's response to providing a cloud based indexer. It uses Elastic Search as the underlying driver, but the Elastic Search engine is not directly accessible. Currently Azure Search is only accessible using RESTful Web services or the Azure Resource Manager control panel.
I assume switching from SOLR to Azure Search will be easy i.e. no code
change (just use content search provider)?
As for the Sitecore provider, it will hook into Sitecore in a similar fashion to Solr and utilize all of the same Sitecore ContentSearch api.
My initial thoughts are that it's possibly viable so long as all of your Sitecore roles are in Azure and in the same Resource group as well as same virtual network.
Any other use or connection and the latency makes indexing so slow that it's not recommended. To give you an idea, it took approximately 9 minutes to index 1000 items from local laptop to Azure Search.
For a full cloud implementation though it is very promising.
Has anyone played with Azure Search?
Jamie Scott (Slalom) wrote one of the original implementations that works with Sitecore 8.1. You can find his Github repo here: Sitecore Azure Search Provider for Sitecore 8.1.
Here is a link to the LinkedIn Blog post he wrote about it.
Does azure search has concept of Cores (similar to Solr) so that we
can patch per environment?
Azure Search uses indexes as the primary collection. If you need to use different indexes for a different environment you can setup a different service connection.
| Sitecore Azure Search vs. Solr Provider
I've used both Solr and Lucene. The majority of our sites now use SOLR. Heard Azure Search provider will be introduced on 8.2.1 release.
Has anyone played with Azure Search?
Does Azure Search use Lucene as a search engine?
Does Azure Search have a concept of Cores (similar to Solr) so that we can patch per environment?
I assume switching from SOLR to Azure Search will be easy i.e. no code change (just use content search provider)?
Thanks.
| |
I'd recommend learning and using Apache JMeter.
Yes, it's a technically a load testing tool, but in reality it's a highly configurable and very powerful tool to script simple and complex HTTP (and other) requests against one or many destinations.
We use it for both load and stress testing. You can build up a suite of requests that cover a good representation of your site pages, configure and pass in variables / user logins, etc. and then set it to run with a low thread concurrency level (i.e. only running 1 or 2 requests at a time but over a much longer period of time.).
Also worth nothing that each thread can be spun up with a unique session scope and cookie storage, so you can simulate complex site interactions. Or you can choose not to do it and just bombard the site with anonymous requests.
We've used this same process to run extended tests over a weekend to catch memory leaks, very much what you sound like you're looking to do.
I'd suggest avoiding using site-crawlers for this as they'll make it hard to identify what pages are causing the leaks. With something more controlled like JMeter you'd be able to turn on and off tests to isolate to just the requests that cause the leak. Then fix the leak and re-run the exact same tests.
Useful links:
JMeter Home
JMeter Plugins
| Tool to test long term execution footprint of your Sitecore solution
So I'm coming up on the end of a project cycle; and I want to just give it a good shake around the hinges to see if everything is fine.
I'm not looking for load testing (imo, load testing locally is pointless) - but my idea is to fire up dotProfile and dotMemory then (using a tool) continuously run sessions against the site locally - either following a script or automatic (spidering). Again; not for purposes of load testing - more like leave it running for a couple of hours and see if anything stands out in the traces.
I've been doing some research myself; but most tools I find are either Spiders/SEO optimizers or load testing tools. I suppose a load testing tool could do the job, but I'm wondering if anyone else has experience they'd like to share.
| |
I've seen (and tried) many different approaches to this problem. I'm going to propose one, but there will be quite many alternatives. Let's see what the community comes up with.
Your first problem is the execution order of your components. In your scenario; the container component will execute its Action before any of the sub-components. There really isn't much that can be done about this; so you're going to have to break down your container component into two separate actions. I would suggest Index and Sum. I am also assuming ControllerRendering.
To deal with execution order - this approach can be used:
<div>proceed to output your container html here<div>
<div class="container">
<div class="child-elements">
@Html.Sitecore().Placeholder("main")
</div>
<div class="summary">
@Html.Sitecore().Placeholder("sum")
</div>
</div>
Why does this work?
Essentially because the Razor file is processed top-down, we know the "main" Placeholder() call will get executed before the "sum" Placeholder call.
With this in place; you are ready to communicate. The very simplest approach uses HttpContext.Current.Items. At the end of your Index Action method; do something like HttpContext.Current.Items["pricesummary"] = new SummaryResults() (or even just set it to 0d). Your child elements would then do something like
if (HttpContext.Current.Items["pricesummary"] != null)
HttpContext.Current.Items["pricesummary"] += myPrice;
And lastly; your Sum() Action method would output the sum.
In this example, you could replace the "sum" Placeholder with a direct call to your action method, if you prefer.
Lastly: Jeremy Davis wrote a very decent summary of this problem, with a few more advanced solutions to the problem. Find his post here: Getting MVC Components to Communicate.
| Shared data between root- and subcomponents in placeholder while having a loose coupling between them
I have a nested component structure, where my root element has a placeholder, which contains zero to many sub-components. Each sub-component has it's own price, which gets calculated inside the sub-component itself.
On the root component, I want to calculate the sum of the sub-component's individual prices. One way to go about this is to have the root component access all the sub-components found inside the given placeholder, fetch the price and calculate the sum. However, I feel that it's not really the proper way to do this. Instead, I would like to have some sort of pub/sub system, where the calculating of each sub-component price would trigger an event, that the root component could listen to etc. The problem is however, that the root component exists multiple times on the same page item, meaning that I somehow need to have a unique identifier that tells which root component each sub-component lives under.
Using Sitecore 8 with MVC, my question is how this best can be done, while still having a loose coupling between the subcomponents and the root components.
| |
Instantiate a SitecoreContext and call the Cast<T>() method.
ISitecoreContext context = SitecoreContext.GetFromHttpContext();
var myTemplateObject = context.Cast<MySite.Model.MyTemplate>(item);
| How to convert a Sitecore Item object into a strongly-typed Glass model?
I have a Sitecore template MyTemplate and a corresponding Glass model MySite.Model.MyTemplate.
In my page code, I retrieve a raw Sitecore.Data.Items.Item object from a legacy data access class. This object represents an item of the template MyTemplate, but it is still a generic item object, so I have to access its fields like this: item["FieldName"].
Is there a quick way to convert this Item object into a strongly-typed Glass model of the class MySite.Model.MyTemplate? I want to do this directly in my page code, without replacing the way in which I obtain the item object.
| |
The Sitecore 8.2 Release Notes provide a wealth of information around the changes that come along with 8.2. I would definitely pay attention to the breaking changes section. Largely, the 8.2 Version of Sitecore was very Developer focused and not as much has changed on the marketing side.
Specifically though, the biggest, noticeable, differences in 8.2 include the following short list:
Introduction of Microsoft's Dependency Injection.
Sitecore went all in on this. Almost every manager and provider in Sitecore has been refactored into a Lazy Singleton service pattern. Sitecore also included a nifty way to patch in your own controls. Kam Figy wrote the leading blog discussing how this is used.
The Cache mechanism has been completely rewired and the Cache class has been removed.
All your binaries will need to be recompiled to .NET 4.5.2
Solr is now configurable without needing to modify the Global.asax or use a Solr Support Package.
All of the Sitecore SPEAK UI components have been precompiled into the DLL, making the content editor and experience editor lightning fast. This also introduces functionality that allows you to precompile your own view renderings as well.
There are many other changes that have come about, but these are the biggest in my opinion. Others are welcomed and encouraged to add their own thoughts on the pieces they feel are important.
| What are the main improvements of Sitecore 8.2, compared to 8.1?
I have a Sitecore installation in production. Most standard features are being used—Content Editor, Experience Editor, xDB, Experience Profile, Experience Analytics, MVC, custom pipeline processors, Lucene indexes, etc. We're also using a dependency injection container integrated with MVC controllers.
The Sitecore version currently used is 8.1 rev. 151003 (8.1 Initial Release).
The latest available version is 8.2 rev. 160729 (8.2 Initial Release).
What are the biggest benefits of upgrading from 8.1 to 8.2?
| |
The entirety of the CMS Performance Tuning guide that you linked is relevant for Sitecore 8.X. The guidelines and features discussed have not changed. The underlying architecture for some of the elements have changed (such as Caching) but how you tune has not.
What's not in here are the additional performance improvements that can be done as a result of the changes in 8.2+. For example, the inclusion of Dependency Injection or the precompiling of view renderings, all lead towards improving performance of the core product.
I would expect that as Sitecore completes the documentation phase of 8.2, we'll should start to see some performance optimization documentation. If we don't though, have confidence in knowing that the 7.X documentation is still viable and relavant.
| CMS Performance Tuning for Sitecore 8+
Sitecore has previously published a CMS Performance Tuning Guide for Sitecore 6.x and 7.x on SDN. I do not see any similar content on doc.sitecore.net for Sitecore 8.x. Is most of the content in the 7.x document on SDN still relevant? Any new considerations on 8.x which have not been documented?
| |
When an item is updated in the index, the indexing:updateditem event is raised with the index name and item ID as parameters. You could add a handler for this event and either clear the cache based on that item, or append to a queue that you then process and clear when the indexing:end event is fired.
There is also indexing:deleteitem and indexing:added for deletes / adds.
| Get indexed items after index update
We are using some (custom) caches that get cleared when data changes in Sitecore - it's written so that it only clears the cache when items from a certain template are published (we don't want this cache to be thrown away each time an editor publishes a small unrelated content change).
This works fine but.. the cache gets filled with data based upon an index query. So if the cache is cleared, and the index is not yet up-to-date before the first request that refills the cache, we are (might be) caching old data. So I started looking into events that we could use after index end.
I found an indexing:end event, but as far as I could see the arguments are .. well, just the index name.
So my question is: is there a way to get a list of indexed items? (project is now on Sitecore 8.1 - but a solution on a higher version could also help)
| |
Try clearing this setting:
<setting name="RedirectURLPrefixes" value="/sitecore" />
If it makes a difference it's a reasonable assumption you got some less than ideal URLs going on in your solution. Like http://site.domain/sitecore/content/home/news - that type of thing.
| Request is redirected to no layout page
I noticed that in my logs there are a ton of entries like this:
5920 09:09:26 WARN Request is redirected to no layout page. Item: sitecore://web/{11111111-1111-1111-1111-111111111111}?lang=en&ver=1 Device: {FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3} (/sitecore/layout/Devices/Default)
I am not seeing any odd visual behavior. Is there a way to further debug what issue is placing this into the logs.
I'm using Sitecore 8.1
| |
Previously, the 9.1 packages were in a separate feed, as of March 4th 2019, these have now been moved back into the main feed. The NoReferences packages are still removed.
To avoid link rot, here are the feed urls for the official feeds:
For all versions:
NuGet V3 feed URL (Visual Studio 2015+)
https://sitecore.myget.org/F/sc-packages/api/v3/index.json
NuGet V2 feed URL (Visual Studio 2012+)
https://sitecore.myget.org/F/sc-packages/
Browse packages
https://sitecore.myget.org/gallery/sc-packages
Versioning Updates
As of 9.1, The package versions will follow the Product version numbers, this will make it easier to identify which version a package refers to rather than having to look up the revision number for each update. So Sitecore 9.1 packages are versioned 9.1.0
This is a breaking change!!!
In the separate 9.1 feed, the version numbers followed the binary versions, so the version for 9.1 initial release was 12.0.0, in the new feed they follow the product version, so it will now be 9.1.0, so when you switch to the correct feed, you will have to change your version numbers to match.
What about the separate 9.1 feed? Will this break my build?
Sitecore are removing the "old 9.1" feed listing from the gallery, but the feed will remain in place for those of you who have already used it. Once you upgrade, you will need to use the original feed for newer packages.
Sitecore have now deprecated the original Sitecore XP 9.1 MyGet feed. After March 31st, 2020 the original 9.1 MyGet feed will not be available. Please make sure you move over to the current feed. More info can be found here: https://kb.sitecore.net/articles/686847
What happened to the .NoReferences packages?
With the new updates to the packages, Sitecore have also stopped providing the .NoReferences packages. This was done to simplify the the process for developers and also the release process for Sitecore.
But - you can still have a similar behavior with the full packages. Using the Nuget Package Manager you can change the Dependency Behavior option to Ignore Dependencies:
If you want to use the Package Manager Console you can use the -IgnoreDependencies flag like this:
Install-Package -Id <package name> -IgnoreDependencies -ProjectName <project name>
PackageReference
For those of you on VS 2017+, you can also migrate to using PackageReference to reference your nuget packages. This uses the PackageReference node in the .csproj file to manage the NuGet dependencies instead of the packages.config file. This brings a number of benefits that are too numerous to mention here, but you can find out more on the PackageReference page.
Build Servers
If you are using a build server, as well as adding this to Visual Studio you will want to update your Nuget.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Used to specify the default Sources for list, install and update.
-->
<packageSources>
<add key="Official Sitecore" value="<URL to the package feed appropriate for your project>" />
</packageSources>
<activePackageSource>
<!-- this tells that all of them are active -->
<add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
Upgrading your Solution
There is a nice post here talking about adding that to your VS solution: https://jermdavis.wordpress.com/2016/09/05/the-official-sitecore-nuget-feed-is-here/
Some of the main points when using are:
* There are packages with .NoReferences suffixed. These are probably the most useful as they don't try to bring in a lot of dependencies you may not need in your project.
* They set the binaries as CopyLocal=true, so you may want to change that in your project
@kamsar wrote a nifty PowerShell script to update your solution to use this: http://kamsar.net/index.php/2016/09/Nugetify-your-Sitecore-References/
Updates:
March 24th 2020 with new information about the original 9.1 specific MyGet feed.
March 26th 2019 with new information about NuGet feeds for 9.1
| How do I reference Sitecore binaries from NuGet?
I've heard through the grapevine that Sitecore DLL's can be referenced through the use of NuGet Packages. I found Sitecore.NuGet, but I don't think that's the right option. I also found this blog post talking about the Sitecore NuGet Package Generator which looks promising.
Seems like there are quite a few ways that this is being handled according to Google. I also recall at the Sitecore Symposium 2016, that NuGet package availability might be something Sitecore provides.
So, the root of my question is:
What is the best way to reference Sitecore DLL's?
| |
I've not tried to set this up yet myself, but I can tell you that the solr support package is no longer required. So, I'm going to guess that you can simply enable all of the solr files and disable the lucene files.
| Where can I find the instructions for setting up SOLR without using IOC?
I'm trying to setup an instance of Sitecore 8.2 so I can see what it's going to take to upgrade my site from Sitecore 8.1 to it. I've heard that Sitecore 8.2 can run SOLR natively (without using IOC), but I can't find any documentation that tells me how to do it. All that I'm able to find are documents describing how to setup SOLR using IOC. Thanks for your help!
| |
Summary
To summarise the comments on this question, which provide a reasonable answer.
7.5 does not have the fix applied. 7.2 update 6 does.
They recommend upgrading to 8 for improved functionality
Sitecore strongly recommends that you upgrade to the latest version of the Sitecore Experience Platform. [...] The latest Sitecore XP 8.0 update also includes critical hotfixes that significantly improve stability of this release compared to Sitecore XP 7.5.
So two options stay on 7.2 update 6 or upgrade to 8 to get fixes.
They are working on Hotfix for Sitecore 7.5 update-2
| Sitecore Page Editor Issues with Move and Add Components
I have a page with "body" placeholder in which I have kept 10 controller renderings on a page.
When I'm trying to order the component using Page editor or Content editor, the sort order randomly readjusts by itself.
Does anyone know of a fix for this?
This is Sitecore 7.5 update 2
-- UPDATE 1--
The issue is observed with the Page Editor and Content Editor both.
I got an update from Sitecore support as below:
As for the changing the controls order in the Page Editor:
The issue is indeed server-side and is related to how XML deltas are
built and processed. I've registered the issue as a bug in the
current Sitecore version. I've spent quite some time investigating the
root cause of the issue and looking for ways to implement the most
practical workaround. Unfortunately, the proper patch would be
extremely nontrivial to implement and would require the customization
of some deep Sitecore logic, which may affect some other parts of
Sitecore in unpredictable ways. The only workaround I can provide you
with at the moment is the one, that makes an item use full XML
representation of page layout instead of a delta one.
As for the changing the controls order in the Content Editor-->Layout
Details dialog:
This issue was fixed in 7.2 rev.160123 (7.2 Update-6). Please get more
info on the Release Notes page using the reference #388264
https://sdn.sitecore.net/SDN5/Products/Sitecore%20V5/Sitecore%20CMS%207/ReleaseNotes/ChangeLog/Release%20History%20SC72.aspx
Sitecore Support
Note: Though Sitecore Support says its fixed with Sitecore 7.2 update-6 its not working for me in 7.5 update-2.
-- UPDATE 2--
From Sitecore Support
Please let me explain the reasons that this issue persists in Sitecore
CMS 7.5 U-2 and at the same time was fixed in Sitecore CMS 7.2 U-6.
The reason of that lays in the fact that actually Sitecore CMS 7.2 U-6
(January 26, 2016) has been released after Sitecore CMS 7.5 U-2
(February 13, 2015).
I understand that this can look a bit confusing at a first glance, sorry for that.
Sitecore Support
--Final Update--
Sitecore has provided Hotfix which works as expected. Sitecore Support's reference number for Hotfix is 126989
| |
Turns out to be a known Sitecore bug - request patch 81234 for a DLL/config from support.
| Experience Editor search - requested document not found
This is using Sitecore 8.1 Update 1. When I click the search icon to get the "navigate to item" and search for something in my website, I get a "requested document not found" error. It's quite clearly there, but even something like my home page will throw this error. It's a multi-site setup, but I thought this was supposed to handle that just fine and even facilitate working in multiple sites.
This message is at the bottom of the page - "If the page you are trying to display exists, please check that an appropriate prefix has been added to the IgnoreUrlPrefixes setting in the web.config." - but I'd guess that's for any "real" pages - these are definitely Sitecore items.
Any thoughts? Thanks.
| |
Looking at the OP, the comments, your code and Sitecore's, I believe that this issue is likely caused by a bug in the PageEvent.IsGoal property, whereby the property is not being correctly set to true for events that are goals. I have not yet confirmed this bug, but if I am correct then the following should help you work around the issue:
Solution
Try changing your code to the following:
foreach (PageData page in args.Context.Visit.Pages)
{
if (page.PageEvents != null && 0 < page.PageEvents.Count)
{
foreach (var pageEvent in page.PageEvents)
{
var pageEventItem = pageEvent.PageEventDefinitionId != Guid.Empty
? Tracker.DefinitionItems.Goals[pageEvent.PageEventDefinitionId]
: Tracker.DefinitionItems.Goals[pageEvent.Name];
if (pageEventItem == null || !pageEventItem.IsGoal)
{
throw new Exception("I must be null because I definitely should be a goal. Still I should never be thrown because I came from the Goals property of the trackers definition items");
}
Log.Info("Goal: " + pageEvent.Name.ToString(), "PageEventProcessor");
// now do something with your goal
}
}
}
Notice that in the above solution, I am using the pageEventItem.IsGoal property instead of the pageEvent.IsGoal property. I have not sufficiently tested this to figure out if the problem is simply with the PageEvent.IsGoal flag is not set when you check it, but I expect that to be the case. Regardless, the PageEventItem.IsGoal should be accurate and more reliable, as that property is read directly from the item's field.
Arrival at Solution
While I am still working to figure out if this is actually a bug in xDB, I came to this solution by looking at how Sitecore aggregates goals in the <interactions> pipeline.
Remember that a Goal is really a conversion, and since there weren't any processors with "Goal" in the name, I had a look at the Sitecore.Analytics.Aggregation.Pipeline.ConversionsProcessor.
After reviewing the processor I realized that Sitecore's approach was nearly identical to yours though slightly different - Sitecore's code uses the item's field to determine if it's actually a goal. Since checking the value of that field should be more reliable than a property that may or may not have been correctly set on a C# object, I am left to infer that the issue is likely a bug in Sitecore with the PageEvent.IsGoal property and that you should work around the issue by using the PageEventItem.IsGoal property, instead.
Next Steps
The first thing that I recommend you do is try the above workaround. Next, I would get in touch with Sitecore Support and show them what you've tried and what you are seeing. They should be able to provide further assistance, in addition to documenting and fixing the bug, if confirmed.
Good luck!
| Goals not being retrieved from Sitecore xDB ( MongoDB )
I upgraded my site from Sitecore 7.5 to 8.1, and following is the code that I'm using to retrieve the page events:
foreach (PageData page in args.Context.Visit.Pages)
{
if (page.PageEvents != null)
{
foreach (var pageEvent in page.PageEvents)
{
if (pageEvent.IsGoal)
Log.Error("Goal: " + pageEvent.Name.ToString(), "PageEventProcessor");
}
}
}
the page events are being retrieved except the goals, Although I can see the following data in the interaction collection in MongoDB:
"PageEvents" : [
{
"Name" : "Mobile Click",
"Timestamp" : NumberLong(0),
"Data" : "Mohammed Test",
"DataKey" : "650fce89-87bb-4768-ab40-8bc988d7a729",
"Text" : "Location Name and other information",
"PageEventDefinitionId" : LUUID("e7798282-5362-af4d-80ce-07055fcf3b86"),
"IsGoal" : true,
"DateTime" : ISODate("2015-08-23T16:12:21.686Z"),
"Value" : 10
}
],
Am I doing something wrong in the retrieving code? Is there another code I should use? Any suggestions?.
| |
You must change the maxAllowedContentLength setting to increase the maximum allowed download size of the update package.
To do this:
In a text editor, in the \wwwroot\\Website\sitecore\admin\web.config file, change the maxAllowedContentLength setting from:
<requestLimits maxAllowedContentLength="1048576000" />
to:
<requestLimits maxAllowedContentLength="4194304000" />
for more information check the upgrade document:
Upgrade Guide
| OutOfMemoryException running the 8.1->8.2 upgrade wizard
On Step 3 of 1.2.3 in the upgrade guide, I'm getting a System.OutOfMemoryException pointing to Sitecore.Update.Utils.FileUtils.SerializeFile(Stream stream, String location) +137.
Installation wizard installed fine and the UpdateInstallationWizard.aspx page comes up fine.
In /sitecore/admin/packages, it looks like, it tried to write the file "Upgrade from 8.1 rev. 160519 to 8.2 rev. 160720.update", but it's got zero length.
Any ideas?
| |
There are several pieces of documentation that are available for this:
First is https://doc.sitecore.net/sitecore_experience_platform/setting_up__maintaining/security_hardening
This contains a collection of documents relevant to your version of Sitecore.
Second is The Security Hardening Guide which is the defacto guide for locking down and securing a Content Delivery server.
Last, part of the process of locking down a content delivery server is removing all references to the master database. There is a config SwitchMastertoWeb.config.disabled that should be included somewhere in your config solution. Rename that to SwitchMasterToWeb.config and that will remove master from the server references.
| How do I disable /sitecore access on a Content Delivery Server?
I have 2 servers:
Content Delivery - the live site pointing to the web database.
Content Management - the internal only site pointing to the master database.
I want to prevent access to /sitecore on the live site, and require Content Editors to access this from the Content Management server.
How can I lock this down to prevent access from the Content Delivery server?
| |
Messy; sure. But it should be without consequence. Templates and fields are language agnostic; even if the "field items" themselves get created with a language version. All fields on a field template are either [Shared] or [Unversioned].
The only exception to this that I'm aware of, is Enable versioned field level fallback; used in the setup and use of Field Level fallbacks. If you're using that feature, you need to be mindful of its setting on the various language versions you have.
Also - but I believe you realise this already - be aware of your __Standard Values item and versions - for this, it matters what language versions you have created. Likely some Sitecore Powershell Extentions scripting could help clean that up a bit.
So in summary. If you're not using Field Level Fallback; don't worry too much about this. 'd be nice to clean up, but it should not have any practical impact on your solution - just be careful of Single Language Publishes. They might just go ignore your item if you're publishing only "en" but a field is defined with a "de" language version. If I remember it right; the PublishEmptyItems setting could influence this behaviour.
| Are there any issues with having multiple language versions of templates and template fields?
We have a multilingual website based on Sitecore 8.1 rev. 151207 (8.1 Update-1) and Glass Mapper. It has four languages: English, Danish, Swedish and German.
Some of the developers are native English speakers, and some are native German speakers. "Naturally", they used their respective Sitecore UI languages in the content editor when creating and editing templates. So we ended up with approximately 100 item templates, with some of them having only an English version, some only German, and some both. The same goes for template fields—actually, some templates have most fields with two language versions, a couple fields in only English or German.
This is a messy situation, and I believe that mid-term we should spend time on making all templates English-only. But in the meanwhile, I would like to know whether or not this could become an issue short-term. Could this result in errors in some situations? Could it affect language fallback functionality? How much should we prioritize fixing this?
| |
It is a permissions issue. You've not shared your actual connection string sharedsession but the end result will be the same, the account you're using to connect to SQL does not have sufficient permissions. My first course of action would be to attempt a connection string based on the sa account and see if the problem goes away.
Default SQL session state is based on tempdb so you're right; setting permissions directly on that will be lost after restart. You can however opt to install a permanent version.
When you use the default InstallSqlState.sql and UninstallSqlState.sql
script files to configure ASP.NET SQL Server mode session state
management, note that these files add the ASPStateTempSessions and the
ASPStateTempApplications tables to the tempdb database in SQL Server
by default. Furthermore, if you restart SQL Server, you lose the
session state data that was stored in the ASPStateTempSessions and the
ASPStateTempApplications tables.
For setting up a permanent version; refer to HOW TO: Configure ASP.NET for Persistent SQL Server Session State Management.
If you want to stick with the default setup, use an Integrated connection string, then grant your IIS AppPool user (or whatever user you use to connect) the following permissions on the ASPState database:
datareader
datawriter
| Configuring private sessionState database raises runtime error:
I am trying to configure a mssql private sessionState database. I added the following to web.config's :
<sessionState mode="Custom" customProvider="mssql" cookieless="false" timeout="20">
<providers>
<add name="mssql" type="Sitecore.SessionProvider.Sql.SqlSessionStateProvider, Sitecore.SessionProvider.Sql" connectionStringName="session" pollingInterval="2" compression="true" sessionType="private"/>
</providers>
</sessionState>
My connection string (with password and domain altered for security):
<add name="session"
connectionString="user id=Sitecore;password=mypassword;Data Source=db.mydomain.com;Database=Sitecore_Sessions;Initial Catalog=Sitecore_Sessions"/>
However, this throws an error at runtime rendering the site useless:
Event code: 3008 Event message: A configuration error has occurred.
Event time: 9/27/2016 1:27:20 PM Event time (UTC): 9/27/2016 8:27:20
PM Event ID: 9b328571e1994ddf8f99ae0ad4d56473 Event sequence: 8
Event occurrence: 1 Event detail code: 0 Application information:
Application domain: /LM/W3SVC/1/ROOT-1-131194816187533180
Trust level: Full
Application Virtual Path: /
Application Path: E:\wwwroot\Sitecore\Website\ Process information:
Process ID: 9180
Process name: w3wp.exe
Account name: IIS APPPOOL\SitecoreAppPool Exception information:
Exception type: ConfigurationErrorsException
Exception message: The SELECT permission was denied on the object 'Application', database 'tempdb', schema 'dbo'. The SELECT permission
was denied on the object 'Application', database 'tempdb', schema
'dbo'. The INSERT permission was denied on the object 'Application',
database 'tempdb', schema 'dbo'.
(E:\wwwroot\Sitecore\Website\web.config line 371) at
System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings
providerSettings, Type providerType) at
System.Web.SessionState.SessionStateModule.SecureInstantiateProvider(ProviderSettings
settings) at
System.Web.SessionState.SessionStateModule.InitModuleFromConfig(HttpApplication
app, SessionStateSection config) at
System.Web.SessionState.SessionStateModule.Init(HttpApplication app)
at System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) at
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) at
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) at
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext)
The SELECT permission was denied on the object 'Application', database
'tempdb', schema 'dbo'. The SELECT permission was denied on the object
'Application', database 'tempdb', schema 'dbo'. The INSERT permission
was denied on the object 'Application', database 'tempdb', schema
'dbo'. at System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction) at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds, Boolean describeParameterEncryptionRequest) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean asyncWrite) at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
Sitecore.SessionProvider.Sql.SqlSessionStateStore.GetApplicationIdentifier(String
name) at
Sitecore.SessionProvider.Sql.SqlSessionStateProvider.Initialize(String
name, NameValueCollection config) at
System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings
providerSettings, Type providerType)
Request information:
Request URL: http://localhost/
Request path: /
User host address: 127.0.0.1
User:
Is authenticated: False
Authentication Type:
Thread account name: IIS APPPOOL\SitecoreAppPool Thread information:
Thread ID: 9
Thread account name: IIS APPPOOL\SitecoreAppPool
Is impersonating: False
Stack trace: at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings
providerSettings, Type providerType) at
System.Web.SessionState.SessionStateModule.SecureInstantiateProvider(ProviderSettings
settings) at
System.Web.SessionState.SessionStateModule.InitModuleFromConfig(HttpApplication
app, SessionStateSection config) at
System.Web.SessionState.SessionStateModule.Init(HttpApplication app)
at System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) at
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) at
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) at
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext)
It appears that this could be is a permissions issue, but wouldn't permissions get reset on the tempdb every time the SQL server is rebooted?
I am running Sitecore 8.1
UPDATE: I can duplicate this behavior in SQL Management studio.
USE [Sitecore_sessions]
SELECT * FROM [dbo].[Applications]
Returns the following error:
Msg 229, Level 14, State 5, Line 2 The SELECT permission was denied on
the object 'Application', database 'tempdb', schema 'dbo'.
That is because dbo.Applications is a synonym that points to tempdb. :-(
| |
Based on your code snippet above, and compared with what I'm doing with my custom caches, you don't have to call base.SetObject(). As long as you provide a long maxSize in the base constructor call, the CustomCache class will take care of the rest. One of the changes Sitecore made was removing the need to calculate the size of your cache object. The new cache provider will do that for you.
Here is a code snippet (below) from my Dynamic Sites Manager, where I'm creating a custom cache based off of CustomCache class, and updated for Sitecore 8.2.
I would just remove the need to call base.SetObject()
using System.Collections;
using Sitecore.Caching;
using Sitecore.SharedSource.DynamicSites.Utilities;
using Sitecore.Sites;
namespace Sitecore.SharedSource.DynamicSites.Caching
{
internal class SiteCache : CustomCache
{
public SiteCache(long maxSize) : base(DynamicSiteSettings.CacheKey, maxSize)
{
}
//AddSite
public void AddSite(Site siteItem)
{
if (ContainsSite(siteItem))
{
RemoveSite(siteItem);
}
var cacheItem = new SiteCacheItem(siteItem);
InnerCache.Add(siteItem.Name, cacheItem);
}
//GetSite
public Site GetSite(string name)
{
if (!ContainsSite(name)) return null;
return (Site)InnerCache.GetValue(name);
}
private void RemoveSite(Site siteItem)
{
if (ContainsSite(siteItem))
{
//Refresh Information
InnerCache.Remove(siteItem.Name);
}
}
//GetAllSites
public SiteCollection GetAllSites()
{
return GetAllSites(InnerCache.GetCacheKeys());
}
//ContainsSite
public bool ContainsSite(Site siteItem)
{
return InnerCache.ContainsKey(siteItem.Name);
}
private bool ContainsSite(string name)
{
return InnerCache.ContainsKey(name);
}
// Count
public int Count()
{
return InnerCache.Count;
}
public SiteCollection GetAllSites([NotNull] IEnumerable orderedList)
{
var collection = new SiteCollection();
foreach (string siteName in orderedList)
{
collection.Add(GetSite(siteName));
}
return collection;
}
}
}
To expand upon why you are seeing this, base.SetObject() was changed from 3 arguments to two, and then another overload was added to handle an event. This is why you are seeing the event handler.
using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.Diagnostics.PerformanceCounters;
using System;
namespace Sitecore.Caching.Generics
{
public abstract class CustomCache<TKey>
{
...
protected void SetObject(TKey key, object value)
{
if (!this.Enabled)
return;
this.cache.Add(key, value);
}
protected void SetObject(TKey key, object value, EventHandler<EntryRemovedEventArgs<TKey>> removedHandler)
{
if (!this.Enabled)
return;
this.cache.Add(key, value, removedHandler);
}
...
}
}
| Sitecore.Caching.CustomCache changes with 8.2
I'm upgrading my site from Sitecore 8.1 to Sitecore 8.2, and one of the compile errors that I'm getting is
CS1503 Argument 3: cannot convert from 'long' to
'System.EventHandler'
As I'm looking into this, I think that I remember reading how Sitecore completely changed the cache working in 8.2, and therefore I will need to change my code as well. Can someone provide an overview of what kind of changes I'll need to make to my code so that I can run on 8.2?
Edit
This class is based on the Sitecore.Caching.CustomCache class.
Here's the code that I'm having problems with:
public void SetObject(string key, object content)
{
base.SetObject(key, content, EstimateObjectSize(content));
}
private long EstimateObjectSize(object obj)
{
long size = 0;
try
{
using (Stream s = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, obj);
size = s.Length;
}
}
catch(SerializationException)
{
// object cannot be serialized so just return 0
size = 0;
}
return size;
}
The code is complaining about the base.SetObject call (with the EstimateObjectSize) method. I understand that I need to change my object, and having read that document that Mark posted, I still am not sure what changes need to be done. It seems as if the SetObject method has changed from holding content to holding some sort of event, and I can't wrap my head around how this is supposed to work. I'm sorry for the vague/generic original post, I'll try to be more specific in the future.
Thanks for your help!
| |
The simplest solution here seems to be to update your custom controller A.B.Controllers.AuthenticationController to have a unique name so that it doesn't conflict with the Sitecore one.
The risk of trying to change the Sitecore references to that controller are high and it would potentially make any future upgrades more complex as you would have to make sure that customization was carried over. I would just change your custom A.B.Controllers.AuthenticationController to a new name or a new Area and that should solve the issue.
| How to override/replace the default Sitecore Authentication Controller
I upgraded my site from 7.5 to 8.1 and when I try to click on Sitecore logout link I have the following error:
Multiple types were found that match the controller named 'Authentication'.
This can happen if the route that services this request ('sitecore/shell/api/sitecore/{controller}/{action}')
does not specify namespaces to search for a controller that matches the request. If this is the case,
register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces'
parameter.
The request for 'Authentication' has found the following matching controllers:
Sitecore.Controllers.AuthenticationController
A.B.Controllers.AuthenticationController
My question is how I can change the controller name for Sitecore logout to use the full name of the controller I mean with namespace?
| |
Change your script in a following way:
$targetTemplate = Get-item 'master:/sitecore/templates/User Defined/Common/Data';
$templateFilter = Get-Item "master:/sitecore/templates/System/Templates/Template Field";
Get-ChildItem $targetTemplate.FullPath -recurse | Where-Object { $_.TemplateName -eq $templateFilter.Name -and $_.type -eq 'Rich Text'} | ForEach-Object {
$_._Source # <- Here's the change, added underscore before the Source
$_.Name
$_.Type
}
| Unable to get value of $_.Source using SPE
I have a rich text field in my user defined template and I want to replace the source value of the rich text field. Below is my query where I'm able to read Name, type etc, however $_.source is something which returns nothing though the source value still exists. Any help please.
$targetTemplate = Get-Item 'master:/sitecore/templates/User Defined/Common/Data';
$templateFilter = Get-Item "master:/sitecore/templates/System/Templates/Template Field";
Get-ChildItem $targetTemplate.FullPath -recurse
| Where-Object { $_.TemplateName -eq $templateFilter.Name -and $_.type -eq 'Rich Text'}
| ForEach-Object {
$($_.source)
#$_.Name
#$_.Type
}
| |
Quick test confirms that the following allows you to set a rendering parameter on existing items.
# Path to the Coveo rendering you need to update
$rendering = Get-Item "master:\sitecore\layout\Sublayouts\Sample Sublayout"
# Update this value for the path of all the templates whose std vals you wish to update
$items = Get-ChildItem -recurse master:\sitecore\templates\Sample
$items | % {
$renderingInstance = Get-Rendering -Item $_ -Rendering $rendering
if ($renderingInstance) {
Set-Rendering -Item $_ -Instance $renderingInstance -Parameter @{
# Put new/changed rendering parameter name and value here
# Other existing values should be unchanged by this
"Lorem" = "Ipsum"
}
Write-Host "Updated $($_.Paths.FullPath)"
}
}
More information:
Get-Rendering
Set-Rendering
| Update same rendering of several templates using SPE
I have a bunch of templates that have a Coveo Search Box View rendering associated with the standard values. I need to update the property "Reveal Advanced Query Suggestions" of all of them(a lot of templates in this case) and set them all to checked = false. Although I could manually update them all I'm looking for an automated way of doing such a task. Anyone have done anything similar using Sitecore PowerShell?
I do have the PowerShell documentation and if I spend some time and play with it I'll figure that script on my own just wondering if anyone has ever done anything similar that they could share?
Thanks
| |
In your command there is a QueryState method where you can hide or disable buttons.
Return:
CommandState.Hidden to hide the button
CommandState.Disabled to disable the button
CommandState.Enabled to enable the button
An example is shown below:
public class MyCommand: Command
{
public override void Execute(CommandContext context)
{
//main stuff here
}
public override CommandState QueryState(CommandContext context)
{
Error.AssertObject((object) context, "context");
if (context.Items.Length == 0)
{
return CommandState.Disabled;
}
if (context.Items[0].TemplateID.ToString() != "{4F3D0700-F7E0-47E9-903E-FCA1CB08830C}")
{
return CommandState.Disabled;
}
return base.QueryState(context);
}
}
| Enable Content Editor button depending on template type
I'm building a custom content editor button which will issue a command passing the ID of the selected item. Is there a way to enable/disable my button based on the template of the selected item. I want my command to only be run-able for items of a specific template. Obviously I could simply check the template ID of the item within my command handler code (which I will do anyway) but I would like to make this a bit more user-friendly.
As a (sort of similar) example, if you select an item with no children, the delete-subitems button under the main delete button disappears. I couldn't see any obvious mechanism about how this works though.
| |
The following setup may take some effort, but it will give you proper status codes, as well as "keeping" the requested URL, avoiding superfluous requests between Sitecore and IIS, and allow other processors and modules in your solution to seamlessly return a 404 page if required. It's been my experience that without the following setup, there is inconsistency in how Sitecore solutions return 404 pages and status codes. I've also found that in a completely ironic fashion, sometimes these pages can cause infinite redirect loops or undue strain on the IIS instance.
The high-level overview looks something like this:
Have a 404 page item under your SiteRoot, with a rendering control that uses code to properly set a 404 status code.
Have a 404 processor in the httpRequestBegin pipeline to override Sitecore's default 404 functionality, so that clients aren't redirected and the requested URL is preserved.
Have a 404 processor in the mvc.getPageItem pipeline to force URL's that map to items to return a 404 when appropriate.
Do make sure to configure the ItemNotFoundURL setting to the 404 page item URL within your site.
<setting name="ItemNotFoundUrl" value="/404" />
Web.config
Set the existingResponse attribute to "Auto" to give your website control over how status codes get handled. The "Auto" mode allows you to set Response.TrySkipIisCustomErrors to true to bypass the default IIS 404 page, or anything that's been defined in the httpErrors configuration node.
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto">
<!-- We don't want to interact with Sitecore or any part of the site
that could be causing the HTTP 500 error in the first place, so
it's a good idea to make sure that you have a static 500 page outside
the purview of Sitecore or any other "dynamic systems" within the
application pool/site instance.
-->
<error statusCode="500" path="/static/errors/500.html" responseMode="File"/>
</httpErrors>
Setting the Status Code with a 404 Rendering Control
We need to either have a Controller Rendering or a View Rendering that has code to set a few different properties to allow us to properly return a 404 status code.
There are two critical properties that must be set in your rendering: one obviously being the Response.StatusCode to 404, and the other to set Response.TrySkipIisCustomErrors to true. Remember, TrySkipIisCustomErrors will cause IIS to ignore the configuration in the httpErrors configuration node since we've set the existingResponse attribute on that node to "Auto".
public ActionResult Request404Page()
{
HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.StatusDescription = "404 File Not Found";
return View();
}
Create a 404 Processor
Use a custom HttpRequestProcessor at the end of the pipeline to handle when a context item has not been resolved. This processor exists only to avoid Sitecore's default functionality of redirecting to the 404 page. Instead of redirecting the client or use a server side only redirect, the goal is to leave the URL alone and avoid causing a messy client experience. This is achieved merely by setting the Context.Item and ProcessorItem properties to your desired 404 page.
public class 404HttpRequestProcessor : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
if (Sitecore.Context.Item != null || Sitecore.Context.Site == null)
{
return;
}
if (string.Equals(Sitecore.Context.Site.Properties["enableCustomErrors"], "true", StringComparison.OrdinalIgnoreCase) == false)
{
return;
}
var pageNotFound = this.Get404PageItem();
args.ProcessorItem = pageNotFound;
Sitecore.Context.Item = pageNotFound;
}
protected Item Get404PageItem()
{
// This is largely up to how the project in general is setup.
// My solutions are heavily Fortis dependent, but for Vanilla
// Sitecore setups you could just use the following setting:
// Settings.GetSetting("ItemNotFoundUrl", "/errors/404");
// and pull the Item object from that path
var path = Sitecore.Context.Site.RootPath + "/" + Settings.GetSetting("ItemNotFoundUrl", "/errors/404");
var item = Sitecore.Context.Database.GetItem(path);
return item;
}
}
Patch your custom 404 processor, in this example called 404HttpRequestProcessor, at the end of the httpRequestBegin Pipeline.
<processor type="MyProject.Pipelines.HttpRequest.404HttpRequestProcessor, MyProject.Core"
patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']">
</processor>
Now we have the following:
A 404 page within sitecore that we can customize in anyway we want.
We avoid redirecting the client, so they don't lose their URL or break the back button.
There's no spaghetti setup within IIS that bounces requests back and forth between IIS and Sitecore.
But we're not quite done yet!
404'ing URL's That Map to an Item
Unfortunately, the above setup will only work if you type in a URL that does not map to an item in your content tree (e.g. "www.mywebsite.com/page-item/that/does-not-exist"). Even if you set Context.Item to null in your httpRequestBegin pipeline, Sitecore will "re-resolve" that URL in the mvc.getPageItem pipeline if that URL happens to map to an item in Sitecore. There are certain situations where you want to return 404 for a URL that technically exists, but if this scenario is not applicable to your project you don't need to include the following processor.
To 404 a URL that technically maps to a content item, we need to add a processor to the mvc.getPageItem pipeline. The code will be excruciatingly similar to the 404RequestProcessor processor we added in the httpRequestBegin pipeline, we'll just be modifying a few different "sister" properties to properly exit the mvc.getPageItem pipeline. Of course, since both processors are similar it's possible to abstract the code out and avoid duplication, but I'll leave that as an exercise to the reader.
It is assumed at this point that a previous processor in the pipeline doesn't like something about the current request, so that processor set args.Result to null.
public class 404PageItemProcessor : GetPageItemProcessor
{
public override void Process(GetPageItemArgs args)
{
if (args.Result != null || Sitecore.Context.Site == null)
{
return;
}
if (string.Equals(Sitecore.Context.Site.Properties["enableCustomErrors"], "true", StringComparison.OrdinalIgnoreCase) == false)
{
return;
}
var pageNotFound = Get404PageItem();
args.ProcessorItem = pageNotFound;
args.Result = pageNotFound;
Sitecore.Context.Item = pageNotFound;
}
protected Item Get404PageItem()
{
// This is largely up to how the project in general is setup.
// My solutions are heavily Fortis dependent, but for Vanilla
// Sitecore setups you could just use the following setting:
// Settings.GetSetting("ItemNotFoundUrl", "/errors/404");
// and pull the Item object from that path
var path = Sitecore.Context.Site.RootPath + "/" + Settings.GetSetting("ItemNotFoundUrl", "/errors/404");
var item = Sitecore.Context.Database.GetItem(path);
return item;
}
}
Please pay attention to the fact that the code above sets two properties on the GetPageItemArgs object: ProcessorItem and Result. Both of these properties must be set to the desired 404 page or Sitecore will simply ignore the property value that you set (for reasons I will not get into in this post).
Now, just add the 404PageItemProcessor to the end of the mvc.getPageItem pipeline.
<processor type="MyComp.Pipelines.GetPageItem.404PageItemProcessor, MyComp.Core"
patch:after="processor[@type='Sitecore.Mvc.Pipelines.Response.GetPageItem.GetFromOldContext, Sitecore.Mvc']">
</processor>
Handling fatal errors and HTTP 500 codes
It's my opinion that 500 errors should simply return a static 500 page and not bother with doing anything needlessly fancy. The httpErrors configuration at the top of this post will give you sufficient handling of HTTP 500 error codes, since HTTP 500 status codes are typically thrown when something terrible has happened. The following will log any uncaught errors but still obey your configuration (while technically allowing you to override those settings as well). I've personally found it extremely helpful when attempting to debug fatal errors.
Add the following method to your Global class in your website project's Global.asax.cs file:
protected void Application_Error(object sender, EventArgs e)
{
var error = Server.GetLastError();
Server.ClearError();
var httpException = error as HttpException;
Response.StatusCode = httpException != null ? httpException.GetHttpCode() : (int)HttpStatusCode.InternalServerError;
Sitecore.Diagnostics.Log.Fatal("Uncaught application error", error);
}
You can find more information about the code in the Application_Error method above and the ideas behind it in various posts around StackOverflow, including this one: https://stackoverflow.com/questions/1171035/asp-net-mvc-custom-error-handling-application-error-global-asax.
| How do you setup a 404 and 500 error page for missing files and media items?
When navigating to a url such as www.website.com/missing.pdf and www.website.com/-/media/missing.pdf you will either receive the IIS 404 Server Error message or a Sitecore document not found page.
What is a solid approach to handling these scenarios?
Some requirements:
Should support files and media items.
Should return the proper response status codes (i.e. 404, 500).
Should support the use of content items that represent the friendly page (such as a site map).
@jammykam recommended the following
Web.config settings
<!-- Enable for IIS 7+ -->
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="/utility/404" responseMode="ExecuteURL" />
<error statusCode="500" path="/utility/500.html" responseMode="File" />
</httpErrors>
<!-- Disable for IIS 7+ -->
<customErrors mode="Off" />
where the 404 an 500 content items have a rendering with the following
public ActionResult Index()
{
var errorCode = this.mappingProvider.GetCurrentItem<ErrorCode>();
errorCode.StatusCode = Sitecore.MainUtil.GetInt(errorCode.StatusCode, 404);
if (Sitecore.Context.PageMode.IsNormal)
{
Response.TrySkipIisCustomErrors = true;
return new HttpStatusCodeResult(errorCode.StatusCode);
}
return View("~/Views/Developers/Common/StatusCode.cshtml", errorCode);
}
Update
After reviewing Justin's response here is what I ended up doing.
Updated web.config to handle <httpErrors> with existingResponse="Auto".
Updated ItemNotFoundUrl to an item in the tree such as /home/404.
Updated FilterUrlExtensions to allow for files with the extension .pdf.
Patch MediaRequestHandler to use Server.TransferRequest to avoid the error Error executing child request.
Added a controller rendering to Sitecore to change the status code.
Added a processor to handle the ItemNotFoundUrl setting, load the item, and set to the context item.
In case you are implementing and encounter an Error executing child request message then you may find this article helpful.
<setting name="RequestErrors.UseServerSideRedirect" value="true"/>
| |
From the vanilla instance it should be easy to package up the Roles you are missing and then just install that package on your client instance. I have had to do that before. Packaging roles is nice and simple.
| Roles are missing from Role Manager. How would I restore the roles for the newer version?
My client has fairly recently upgraded their Sitecore from 7.2 to 8.1 Update 3. They are using EXM. We realized today that many of the newer Sitecore 8 roles are missing from Role Manager (which is kept in the Core database as part of the ASP.NET membership provider).
I know I can Serialize and Revert from the file system through Role Manager. However, my client has hundreds of additional roles created that I don't want to get rid of.
I have a vanilla 8.1 U3 instance where I can grab the roles from.
So really two questions:
Does Revert All Roles (from file system) delete roles that aren't in the file system?
UPDATE #1: Turns out Revert does delete roles. (From my sandbox Sitecore instance)
2. Is there a recommended Best Approach for moving roles from my Vanilla 8.1 U3 site to the Client implementation?
| |
Pre Sitecore 8.1 (which splits out the Sitecore node into /App_Config/Sitecore.config) - I generally create my own Sitecore.config and patch that into the web.config in the same way as the connection strings is done.
Then yes, I just have the resulting web.config from my Sitecore installation in the web project. With debug transforms for local development.
So assembly bindings would be added in there.
With 8.1+ the removal of the Sitecore node is done for you, so just add the web.config from the installation to your web project and use that.
| What is the best practice for managing Web.config changes in a solution?
To my knowledge, it is considered a best practice not to include any of Sitecore's out-of-the-box configuration files into Visual Studio web projects. The reason being, if you handle all configuration changes as custom patch files (rather than directly modifying the default configuration), updating Sitecore to a newer version will be much easier.
But what should I do with Web.config changes? This file cannot be patched by Sitecore configs. At the same time, Sitecore's Web.config already has a lot of configuration, so I cannot replace it with my own.
I currently need to add a new assembly binding redirect. Do I just include the Web.config that's included with Sitecore into my web project? Or is there any other way?
| |
It has been determined that List Manager in Sitecore 8.1 is not as efficient as it could be. Sitecore Support KB Reference Number 431777 assists with List Manager issues. With this installed, List Manager seems to function better, albeit still not as fast.
Instead, the answer from Sitecore Support is that List Manager as a product is being overhauled and rewritten.
Speculation is that there may be a List Manager Hotfix/Update out of cycle before Sitecore 8.3 is released, however, normally List Manager is released with updates on the same schedule as the over all product.
How does this tie into EXM?
EXM uses all List Manager functions now to manage recipient lists. So if you're struggling with lists like I was, contact Sitecore Support and explain that you need all of the List Manager KB's as well as the EXM 3.3 Hotfix.
| Is there anyway to improve the speed that List Manager builds a list?
In Sitecore 8.X, the List Manager is the primary tool used to import contacts and create audience lists for Sitecore. This is a dependency in EXM as well for creating message dispatches against a List Manager list.
When a list is created, it goes through a couple steps:
Sitecore creates the stub of the list as an item in Sitecore.
Sitecore then locks the list from any pending changes.
During the lock phase:
Sitecore Creates the xDB contact.
Sitecore adds to the sitecore_list_index the list information.
Once the lock phase is complete, Sitecore unlocks the list and it can be used for consumption.
The main issue at hand is that for some reason, writing to the sitecore_list_index takes an enormous amount of time. Creating a list of 2 users has thus taken 5 minutes. When I have a CSV of 90,000 that I need to upload.
A little bit about our indexing. We are using Solr Server 6 for all indexes. (Yes, we know Solr 6 isn't an approved version, but so far, we not have any issues and all tests are coming back very positive. The master index builds very fast.)
The sitecore_list_index is very small.
Question: How do I improve this experience? Am I even able to?
UPDATE 1:
I don't think it's Indexes. According to the log, the index is getting processed and updated almost immediately.
ManagedPoolThread #11 16:13:33 INFO Job started: Index_Update_IndexName=sitecore_list_index
ManagedPoolThread #9 16:13:33 INFO Job ended: Index_Update_IndexName=sitecore_master_index (units processed: )
ManagedPoolThread #9 16:13:33 INFO Job started: Index_Update_IndexName=sitecore_master_index
ManagedPoolThread #17 16:13:33 INFO Job started: CONTACT_BULK_UPDATE_ListManagementImportContacts_cbaf9d6805a74a509e0413ac2fd751b7
ManagedPoolThread #11 16:13:33 INFO Job ended: Index_Update_IndexName=sitecore_list_index (units processed: )
ManagedPoolThread #4 16:13:33 INFO Job started: Index_Update_IndexName=sitecore_list_index
ManagedPoolThread #17 16:13:33 INFO Job ended: CONTACT_BULK_UPDATE_ListManagementImportContacts_cbaf9d6805a74a509e0413ac2fd751b7 (units processed: 2)
ManagedPoolThread #4 16:13:33 INFO Job ended: Index_Update_IndexName=sitecore_list_index (units processed: )
ManagedPoolThread #8 16:13:33 INFO Job started: Index_Update_IndexName=sitecore_list_index
UPDATE 2:
Turns out that the order of operations is first indexing, which isn't the issue. Then the next operation is something to do with the EventQueue table. List Manager puts entries in it for processing of something. So if EQ table is jammed, this runs long. But I still don't understand that. So question still applies.
| |
You'll want to make sure that you update all your projects to .NET 4.5.2+ in the Project Properties Screen. You'll need to do this for every project in the solution.
You will also want to make sure the VS Extention for Microsoft Practices is updated.
Also, do not use the SOLR Support Packages DLL. SOLR is now natively in the Sitecore dll's. Just enable the 8.2 Solr configs.
| Microsoft.Practices.ServiceLocation assembly not loading
I'm upgrading my Sitecore 8.1 Visual Studio project to use Sitecore 8.2, and I've made quite a bit of progress. I've switched to SOLR, updated Glass Mapper, and replaced out my DLL references to use the Sitecore supplied NuGet package manager. The issue that I've hit now I believe is related somehow to the new SOLR implementation that doesn't use DI. I am getting the following error:
Server Error in '/' Application.
Could not load file or assembly 'Microsoft.Practices.ServiceLocation,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The located assembly's manifest definition
does not match the assembly reference. (Exception from HRESULT:
0x80131040)
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or
assembly 'Microsoft.Practices.ServiceLocation, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to
determine why the assembly 'Microsoft.Practices.ServiceLocation,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
could not be loaded.
WRN: Assembly binding logging is turned OFF. To enable assembly bind
failure logging, set the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There
is some performance penalty associated with assembly bind failure
logging. To turn this feature off, remove the registry value
[HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly
'Microsoft.Practices.ServiceLocation, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)]
Sitecore.ContentSearch.SolrProvider.SolrNetIntegration.IntegrationHelper.IsSolrConfigured()
+0 Sitecore.ContentSearch.SolrProvider.Pipelines.Loader.InitializeSolrProvider.Process(PipelineArgs
args) +28 (Object , Object[] ) +71
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName,
PipelineArgs args, String pipelineDomain) +22
Sitecore.Nexus.Web.HttpModule.Application_Start() +259
Sitecore.Nexus.Web.HttpModule.Init(HttpApplication app) +704
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +618
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +343
[HttpException (0x80004005): Could not load file or assembly
'Microsoft.Practices.ServiceLocation, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+112 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +712
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.6.1055.0
I've tried several things, including changing the dependentAssembly to point to the correct publicKeyToken (which is 59d6d24383174ac4 and not 31bf3856ad364e35 as the error message suggests). I'd appreciate any help that you all can provide. Thanks!
| |
When adding a new project, simply create the project "code", and then rename the project and namespace to your preferred name.
Check out the following workshop video:
https://youtu.be/4lC-SdYh4Xg?list=PL1jJVFm_lGnz0XzXU5uNJSgTGMxNFsOky
The Yeoman generators are great for setting up additional parts like the .config, TDS, unit tests etc.
https://www.npmjs.com/package/generator-prodigious-helix
| Changing the Helix file system folder structure
Looking at Sitecore Habitat, each Visual Studio project is in a folder named 'code'. In Visual Studio, by default this folder is named the same as the project. I can rename this folder, but I have to jump through some hoops (remove the project from the solution, rename the folder, re-add the project to the solution... Plus maybe some source control shenanigans). Is there a simpler way to do this? Helix has a lot of projects... Some settings? Do I need a custom vsix?
| |
When Sitecore gets reconfigured to use another container; will that container also be used to resolve these entries?
It depends on how that other container gets configured, exactly. If you use the approach of patching the <serviceProviderBuilder>, then the container gets replaced completely and there's only one DI implementation. This would be my recommendation, as it seamlessly integrates your container into Sitecore. This way, the services that you configure with <services> –> <register> will be handled by your container of choice.
On the other hand, if you only replace the MVC dependency resolver, then there will be two containers: one used in Sitecore, and another in your application. Sure, you can manually copy all Sitecore service registrations into your container, but there will still be two containers running side-by-side.
Am I really not saving anything because Sitecore already references Microsoft.Extensions.DependencyInjection and one more reference from a module will make no difference at all?
That's how I see it as well. The assembly will be loaded into memory anyway by Sitecore, so referencing it from your modules won't make anything worse.
The decision of whether to use code or XML configuration to register your services is a matter of personal preference.
Doing it like this is agnostic towards the actual container in use; saves me a project reference to any container. Seems like a win/win. But is it?
Well, it will be agnostic to the container, but instead it will be tied to Sitecore's XML registration format, which has even fewer features than IServiceProvider. If that works for you, then by all means, go ahead with it.
Just keep in mind that this way you won't have an option to do things like mass-registration. E.g. with Autofac:
builder
.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t =>t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(IService))))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
| Should I reference Microsoft.Extensions.DependencyInjection in modules I create for Sitecore 8.2+?
So I'm in the process of upgrading various modules to Sitecore 8.2. Among other things this involves getting rid of IoC container project references and getting on board with the Sitecore one.
And herein lies my question.
It seems to me that if I just add a reference to Microsoft.Extensions.DependencyInjection I am really just replacing one DI reference with another one. Also; what if the main project that my module will plug into, has that container replaced - like with SimpleInjector or Unity or such?
Reading through Kam's post on DI in 8.2 it seems to me that the best approach for a module would be to use Direct Registration. Like so:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<services>
<register
serviceType="Type.IName, Assembly"
implementationType="Type.Name, Assembly"
lifetime="Transient" />
</services>
</sitecore>
</configuration>
Doing it like this is agnostic towards the actual container in use; saves me a project reference to any container. Seems like a win/win. But is it?
When Sitecore gets reconfigured to use another container; will that container also be used to resolve these <register /> entries? (as opposed to what Kam suggests; resolve these via Reflection)
Am I really not saving anything because Sitecore already references Microsoft.Extensions.DependencyInjection and one more reference from a module will make no difference at all?
| |
Apparently the fact that we were using a custom index was an important factor after all. Sitecore Support gave us a solution:
It seems that if you have a custom index with its own configuration the language is stored in the index in a short format. We had to include the _language field as defined in the standard config in the fieldmap of our custom index. So we add this to the custom fieldmap:
<field fieldName="_language" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
<analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />
</field>
It seemed weird that this fixes our issue, but it does. Somehow I expected the standard Sitecore fields in the custom index to come from the default configuration but apparently they do not.
I also checked the search log files (should have done that sooner) and now the queries show full languages instead of short ones as before. And we get the correct results.
| Lucene _language field TOKENIZED - how do I search on language?
In our Sitecore site we have a few 'English' languages:
en
en-GB
en-US
We wanted to do a search using the Lucene index (a custom one, but that doesn't actually matter) and included the language in it to get only results for the current language. But when we search on "en" we also get results for the other "en" based languages. When we search on "en-gb" we get nothing.
We tried Luke and got the same results. So I assumed the field would be tokenized and indeed, in the default Lucene config I found:
<field fieldName="_language" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
<analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />
</field>
This explained the behavior, but now I am wondering if we can search on language (when having multiple 'English' languages) without adding a custom field for this?
| |
As far as I remember, Sitecore 8 support for Sheer has been dropped in favour of SPEAK.
Here you can find more information on how to convert a button from Sheer to SPEAK.
In essence you have to use JavaScript for that and create a function according to the template below:
define(["sitecore"], function (Sitecore) {
Sitecore.Commands.YourCommandName = {
canExecute: function (context) {
return true; // check if the command can execute
},
execute: function (context) {
var id = context.currentContext.itemId;
var lang = context.currentContext.language;
var ver = context.currentContext.version;
// here comes your code
alert("Error!"); // use javascript here to show info or ask for confirmaiton
}
};
});
Then connect it to the presentation of the button. Refer to this link for the detailed information.
More info about Speak can be found here.
| How do I display an error dialog from content editor command?
How do I show an error style dialog (i.e. with red error logo and the expand text) from a content editor command?
I've tried to use SheerResponse.ShowError(). The content editor greys out like it does for regular modals / dialogs, but no error message appears. I'm using Sitecore 8.0 update 3. My code is below:
public class MyCommand: Command
{
public override void Execute(CommandContext context)
{
var nameValueCollection = new NameValueCollection();
if (context.Items.Length == 1)
{
Item item = context.Items[0];
if (item != null
&& item.TemplateID.ToString() == Templates.RedirectSettings.TemplateId)
{
nameValueCollection["id"] = item.ID.ToString();
Sitecore.Context.ClientPage.Start(this, "DoStuff", nameValueCollection);
}
}
}
protected void DoStuff(ClientPipelineArgs args)
{
var itemId = args.Parameters["id"];
if (!args.IsPostBack)
{
SheerResponse.Confirm("Do stuff now?");
args.WaitForPostBack();
}
else if (args.Result == "yes")
{
var everythingOk = //do some stuff and check if successfull..
if (everythingOk)
{
SheerResponse.Alert("Everything worked ok", true, "It's ok");
}
else
{
//something went wrong
SheerResponse.ShowError("My short description", "Detailed description...");
args.WaitForPostBack();
}
}
}
| |
Root cause was
- Item existed in EN version and when trying to preview in other language it should fallback to EN. Now twist here was EN version had publishing restrictions so effectively item didn't existed in any language versions which somehow gives error, from Item-level Language Fallback module, in page when trying to use preview mode.
I have fixed this issue by modifying the Item-level Language Fallback module's source.
I have downloaded module source from Sitecore marketplace. Recompiled module source with modified class as below..
public class LanguageFallbackItemProvider : ItemProvider
{
protected override Item GetItem(ID itemId, Language language, Version version, Database database)
{
... some code ...
Item fallback = GetItem(itemId, fallbackLanguage, Version.Latest, database);
/* FIX START - TO CHECK FALLBACK ITEM IS NULL */
if (fallback == null)
{
return item;
}
/* FIX END - TO CHECK FALLBACK ITEM IS NULL */
var stubData = new ItemData(fallback.InnerData.Definition, item.Language, item.Version, fallback.InnerData.Fields);
... some code ...
}
}
| Item Language Fallback doesn't work for Sitecore query
This is for Sitecore 7.5 update-2 version.
We are using Item-level Language Fallback and everything works fine except this piece gives error every time except when in Page Editor mode.
item.Axes.SelectSingleItem('ancestor::*[@@templateid='GUID']//*[@@templateid='GUID']')
Above code returns NULL object when trying to fetch item in language version which it doesn't exist. Since we have Item-level Language Fallback configured I'm unable to understand why this doesn't fallback when using Sitecore query.
Anyone has any idea on this appreciated or did you faced same issue anytime?
| |
This should give you what you want:
@using (Html.Glass().BeginRenderLink(Model, m => m.MyLinkField, null, true) {
@Html.Glass().RenderImage(Model, m => m.MyImageField, null, true)
}
| Editable Sitecore fields with Glass
Folks
I'm trying to do something basic here which is have a general link and an image field as editable in experience editor on my view using Glass.
my end goal is to have two editable fields which are rendered as:
<a><img></img><a>
I am trying to do something like this but this is not working well
@Html.Glass().Editable(Model, m => m.MyLinkField, new { img = Model.MyImageField })
Anyone know what I'm missing here?
| |
It usually means that a Url for a media asset is missing the Hash query string parameter when being called.
This was introduced in v7.5. It attempts to fix an image resize vunerability where you could potentially fill a disk with different image sizes.
If you use a FieldRenderer you will get a valid url with the Hash query string appended.
If you just generate the url, you will need to add the hash. Fortunately Sitecore has some utilities to do that:
Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl : will return the full Url with the hash added.
Use:
Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(
Sitecore.Resources.Media.MediaManager.GetMediaUrl(
myMediaItem,
new MediaUrlOptions()
{
Language = Context.Language,
Width = 100,
Height = 75
}));
| MediaRequestProtection: An invalid/missing hash value was encountered
My Sitecore error logs contain messages such as:
ERROR MediaRequestProtection: An invalid/missing hash value was encountered. The expected hash value...
What would be causing this? This is only for Sitecore 8 and newer.
Does it have anything to do with the Media.RequestProtection.SharedSecret configuration setting?
| |
SIM doesn't perform the post-install steps (running the SQL script, updating the web.config for captcha, etc...). It does "complete", for all intents and purposes, but SIM gets stuck on the placeholder selection dialog at the end of the installation.
But apart from that, everything is installed as it should be.
| Installing WFFM with SIM - post-install steps
When installing the WFFM module with SIM, does it perform the post-install steps for you, like running the SQL script against the reporting database or updating the web.config for the captcha controls?
I noticed when I tried adding that module to a SIM install that the SIM installation eventually just hangs.
Thanks in advance!
| |
I have implemented several search based sites on top of the Lucene provider, and for me the system is consistent and reliable. When I have had that sort of problems with the index in the past it was due to two reasons:
The scope of my SearchContent: I was reusing it too much, meaning my results were not updated, even when the actual index was. As the index was constantly updated, I had to call Index.CreateSearchContent each time I had to search.
Obsolete items in the index: I managed to fix it following this KB
| Lucene index corruption
I've had a serious problem with several clients while utilising a Lucene search index where anomalies like content missing that should be there or duplicate content (more than one document of the same content item that both have the islatest flag). In many cases an index rebuild will fix it, but more often than not a rebuild will simply shuffle around the anomalies.
Ultimately I'm asking is there a way to configure the search index to be more consistent and reliable?
Note that I'm specifically talking about the sitecore_master_index and sitecore_web_index.
| |
You can set this in the web.config. In your membership section. You can set a password strength regular expression.
<add name="sql" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="core"
applicationName="sitecore"
minRequiredPasswordLength="8"
minRequiredNonalphanumericCharacters="1"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
passwordStrengthRegularExpression="^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$" />
I found this regex ^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+]{7,19}$ for your requirements: Regex Source
| How do I set password complexity?
I need to change the password complexity requirements for authors to meet corporate standards of a password being:
Minium of 8 characters
Contain at least one numeral
Contain at least one symbol
| |
Sitecore supports two ways to render the Content Editor.
Standard Sitecore Render
Themed XML Skin Rendering
The pipeline you want to focus on is <renderContentEditor>.
You'll find the following:
For the purpose of this answer, I'll focus on how to override the
Standard Content Editor. I would probably advocate for using the
Theme/Skinning option that is available, but will need to defer that
answer until I am more versed in how to do the themeing.
If you look at Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderStandardContentEditor pipeline process you'll find that it is calling the EditorFormatter class RenderSections(...)
public class RenderStandardContentEditor
{
/// <summary>Gets the field value.</summary>
/// <param name="args">The arguments.</param>
/// <contract>
/// <requires name="args" condition="none" />
/// </contract>
public void Process(RenderContentEditorArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
args.EditorFormatter.RenderSections(args.Parent, args.Sections, args.ReadOnly);
}
}
Digging down further, you'll find that RenderSections is calling RenderSectionBegin(...).
The real issue with the Section Icon going away is that Sitecore decided just not to render the image. But as you can see from the decompiled code below, Sitecore still supports the section icon, just never utilizes it.
public void RenderSectionBegin(System.Web.UI.Control parent, string controlId, string sectionName, string displayName, string icon, bool isCollapsed, bool renderFields)
{
Assert.ArgumentNotNull((object) parent, "parent");
Assert.ArgumentNotNullOrEmpty(controlId, "controlId");
Assert.ArgumentNotNullOrEmpty(sectionName, "sectionName");
Assert.ArgumentNotNullOrEmpty(displayName, "displayName");
Assert.ArgumentNotNull((object) icon, "icon");
HtmlTextWriter htmlTextWriter = new HtmlTextWriter((TextWriter) new StringWriter(new StringBuilder(1024)));
if (this.Arguments.ShowSections)
{
string str1 = isCollapsed ? "scEditorSectionCaptionCollapsed" : "scEditorSectionCaptionExpanded";
string str2;
if (UserOptions.ContentEditor.RenderCollapsedSections)
str2 = "javascript:scContent.toggleSection('" + controlId + "','" + sectionName + "')";
else
str2 = "javascript:return scForm.postRequest('','','','" + StringUtil.EscapeQuote("ToggleSection(\"" + sectionName + "\",\"" + (isCollapsed ? "1" : "0") + "\")") + "')";
htmlTextWriter.Write("<div id=\"{0}\" class=\"{1}\" onclick=\"" + str2 + "\">", (object) controlId, (object) str1);
ImageBuilder imageBuilder1 = new ImageBuilder()
{
ID = controlId + "_Glyph",
Src = isCollapsed ? "Images/accordion_down.png" : "Images/accordion_up.png",
Class = "scEditorSectionCaptionGlyph"
};
htmlTextWriter.Write(imageBuilder1.ToString());
ImageBuilder imageBuilder2 = new ImageBuilder()
{
Src = Images.GetThemedImageSource(icon, ImageDimension.id16x16),
Class = "scEditorSectionCaptionIcon"
};
htmlTextWriter.Write(Translate.Text(displayName));
htmlTextWriter.Write("</div>");
}
if (renderFields || !isCollapsed)
{
string str1 = !isCollapsed || !this.Arguments.ShowSections ? string.Empty : " style=\"display:none\"";
string str2 = this.Arguments.ShowSections ? "scEditorSectionPanelCell" : "scEditorSectionPanelCell_NoSections";
htmlTextWriter.Write("<table width=\"100%\" class=\"scEditorSectionPanel\"{0}><tr><td class=\"{1}\">", (object) str1, (object) str2);
}
this.AddLiteralControl(parent, htmlTextWriter.InnerWriter.ToString());
}
Note that in this class, the icon comes in as part of the argument of the method. Highlighting the following piece:
imageBuilder2 contains everything that we need to know in order to render the Section icon. however, scanning this method, imageBuild2 is never utilized. Instead, immediately after imageBuilder2 is created, it writes the displayName.
However, if you look at the accordion image just above this:
You'll note that it's sending the image to the htmlTextWriter which sets up an awesome example as to how to implement the section icon as well.
SUMMARY
This actually smells like a Sitecore Bug. However, if it's completely intentional, and you want to activate the icon, I would create a custom RenderContentEditor pipeline processor, extend the EditorFormatter class and override RenderSectionBegin method, sending the icon to the HtmlTextWriter.
OP ED
Responding to @jammykam's comment, the amount of code changes that this would require, the reward gained by getting the icon back may not be worth it (in fact not worth it).
One must take into consideration upgradability, and maintainability.
Using a new processor, as described above, allows you to pull out the change relatively quickly and the approach above does not harm core functionality. However, if changes occur with this class (as they most certainly will) in order to maintain the icons, you'd have to update this custom class.
Lastly, while my professional recommendation is to not utilize all of this, just for the icon, and nor do I think creating a whole new XML Skin just for icon make sense either, this is a often requested feature from client who are used to the section icon.
Therefore my true feeling is to appeal to Sitecore to offer an easier toggle, config setting or otherwise, in order to display it. Otherwise, I would advocate against trying to implement this at all.
But it is possible! =)
| How do I get my section icons in the Content Editor to show again?
It used to be, that next to the collapsible sections in the Content Editor tab; the section icon would display on the tab. This made it very easy for me to identify the section I was looking for.
To clarify; this is where I mean:
In recent Sitecore versions, this has gone away. I presume it has to do with the Content Editor moving to SPEAK but I am not sure.
Is there any way to get this back? A setting or so? And if not, does anyone have an example of how this functionality could be overridden to bring the icons back in?
| |
It's a difficult one; a question I've considered many times over in the years I've been working with Sitecore.
I can start with some numbers. I've done perhaps 30 or so projects that involved data integration of some kind. 29 of which, I ended up importing the data. I've only ever done 1 project where I've implemented a full Data Provider - and I'll highlight why:
Data is often imperfect
This is especially the case for most e-commerce solutions I've worked. This is usually product data, product meta data, category trees and so on. It's very rare that one can source all of the required information (short descriptions, long descriptions, images, product attributes and so on) from the back-end systems. So what I've ended up doing; is doing multiple integration runs - enriching the product catalogue in each run. Then when complete - publish the enriched data.
Back-end systems are too slow for practical website use
This is especially true for ERP and PIM systems. They are designed with data integrity in mind, and only secondly have an eye on performance. If even that. Add to this; the nature of data in these systems is rarely a tree-like structure (rather; relational) - making it difficult to make them fit into the parent/child nature that a Sitecore Data Provider has to follow.
Lastly; if opening up a Data Provider to a back end system - it needs to be available all the time, or the Content Editor users find themselves out of work. And publishing an empty structure... doesn't really end so well.
Sitecore's data model is richer than most back-end systems
I argued this in Working with multiple content databases in Sitecore 6.
Sitecore offers versioning, language versions, workflows, many types of fields - right out of the box. Writing a Data Provider, one often ends up stubbing most of this functionality out, thus detracting from the overall Sitecore experience. The data looks like it's a native part of the Sitecore content tree, but it's really not.
So where?
Well I honestly don't see where I would use one today. Unless writing a very specialized tool - like Kamsar's Unicorn or so. For live use on the website? We have so many other ways of abstracting data - Dependency Injection, Services, Web APIs and so on - I really don't see any added value in feeding this data in via a Data Provider, just so we can use Sitecore Query (brr) to query it. I think Data Providers made sense, when XSLT was still the de-facto standard for rendering Sitecore content.
I think those days are behind us.
EDIT: elaboration
The whole point of a data provider is; to bring in content and have it appear as native Sitecore content. The idea being; you then bring in your content from multiple sources, and then have it work just like had it been created natively in Sitecore. And yes; part of that was based on creating XSLT renderings, and they shouldn't need to know what content was native and what was not - and with XSLT renderings there simply is no easy option to render non-Sitecore data.
So how are these used?
Well presumably your data provider is one-way. You can implement a 2 way provider but I've never had a business case for it. Usually one integrates to a business system and we can't just let any editor simply edit content (by mistake - in Experience Editor this could easily happen) and have it written back to the origin system.
So we feed in data from the provider; and we probably feed it directly into "master" and "web" in many instances, as support for publishing of provided data is extra work. Plus - you data provide to have a real time view to the origin system and publishing would sort of ruin that idea. Now you have to decide how to deal with caches; external link to origin system breaking down (and taking your solution down in the fall)... meh the list just goes on.
So what can we do instead?
Lots. Ruling XSLT out again; say you wanted to reach data from a back end CRM database. Your Helix feature would be something like "CRM Integration" (pardon me if not up to speed on any naming conventions in Helix). And go for it; provide the project layers with ICrmIntegration if you want. And if you desperately crave a Sitecore Item tree, nothing is stopping you from mocking one up at this point. Especially not in new Sitecore releases. Something like
var customersRoot = _crmIntegration.GetCustomersRoot();
foreach(Item customer in customersRoot.GetChildren())...
Possible? Sure. But looking at it like this, it becomes obvious it just doesn't make much sense.
If there is a case for a Data Provider, it would only be a fully implemented 2-way provider. To save you having to write a web interface to update some data. Nothing else rings any kind of sense to me. Not today, not post XSLT. Not with models, Dependency Injection, Layered Architecture. We have so many better options available.
| What are some appropriate uses for Sitecore Data Providers?
Data Providers are difficult to develop, given the performance and data mapping challenges they can present. But they are powerful when done correctly:
Allowing real-time integration with external systems
Present as Sitecore items that can be used for linking or even to drive pages
Can enable editing of data in external systems via Sitecore
In what cases would one create a data provider instead of importing content? What are examples of practical integration scenarios which would benefit from a Data Provider implementation?
| |
If it's slow for only the first insertion of a specific component, but subsequent insertions of the same component are relatively fast, then you may benefit from tuning the prefetch cache.
Here's what the Sitecore manual states (source - Sitecore 6.6 manual):
The following sample demonstrates the XML structure for configuring
prefetch caches.
<configuration>
<cacheSize>20MB</cacheSize>
<childLimit>100</childLimit>
<template desc="reference">{EF295CD8-19D4-4E02-9438-94C926EF5284}</template>
<item desc="home">{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}</item>
<children desc="field types">{76E6D8C7-1F93-4712-872B-DA3C96B808F2}</children>
</configuration>
The <cacheSize> element controls the maximum size of the prefetch
cache. The <childLimit> element defines a limit to the number of
children to represent in the prefetch cache. If an item has more than
this number of children, Sitecore does not cache information about the
children of that item in the prefetch cache. The <configuration>
element can contain any number of <item>, <template>, and <children>
elements. For elements, Sitecore loads the specified item into
the prefetch cache. For elements, Sitecore loads all of the
items based on the specified data template into the prefetch cache.
For <children> elements, Sitecore loads all of the children of the
specified item into the prefetch cache.
So you'd probably be able to use the <children> element to include any essential content branches and all their children.
| Sitecore Experience Editor Slow on Servers?
Does anyone have any ideas why Experience Editor would take 5-6 seconds to display a component I add when running on development or staging servers vs less than 2 seconds when running Sitecore and the DBs locally? I know there is likely some latency between the CD and DB servers but this seems like a ridiculous difference. Especially since the servers are much higher spec than my machine. I've done all I can to optomise my code and what is loaded in Experience editor so am pretty stumped.
| |
The easiest solution is probably to find and replace characters rather than parse all of the html. Try this:
# Home Item
$rootId = "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"
# Get only the immediate children
$items = @((Get-ChildItem -Path "master:" -ID $rootId))
foreach($item in $items) {
$html = $item.Text
if([String]::IsNullOrEmpty($html)) { continue }
$newText = $html.Replace("<ul>", "<ol>").Replace("</ul>", "</ol>")
$item.Text = $newText
}
| How do I parse a Rich Text in PowerShell in order to replace elements?
I have a requirement to read each rich text field and then edit the content with unordered lists rather than ordered.
| |
I think this URL speaks to your issue: https://kb.sitecore.net/articles/404548
Among the other suggestions there, try to reload the perf counters:
Start an administrator command prompt.
Run unlodctr .NETFramework.
Run lodctr %WINDIR%\Microsoft.NET\Framework\\CORPerfMonSymbols.ini
where is the directory of the .NET Framework version which contains the CORPerfMonSymbols.ini file. It should be either v4.0.xxx or v2.0.xxx if 4.0 is not installed.
Restart IIS.
| WARN Could not register counter in HealthMonitor warnings in logs
I'm seeing a ton of these messages in my logs all the time. How can I clear them up?
Heartbeat 13:07:35 WARN Could not register counter in HealthMonitor. Category: .NET CLR Memory, Name: # Bytes in all Heaps, Instance: , InstanceType: CLR
Message: Category does not exist.
Heartbeat 13:07:35 WARN Could not register counter in HealthMonitor. Category: .NET CLR Memory, Name: % Time in GC, Instance: , InstanceType: CLR
Message: Category does not exist.
Heartbeat 13:07:35 WARN Could not register counter in HealthMonitor. Category: .NET CLR Memory, Name: Large Object Heap size, Instance: , InstanceType: CLR
Message: Category does not exist.
Heartbeat 13:07:35 WARN Could not register counter in HealthMonitor. Category: .NET CLR Loading, Name: Bytes in Loader Heap, Instance: , InstanceType: CLR
Message: Category does not exist.
Heartbeat 13:07:35 WARN Could not register counter in HealthMonitor. Category: .NET CLR Loading, Name: Current Assemblies, Instance: , InstanceType: CLR
Message: Category does not exist.
| |
Please, verify that your attribute "stored" is set to true:
<field name="_path" type="string" indexed="true" stored="true" multiValued="true" />
I had the behavior you mentioned when the stored attribute was set to false. Check you have that value set on all schemas
| SOLR schema is Invalid?
I have been tweaking my SOLR 5.4 schema and I have noticed this behavior:
If I have _path defined in my schema.xml, I do not see _path_sm (or _path) in my raw SOLR index. However, if I remove the _path definition from my schema.xml, then I correctly see _path_sm in my index.
The offending field is:
<field name="_path" type="string" indexed="true" stored="true" multiValued="true" />
And the field looks like this in SOLR:
<arr name="_path_sm">
<str>11111111111111111111111111111111</str>
<str>0de95ae441ab4d019eb067441b7c2450</str>
<str>3156c74fd8334b8f86815a17ebe69998</str>
<str>05e49a575ece46e98b73ce7f3fedc78d</str>
<str>fd17e8226ec8435ea522d32f986bb8e1</str>
<str>f9ce8111622a45e0b9cf2f88ea627c06</str>
<str>c7f77608398e457297890077a5500c73</str>
</arr>
Has anyone else noticed this behavior? Is there an elegant solution (besides just removing the field from my schema)?
| |
The problem with the simple injector container is that they do not provide a conforming container option. They don't like it. So to replace it with Simple Injector requires a bit more effort.
In this post Habitat DI with Simple Injector - I explained how to use SI in a conforming way to register your dependencies for Habitat projects.
You could take a similar approach with replacing the default Sitecore container. Using the custom ServiceProviderBuilder from the post in the question you could do this:
public class SimpleInjectorServiceProviderBuilder
: BaseServiceProviderBuilder
{
protected override IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection)
{
var container= new Container();
// Register Sitecore services in SI
var containerCache = new List<Type>();
foreach (var serviceDescriptor in dependencyInjectionArgs.ServiceCollection)
{
// Safety check so we don't try to register the same type twice
if (containerCache.Contains(serviceDescriptor.ServiceType))
{
continue;
}
Lifestyle siScope;
switch (serviceDescriptor.Lifetime)
{
case ServiceLifetime.Singleton:
siScope = Lifestyle.Singleton;
break;
case ServiceLifetime.Transient:
siScope = Lifestyle.Transient;
break;
case ServiceLifetime.Scoped:
default:
siScope = Lifestyle.Scoped;
break;
}
container.Register(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationType, siScope);
containerCache.Add(serviceDescriptor.ServiceType);
}
// Return service provider adaptor.
return container.Resolve<IServiceProvider>();
}
}
As you can see - instead of calling the .Populate method and passing the service collection in, you have to enumerate through the service collection and more manually register your services. (Please note, this is PoC and untested code :) )
| SimpleInjector as default DI in Sitecore 8.2
I read this post today about replacing Sitecores 8.2 default DI (https://medium.com/@structuredcode/replacing-the-default-di-container-in-sitecore-8-2-4e65d4956c99), but the example is for Autofac. We use SimpleInjector, but I'm sure not how to do this for SimpleInjector; does anyone have any examples?
| |
Source: https://stackoverflow.com/questions/33235368/sitecore-current-contact-is-locked-for-identification
Why this happens
Normally, you will see this error when you forget to set Analytics.ClusterName in the configuration file Sitecore.Analytics.Tracking.config. This becomes a problem because in the beginning of every session Sitecore lock the current contact by creating a Lease in xDB. It uses Analytics.ClusterName as the identifier of the lock.
The error you are seeing occurs because your Sitecore instance doesn't realize that it owns the lease on the contact since the lease owner identifier is missing.
If you look at your contact in the collection database, you are likely to see something like this:
As you can see, the Owner document does not have the Identifier field set. This indicates that the entity that created the lease did not provide an identifier (its value was an empty string or null).
Solution
To solve this in a development environment, just set both Analytics.ClusterName and Analytics.HostName setting values to the local domain name you're using when accessing the application, e.g. ``sitecore.
<setting name="Analytics.ClusterName" value="sitecore" />
<setting name="Analytics.HostName" value="sitecore" />
You can read more about these settings here.
UPDATE: Sitecore has added a knowledge base article about this issue: https://kb.sitecore.net/articles/965127
| Contact is locked by another operation
I'm having an issue identifying xDB contacts... I'm trying to call the Identify() method in my controller action, but I see this error in the logs:
Exception: System.InvalidOperationException
Message: A contact is locked by another operation.
What am I doing wrong?
EDIT: Here's the full stack trace.
Exception: System.InvalidOperationException
Message: A contact is locked by another operation.
Source: Sitecore.Analytics.MongoDB
at Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbContactStorage.LoadContactIdentifier(ID contactId, LeaseOwner leaseOwner)
at Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbDataAdapterProvider.SaveContactWithIdentifier(IContact contact, ContactSaveOptions saveOptions)
at Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbDataAdapterProvider.<>c__DisplayClass9.b__7()
at Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbDataAdapterProvider.Try(Action action)
at Sitecore.Analytics.Data.DataAccess.MongoDb.MongoDbDataAdapterProvider.SaveContact(IContact contact, ContactSaveOptions saveOptions)
at Sitecore.Analytics.Data.ContactRepository.SaveContact(Contact contact, ContactSaveOptions options)
at Sitecore.Analytics.Tracking.ContactManager.SubmitContact(Contact contact, ContactSaveOptions options)
| |
It turns out there were 2 issues I was having:
Because I was customizing the core names I needed to include a node for sitecore_analytics_index. Based on this blog post I had left the node out thinking it wasn't needed.
Patch config order. My include file was getting patched too soon so the correct core names were not getting used.
| Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex. No matching constructor was found
I am trying to configure Solr for Sitecore 8.2. Solr is running and I have cores set up for each index and secondary cores set up for rebuilding. I'm not using the Solr support package.
I am getting the following error when trying to browse the site:
Could not create instance of type: Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex. No matching constructor was found.
I'm guessing, it's a configuration problem. However, I can't get to showconfig.aspx to see what the issue might be.
Below is the patch config for the indexes:
<indexes>
<index id="sitecore_core_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_core</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_core_2</param>
</index>
<index id="sitecore_master_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_master</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_master_2</param>
</index>
<index id="sitecore_web_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_web</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_web_2</param>
</index>
<index id="sitecore_marketing_asset_index_master" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_marketing_asset_master</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_marketing_asset_master_2</param>
</index>
<index id="sitecore_marketing_asset_index_web" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_marketing_asset_web</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_marketing_asset_web_2</param>
</index>
<index id="sitecore_marketingdefinitions_master" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_sitecore_marketingdefinitions_master</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_sitecore_marketingdefinitions_master_2</param>
</index>
<index id="sitecore_marketingdefinitions_web" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_sitecore_marketingdefinitions_web</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_sitecore_marketingdefinitions_web_2</param>
</index>
<index id="sitecore_testing_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_testing</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_testing_2</param>
</index>
<index id="sitecore_suggested_test_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_suggested_test</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_suggested_test_2</param>
</index>
<index id="sitecore_fxm_master_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_fxm_master</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_fxm_master_2</param>
</index>
<index id="sitecore_fxm_web_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_fxm_web</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_fxm_web_2</param>
</index>
<index id="sitecore_list_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_list</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_list_2</param>
</index>
<index id="social_messages_master" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_social_messages_master</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_social_messages_master_2</param>
</index>
<index id="social_messages_web" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<patch:attribute name="type" value="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider"/>
<param desc="core">SitecoreSandbox_social_messages_web</param>
<param patch:after="*[@desc='core']" desc="rebuildcore">SitecoreSandbox_social_messages_web_2</param>
</index>
</indexes>
| |
So we got to the bottom of this. It was due to a custom media file pipeline in the end. What was confusing was that it was hard to track down/replicate due to the media cache getting in the way.
In the end we needed to add some code to check the file types and skip our pipeline to get it to work.
All the above comments were really useful in order to figure this out though so thanks.
| PDF Downloads 0 Bytes
We have an issue where all images from the media library display fine. But PDFs stored in the media library download with 0 bytes.
We've tracked this down to an issue somewhere in the Multisites configuration as with a single site the PDF downloads without any issues. However with multiples sites configured it fails to find the PDF in the media cache and returns a zero byte file.
Is this a bug or do we need to configure something to resolve this?
| |
The accepted answer is valid for previous version of Sitecore, but it does not reset the password salt and doesn't in fact reset the password to 'b'. In order to do this, you need the following script (which also will unlock the admin user if locked):
UPDATE
[aspnet_Membership]
SET
[Password]='qOvF8m8F2IcWMvfOBjJYHmfLABc=',
[PasswordSalt]='OM5gu45RQuJ76itRvkSPFw==',
[IsApproved] = '1',
[IsLockedOut] = '0'
WHERE
UserId IN (
SELECT UserId FROM dbo.aspnet_Users WHERE UserName = 'sitecore\Admin'
)
| Is there a way to reset Sitecore admin password from database level?
I forgot my Sitecore admin password and was thinking a way to reset from database level.
Is there a SQL query to reset Sitecore admin password ?
| |
Yes. But it can potentially involve a lot of steps, depending on how complex your solution is.
I'll outline the headlines.
Set up a new database to act as "web" for this site; e.g. approval_web
Configure this database in your <databases> section
Create a Publishing Target for your approval site
Map up a new <site> entry and give it a host name; e.g. approval.site.com
Your editors can now publish to this new Publishing Target and pass it on for internal review - before publishing to the "real" public facing website.
The most comprehensive guide I know for this is: Setting up content staging
Lastly; I seem to recall Sitecore making this easier in some recent release - but I can't find anything on it. It would involve the above principles anyway however.
| Trial publish to an alternate site
Our content authors want to do a trial publish before making all their content live; part of their approval process is examining how the layouts pull in all the other 3rd party content etc.
Could we setup a parallel site to the "real" site somehow, and allow people to push content to that preview version.
| |
If you have direct access to the database, you can run the following from SQL Management Studio:
UPDATE aspnet_Membership
SET IsLockedOut = 0,
FailedPasswordAttemptCount = 0
WHERE UserId IN (SELECT UserId FROM aspnet_Users WHERE UserName = 'sitecore\Admin')
Run this from the Core database.
| How to unlock the Sitecore admin user account?
I know you can unlock normal Sitecore users from user manager by login in to Sitecore backend, as admin user.
Is there any way to unlock Sitecore admin user, when the user account gets locked?
|