output
stringlengths
34
25.7k
instruction
stringlengths
81
31k
input
stringclasses
1 value
I have tried enabling pipeline profiling in production and there was no noticeable performance penalty, as long as CPU measurements (Pipelines.Profiling.MeasureCpuTime) were off. With CPU timings measured, the overall page load time was increased by something like 3% (a rough estimate). I know this is anecdotal evidence, but I don't believe anyone has actually measured what the impact is, since it is so small. Normally, you'd only enable pipeline profiling if there are already performance issues on your website, so this minimal additional slowdown will not be noticeable.
Is there a downside to enabling the Sitecore Pipeline Profiler? The Sitecore Pipeline Profiler is disabled by default. What is the performance impact when enabling it? Is it recommended to only do this in development, or can it be safely run in production?
The package without NoReferences suffix brings dependent Nugets containing additional DLLs. These DLLs are defined as dependencies in Nuget definition. If you check the dependencies list you will find Sitecore DLLs and third party DLLs like Newtonsoft.Json or HtmlAgilityPack in it. The package with NoReferences suffix does not bring any dependencies. Developer expected to identify and add all required DLLs manually. Now let's talk about what exactly is included in list of dependencies. The answer why some DLLs are included and others are not becomes clear if you check DLL references in the tool like ILSpy. These are references in Sitecore.ContentSearch.dll: And these are dependencies of Sitecore.ContentSearch Nuget package: There is a clear pattern here. The Nuget package includes referenced assemblies as dependencies. Now we can talk about what an assembly reference is and how it works. When our assembly executes its code it often uses types from external assemblies. References are the guidance for .NET to load the assembly that contains the required type. Interestingly, references are not used when an assembly is loaded, but when the code is executed. When the referenced assembly is missing, the application may work fine if any types from that assembly are not used at runtime. From mentioned above you can see that the regular Nuget package is developer's safe harbour and the default choice. It includes all the references required at run-time, so you can execute any code without fear to get Could not load file or assembly error. *NoReferences Nuget package can be used if you want to have full control over what is referenced. You can reduce amount of DLLs in your bin folder or use some specific dependency version.
When should I use the "NoReferences" NuGet packages? I'm converting a Habitat solution using DLLs checked into source control over to NuGet packages using the Sitecore package source feed. When should I use the packages marked NoReferences (so that I end up with the exact same project references)? Or those without this suffix that include references to the same plus other DLLs?
TDS has a feature named Global Config File that allows you to define the value of any TDS project setting in a centralized manner. Setting up the TdsGlobal.config To start using this feature, right click on the solution and click "Add Global TDS Config file": TDS will add a new folder to your solution, containing the file TdsGlobal.config: In this file, you will be able to set global settings that will be applied for all TDS projects in your solution. You can also set settings per build configuration. So, for example, release settings can be different from debug settings. User configuration You can create user settings both for TDS project files (e.g. SomeProject.scproj.user) and for the global config file (TdsGlobal.config.user). The order of precedence is the following: TdsGlobal.config.user SomeProject.scproj.user TdsGlobal.config SomeProject.scproj So if a setting was defined in TdsGlobal.config, its value can still be overridden on project level (SomeProject.scproj.user), which in turn can be overridden by TdsGlobal.config.user. Format of TDS settings The format of TdsGlobal.config matches that of TDS project files. So if you are wondering what the allowed values are for some of the settings, you can first apply the desired setting value in a single project, then open the corresponding .scproj file and see the value there. For example: This setting in the UI will be saved as the following XML node: <RecursiveDeployAction>SitecoreRecycle</RecursiveDeployAction> List of available settings PackageAuthor PackagePublisher PackageVersion PackageReadme SitecoreAssemblyPath GeneratePackage SeperateFilesAndItems PackageExcludeCode AddDateTimeToPackageName SitecoreWebUrl SitecoreDeployFolder RecursiveDeployAction InstallSitecoreConnector SitecoreAccessGuid DisableFileDeployment NuGetGenerateNuGetPackage NuGetExePath NuGetSummary NuGetDescription NuGetTitle NuGetVersion NuGetPackageId NuGetAuthors NuGetProjectUrl NuGetTags NuGetRequireLicenseAcceptance NuGetReleaseNotes NuGetLanguage NuGetOwners NuGetCopyright NuGetLicenseUrl NuGetIconUrl NuGetDependencies EnableValidations ValidationSettingsFilePath
How can I share settings between multiple TDS projects? I have several TDS projects in a solution, all of them have the same deployment properties (such as the access GUID, deployment folder), package metadata (author, version, etc.) and validation settings. When I need to change any part of configuration, I have to apply it in every project, one-by-one. Is there a way to share these settings from a centralized place?
I think you will have to make this functionality yourself. You will most likely have to hook into the httpRequestBegin pipeline and also extend and replace the default LinkProvider. Here's an (untested) example of how this can be approached. Start by hooking into the httpRequestBegin pipeline and check if the language matches the language setting on the site definition. public class SiteLanguageProcessor : HttpRequestProcessor { public override void Process(HttpRequestArgs args) { var language = Sitecore.Context.Language; var siteLanguage = Language.Parse(Sitecore.Context.Site.Language); // If languages match, don't do anything if (language == siteLanguage) return; // TODO: Find correct site for current language and redirect to it } } This will take care of redirecting incoming requests to the correct site. Next up we need to make sure generated links are also correct. For this we can extend the default LinkProvider and the LinkBuilder it uses. Here we can override the ResolveTargetSite(Item) method. If the site found by the base method doesn't match the requested language then we can go ahead and try to find a matching site. public class SiteLanguageLinkProvider : Sitecore.Links.LinkProvider { protected override LinkBuilder CreateLinkBuilder(UrlOptions options) { return new SiteLanguageLinkBuilder(options); } } public class SiteLanguageLinkBuilder : Sitecore.Links.LinkProvider.LinkBuilder { private readonly UrlOptions _options; public SiteLanguageLinkBuilder(UrlOptions options) : base(options) { _options = options; } protected override SiteInfo ResolveTargetSite(Item item) { var targetSite = base.ResolveTargetSite(item); var targetLanguage = Language.Parse(targetSite.Language); // Site is correct if language match if (targetLanguage == _options.Language) return targetSite; // TODO: Find matching site } } This will take care of generating links to the correct site. Here is a config file to patch all this in. <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/"> <sitecore> <!-- Change default provider to our custom link provider --> <linkManager set:defaultProvider="custom"> <providers> <!-- Add our custom link provider - set additional settings to your preferences --> <add name="custom" type="YourAssembly.SiteLanguageLinkProvider, YourAssembly" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageLocation="filePath" languageEmbedding="always" lowercaseUrls="true" shortenUrls="true" useDisplayName="false" /> </providers> </linkManager> <pipelines> <httpRequestBegin> <!-- Patch after the language resolver (and after site resolver) --> <processor type="YourAssembly.SiteLanguageProcessor, YourAssembly" patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.LanguageResolver, Sitecore.Kernel'"/> </httpRequestBegin> </pipelines> </sitecore> </configuration> You then need to have a site definition for each site/language with the language attribute set to the language supported for that site. EDIT: There are actually some settings for site resolving which probably doesn't require you to extend the link provider as long as you make sure to set the targetHostName attribute on your site definitions. <!-- SITE RESOLVING While rendering item links, some items may belong to different site. Setting this to true make LinkManager try to resolve target site in order to use the right host name. Default value: true --> <setting name="Rendering.SiteResolving" value="true"/> <!-- RENDERING - SITE RESOLVING MATCH CURRENT LANGUAGE Affects how cross-site links are rendered when Rendering.SiteResolving is enabled. If true, the link provider will take the language attribute of the site definitions into consideration when resolving which site/hostname to use when rendering a cross-site link. Default value: true --> <setting name="Rendering.SiteResolvingMatchCurrentLanguage" value="true"/> <!-- RENDERING - SITE RESOLVING MATCH CURRENT SITE Affects how cross-site links are rendered when Rendering.SiteResolving is enabled. If true, the link provider will check if the target item is located under the start item for the current site before it tries to find a match in the full list of site definitions. This ensures that when the target item can be resolved using the current site, the target link will not change to a different site/hostname. Default value: true --> <setting name="Rendering.SiteResolvingMatchCurrentSite" value="true"/>
How to setup single site with one domain per language I have a website that has 2 languages, lets say English (en) and Dutch (nl). Currently the site runs on a single domain, www.x.be. All is fine. But now the customer want to add another domain www.y.com to this site. We can add this domain to IIS and the site definition in Sitecore and it works - but... the actual requirement is that the site should run on www.x.be in "nl" and on www.y.com in "en". We need this on first request (correct language must be set) and on language switch (all pages have a language selector). On all pages we have canonical urls and also a <link rel="alternate" ... hreflang=""> to point to the other language - all these links must be set right to make sure we have no duplicate content. I would prefer that all the links are set correctly automatically so that we can't make mistakes. And we want to make sure that all requests that have a "bad" language are redirected to the correct domain. For the redirects I will probably just use the IIS Rewrite module. But how should I do the setup in Sitecore to match a domain to a language? Would a custom link provider be sufficient? And how can I prevent hard-coding language/domain pairs?
Have recently implemented this module, works perfectly for me so far, give it a try. https://vohil.net/2017/05/16/rebuild-sitecore-analytics-index-without-re-building-reporting-database/
How to rebuild the analytics index without rebuilding the entire reporting database? In Sitecore 8.1.3, is it possible to rebuild the analytics index without rebuilding the entire reporting database as specified in doc.sitecore.net? I have an analytics index that is more or less broken, and as far as I know it is not possible to trigger a rebuild of the index. From https://community.sitecore.net/technical_blogs/b/getting_to_know_sitecore/posts/rebuilding-the-sitecore-analytics-index i can see that there are workaround, but I am worried that it does not take care of everything?
In general, if your data nodes are hosted in different geographical regions, latency between them will be considered high. Write concern High latency will make the replication process slower, which means that using the write concern of w:1 is highly recommended in order to prevent performance degradation. On the other hand, if the majority of your nodes were hosted in the same data center, you'd be fine with using w: majority, which would improve your data safety without compromising performance. Read preference Given that you use w:1, you should use the read preference of primary or primaryPreferred. If you allowed reading from the secondaries, there would be no guarantee that the data read is up-to-date, which would lead to errors, such as contact locking inconsistencies. On the other hand, if you had low latency between all replica set nodes, and given that you used w:3 (or whatever your total number of nodes would be), then you could consider the read preference of secondary, secondaryPreferred or nearest. Although, this would only be recommended in read-heavy environments, which most Sitecore installations are not. Summary To prevent issues caused by high latency, use the write concern w: 1 and the read preference primary or primaryPreferred. Further reading Write concern (MongoDB) Read preference (MongoDB) MongoDB example architecture (Sitecore)
What are the best practices for MongoDB replica set latency? I'm looking to setup a environment with 3 MongoDB (1 x Primary and 2 x Secondary nodes) in different regions and wondering if: Is there any recommendations on latency (in ms) limitations for the synchronization of the data? Is there a way to avoid issues due high latency? Best practices are very welcome
If your throughput consist out of more than 100.000 writes per second, I would recommend you use an SSD. I think you should not overkill your machine. MongoDB cache will only take up to 10% of your available RAM to cache it's write actions. When you use the write concern w:majority on a replicaset your data will always be present in at least 2 (if you have a majorty of 2) of your MongoDB instaces (on disk). Of course SSD will speed of the writing process, but sitecore analytics is not that having that it really needs to have an SSD. We have a replicaset not containing an SSD, and our systems are practically doing nothing while still having many visits. Because the aggregation of Sitecore is not realtime but there are jobs scheduled to perform such writings, your Website will never suffer under the circumstances of your replicaset (unless it is unavailable at all..) Therefor I would refer to a previously made comment of mine (Sizing MongoDB Servers for xDB) My recommendation: 3 database servers(mongoDB) set-up as a resultset 4 x CPU E5 2650 v2 processors 8GB RAM 100GB HDD (dedicated to db storage)
MongoDB disk IOPS I was reading that Sitecore recommends SSD disks for MongoDB Servers, and I am wondering if What are the recommended performance values? Will I have any performance lost if not use SSD? Best practices relation with IOPS
We found that by using an Incognito window in Google Chrome or using Private Browsing Mode in Firefox that this error will go away and we can continue work in Sitecore. Hope this helps others with this issue in the future.
The CSRF cookie value did not match the CSRF parameter value exception in Chrome One of our developers is getting this error randomly when perusing through his local development instance in Sitecore 8.1 Update 3 using Chrome. I am not getting the exception at all on my machine on any of the browsers. Is there an known issue with Chrome on certain machines and what may be the cause of this. Seems when he closes browser or shuts down system it seems to alleviate problem.
There are a couple of steps involved. Download the image from the url via a WebRequest Copy the download stream to a MemoryStream Set up a MediaCreator Configure MediaCreatorOptions Create the MediaItem Optionally you also need to consider the context Database and permissions. In this example I am just uploading to "web" and ignoring security. You will probably want to change this a bit. var webRequest = WebRequest.Create("http://your-domain/logo.png"); using (var webResponse = webRequest.GetResponse()) { using (var stream = webResponse.GetResponseStream()) { if (stream != null) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); var mediaCreator = new MediaCreator(); var options = new MediaCreatorOptions { Versioned = false, IncludeExtensionInItemName = false, Database = Factory.GetDatabase("web"), Destination = "/sitecore/media library/Files/logo" }; using(new SecurityDisabler()) mediaCreator.CreateFromStream(memoryStream, "logo.png", options); } } } } Note: Copying the stream to a MemoryStream is required because the MediaCreator will issue .Seek() operations on the stream, something which is not supported on a stream you get from a WebRequest directly.
How to upload an image programmatically from URL I have a task to upload an image into Sitecore's media library programmatically given the url to the image. How would I make this possible?
You are able to set the required validation item rule item to FATAL ERROR in Sitecore. This is the highest level of validation. This setting prevent the user to save the item with validation error.
How do I enforce Alt tags on all images in Sitecore Sitecore flags up empty Alt tags but it still lets users save them without setting the Alt tag. Is there an easy way to enforce that this is done for all new images? I know I could write a custom validator like so: https://techmusingz.wordpress.com/2014/11/04/enforce-alt-text-for-image-fields-in-sitecore/ But Ideally I'm looking for a way of doing this out of the box with the rules engine or something like that and prevent users saving/uploading images without Alt text. -- Update -- One problem I've seen related to this is that the standard image uploader in the media library doesn't allow the user to add alt text during upload and so even with a rule to enforce alt tags on save this doesn't prevent initial alt tags being empty on save. Thankfully I came across this pipeline example which will run on load and add a default alt text based on the image title: https://sitecorejunkie.com/2014/06/18/set-default-alternate-text-on-images-uploaded-to-the-sitecore-media-library/ Neat idea but I haven't implemented it yet. Further info: Sitecore 8.1 Update 2.
If the workflows are not drastically different, you can achieve 'site-specific' workflow via content security. Step 1: Workflow security Create a single workflow definition with some generic access roles for each state. Use these only to grant access to the workflow states. Step 2: Content security Create a security role for each site and assign it to where the content lives (e.g. sitecore\content\site1, sitecore\content\site2). Step 3: Winning! The Workbox and workflow in general take both workflow state access and content security into account. Users will only see items in the workbox that they have access to for both workflow and content, so users in the same workflow from Site 2 won't see items from Site 1 because they don't have permission to the content in Site 1. Step 4: Advanced Ninja You might want to do alternate steps for some sites. Maybe a 'approve with business' state that only Site 1 uses. In this case, using actions and state security that require a specific role will allow you to create users for one site that have access to this action while other sites use a different approve action. This allows you to simulate multiple flows within a single workflow state definition. Alternate flow You can also have completely separate workflow definitions and create site-specific templates which use different workflows. Suppose you have a 'content page' that is the same in every way between Site 1 and Site 2, but you want different workflows. You create a Site 1 content page template and a Site 2 content page template which inherit all the common presentation details and fields, however you change the default workflow on the site-specific template. You'll have to play with insert options in this case to restrict which templates are used for which sites. Insert Option rules in the rules engine will help you with this. Update based on edited question Handling scenarios when the workbox is too full If a user is looking for specific content, the workbox is not the place to do it. The workbox works well for teams who are keeping on top of their content. If you have 1000 items that need to be reviewed, then the Workbox just won't work for you. What if those 1000 items are in the site and language that the user needs to find their particular page? No amount of security or configuration will help that. Instead, I usually suggest using the Gutters in the Content Editor. That way, you can just expand areas of the site and look for the correct icon. I have a quick 25 second video for turning on gutter icons available: https://www.youtube.com/watch?v=IkqG3OnTSvA In this way, a user can make a more granular search for what they want and take action on the item.
How to apply Site specific workflow in Sitecore? I have problem at hand for which I'm confused about what is the best practice for going after it. I have thought to intercept item creation process in Sitecore and read the site node properties. This idea is similar to what I have read regarding Site specific RTE HTML profiles. Also solution should be extensible later to have per site/per language/per template wise workflows. But is there any OOTB functionality for this? If not what should be best approach to manage workflow with such cases? P.S.: I have seen some projects to follow sprint-wise content workflows but that is not required by us. Update We have three types of user roles - Global team users Site specific admin users Site specific-language authors Problem is for global users and users who are admin for multiple sites. When these users want to approve particular content from workbox and it is difficult for them to find in 1000+ content items in that workflow from all sites and language versions of the sites in workbox.
After further investigation it turns out this was an issue with a custom pipeline that was being fired and interfering with the upload of images. We added some logic to skip the pipleline during uploads and it is now working fine.
'Parameter is not valid' error when uploading images in media library I'm getting a strange behaviour when uploading to the media library recently where Images upload but the pop-up doesn't close and an error is shown if I look in the network tab. The image actually does upload but with no height/width or alt text: > [ArgumentException: Parameter is not valid.] > System.Drawing.Image.FromStream(Stream stream, Boolean > useEmbeddedColorManagement, Boolean validateImageData) +1545584 > Sitecore.Resources.Media.ImageMedia.GetImage() +64 > Sitecore.Resources.Media.ImageMedia.UpdateImageMetaData(MediaStream > mediaStream) +239 > Sitecore.Resources.Media.JpegMedia.UpdateMetaData(MediaStream > mediaStream) +63 > Sitecore.Resources.Media.MediaCreator.AttachStreamToMediaItem(Stream > stream, String itemPath, String fileName, MediaCreatorOptions options) > +282 Sitecore.Resources.Media.MediaCreator.CreateFromStream(Stream stream, String filePath, MediaCreatorOptions options) +117 > Sitecore.Resources.Media.MediaUploader.UploadToDatabase(List`1 list) > +487 Sitecore.Resources.Media.MediaUploader.Upload() +155 Sitecore.Pipelines.Upload.Save.Process(UploadArgs args) +1220 > > > [TargetInvocationException: Exception has been thrown by the target of > an invocation.] System.RuntimeMethodHandle.InvokeMethod(Object > target, Object[] arguments, Signature sig, Boolean constructor) +0 > System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, > Object[] parameters, Object[] arguments) +76 > System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags > invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) > +211 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35 > Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, > Pipeline pipeline) +398 > Sitecore.Pipelines.Pipeline.Start(PipelineArgs args, Boolean atomic) > +366 Sitecore.Shell.Applications.FlashUpload.Advanced.UploadTarget.HandleUpload() > +1525 Sitecore.Shell.Applications.FlashUpload.Advanced.UploadTarget.OnLoad(EventArgs > e) +852 System.Web.UI.Control.LoadRecursive() +71 > System.Web.UI.Page.ProcessRequestMain(Boolean > includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) > +3178 This is the call made to the uploadtarget.aspx page which is returning a 500 error: > sitecore/shell/applications/flashupload/advanced/uploadtarget.aspx? > id=%7B487DBAD1-EFC7-4989-B0C1-1DAAAFD923F6%7D&la=en&language=en&vs=1 > &version=1&database=master&readonly=0&db=master&uploadID=851fea44-50b9-4dc3-8241-4dba5895ffe4 This has only just started happening and I'm not sure why as the permissions on the folder seem fine and we haven't updated the code that I can think would affect this recently. Further info: Sitecore 8.1 update 2.
The indexes are defined in configuration, and the core for that index is specified in that configuration section. Here's the default 'sitecore_core_index' definition in an OOTB sitecore install (some properties elided for space): <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch"> <indexes hint="list:AddIndex"> <index id="sitecore_core_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider"> <param desc="name">$(id)</param> <param desc="core">$(id)</param> </index> </indexes> </configuration> Notice the 'core' section, which uses the index id as its value. By default in later versions of sitecore, these indexes will map 1 to 1 with cores, so in this particular case, the 'sitecore_core_index' would be using a core named 'sitecore_core_index'. You are free to change this value to anything you'd like - you just need to remember to create the requisite core in SOLR.
How to specify Solr core in search code for Sitecore 8.1 I recently upgraded from Sitecore v7.5 to v8.1. In addition my Solr configuration changed a little. On v7.5 I only had a single core. On v8.1 I now have many cores. After upgrading my search code is not returning any results and I am debugging it. I am wondering if maybe my code isn't searching the right Solr core. So I am wondering how the code knows which core to query. Here is a code fragment for my search... using (var context = ContentSearchManager.GetIndex("sitecore_web_index").CreateSearchContext()) { ... do search stuff } When I create the search context using that code am I telling the code to search through the core named "sitecore_web_index"? I guess it is unclear to me how the code knows which core to query.
Normally, the .update package can be converted to a zip file. You just need to rename the .update to .zip. Once this is done, open the package and see if the items and dlls are present in the sub folders. If you have more .update package inside the package, you can try to unzip the main .update package and the install the sub .update package individually. If you have errors while installing one of the .update package, it means that this .update package may contain corrupt items.
Update package installation throwing XML Parsing Error: no element found I'm trying to upgrade an 8.1 install to 8.2. I've followed the steps in the guide so far, including installing the UpgradeInstallationWizard package. When I select the .update package and try to progress to the next step I get this unhelpful error message, XML Parsing Error: no element found Location: http://<mysite>/sitecore/admin/UpdateInstallationWizard.aspx?page=1 Line Number 1, Column 1: ^ The sitecore logs aren't giving me any information on what the problem is. Where can I look to find out why the upgrade installation wizard isn't happy with the .update package I'm trying to install?
This should actually now work out of the box on Sitecore 8.2+ including Sitecore 9 and 10 with no additional code or configuration required. Among the resolved issues from the 8.2 release notes: ​Sitecore.Services.Client prevents using Attribute Routing with ASP.NET WebAPI​. Sitecore is calling the config.MapHttpAttributeRoutes() from Sitecore.Services.Client in the initialize pipeline. This is the one throwing the error you are seeing if you have already called that method in your own startup logic which is run first. You can configure the assemblies is resolves based on the documentation here.
Web API 2 Attribute Routing with Sitecore 8.2+ Has anybody set up Web API 2 Attribute Routing with 8.2 or later? I tried the 'official' route, which is to create a custom pipeline handler to the initialize pipeline that does the registration. I've tried to hook it up with a config as well as using webactivator. I've done something similar to this: http://wp-bartbovendeerdtcom.azurewebsites.net/sitecore-8-webapi-v2-mvc-and-attribute-routing/ - In both cases, I get an error &quot;A route named 'MS_attributerouteWebApi' is already in the route collection&quot;. I've also used a marketplace module (https://marketplace.sitecore.net/Modules/A/Attribute_Routing_Support.aspx?sc_lang=en), which is essentially the same thing, but hooked up with a config. All same error. It makes me think that a web api registration is happening somewhere else already in Sitecore registrations, but I'm not sure where. Even if it does, how do I get past this? Ideas?
It looks like you are missing the caches/fieldsCache node in the coveo node in your Coveo.SearchProvider.config, as the following: <caches> <fieldsCache type="Coveo.Framework.Caching.FieldsCache, Coveo.Framework" singleInstance="true" /> </caches> I suspect this error comes from trying to access the field cache that can't be initialized because the node is missing.
Coveo initial reindex throws "object reference" exception I have a scenario, using the free Coveo on-prem server, where I've previously set up a QA Azure VM that works fine with the SQL server, Coveo, and Sitecore all on it. Due to certain external databases we're using, we have to use an Azure VM for SQL, so we're tying out production server that we're setting up into the QA box and making QA into a database server for all intents and purposes. After setting up Sitecore on production CM, I installed Coveo CES 7, the search API, and the Coveo for Sitecore package. Since CES is on the box with CM, everything is set for localhost to the various ports, so theoretically it's self-contained. When I go to Sitecore's control panel to reindex cover_master_index, I get the error below. I'm not sure if this is because the databases for Sitecore are on another server, or if because that other server also has Coveo and there's some kind of interference. The error's rather unhelpful to me, so if anyone has a thought, I'd appreciate it. Thanks. Job started: Index_Update_IndexName=Coveo_master_index|#Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at Coveo.Framework.Caching.FieldsCacheHandler.Add(IEnumerable`1 p_Entries, String p_DataSourceName) at Coveo.AbstractLayer.FieldManagement.FieldsHandlerUtility.GetCompleteFieldConfigs(String p_IndexName) at Coveo.AbstractLayer.FieldManagement.AdminModuleFieldsHandler.GetSitecoreFields(String p_IndexName, ForeignKeysConfiguration p_ForeignKeysConfiguration) at Coveo.AbstractLayer.FieldManagement.AdminModuleFieldsHandler.UpdateFieldSetAndFields(String p_FieldSetName, String p_IndexName, ForeignKeysConfiguration p_ForeignKeysConfiguration) at Coveo.AbstractLayer.Communication.CES.AdminModule.SetUpRequirements(String p_ServerUrl, String p_TargetSite, Boolean p_ExpandUsers, ForeignKeysConfiguration p_ForeignKeysConfiguration, IList`1 p_RankingIgnoredFields) at Coveo.AbstractLayer.Communication.CES.CESCommunication.InitializeAdminModule() at Coveo.AbstractLayer.Communication.CES.CESCommunication.Initialize() at Coveo.SearchProvider.AbstractProviderUpdateContext..ctor(ISearchIndexSummary p_IndexSummary, IIndexCommunication p_Communication) at Coveo.SearchProvider.ProviderUpdateContext..ctor(ISearchIndex p_Index, IIndexCommunication p_Communication) at Coveo.SearchProvider.ProviderIndex.CreateUpdateContext() at Coveo.SearchProvider.ProviderIndex.<Rebuild>b__3e() at Coveo.SearchProvider.ProviderIndex.TryPerformIndexingOperation(IndexingOptions p_IndexingOptions, Action p_Action) at Coveo.SearchProvider.ProviderIndex.Rebuild() --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args) at (Object , Object[] ) at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at Sitecore.Jobs.Job.ThreadEntry(Object state)
I think the most common extension is to use the rules engine. You create a processor for the GetPlaceholderRenderings pipeline that uses the rules engine to add/remove renderings. Here are some links to various implementations of the idea. I'm sure there are more out there too. https://github.com/matthewkenny/ConditionalPlaceholderSettings https://github.com/williamsk/SitecorePlaceholderSettingsRules http://shanebair.me/2015/09/27/smart-placeholder-settings-how-it-works/ https://brainjocks.atlassian.net/wiki/display/SDD/Placeholder+Settings+Rules
Placeholder settings on sub-renderings This is something that's been bugging me and I was curious to others' solutions. Let's say you have a template that you've done standard values on for the presentation...you pick a layout, put renderings on, put placeholder settings on. Let's say one of these renderings is a sub-layout (in the traditional sense of the word, not an web forms rendering) with placeholders on it. Is there a way to specify the placeholder settings for the sub-layout such that they always stay with the sub-layout? I hate the idea of having to specify all of these placeholder settings on a page template that may or may not use the sub-layout, and I'd hate to always have to specify a template for the sub-layout if all it is is a layout detail (like multiple columns to subdivide a page) and doesn't need a template for data reasons. Thoughts? Thanks.
Start by reading the Sitecore Helix Documentation. The component-based architecture it describes is definitely the way to go. Most of the accelerators use something like it even if they don't use the Foundation-Feature-Project layers. Most of the accelerators also move presentation details away from the template standard values to some extent. SXA has Composite Renderings, Partial Designs and Page Designs. Other accelerators also use things like the Placeholder Fallback mentioned by Derek or Cascading Renderings. There's also my Base Layouts project (GitHub) which I have been neglecting lately. It should go without saying at this point that all of them use Dynamic Placeholders.
Options for Planning an Effective Presentation Details Strategy I am very familiar with Presentation Details and inheritance, as well as the Sitecore 8 documentation on Versioned Layouts, but I feel like Presentation Details are all too often one of the most fragile pieces of architecture on my sites. The loose-coupling challenge is also throwing me. Without using template inheritance, which often means inheriting the Presentation Details of items in other modules, I am having trouble devising a strategy that is easy for the client and our internal teams to maintain. What I am looking for is a Presentation Detail strategy that prevents tight-coupling, keeps overhead low, and provides for easier maintenance. When I say "strategy," what I mean is a set of rules, like "Always declare on Standard Values. Do not depend on Standard Values inheriting from other Standard Values and instead copy the Presentation Details before modifying." Has anyone developed an effective strategy for Presentation Details that works well the above focuses?
The answer to your overall question is that you should not publish across across environments. Can you? Sitecore is so flexible that you can create publishing targets to all kinds of Sitecore databases without Sitecore complaining too much. However, there are a lot of gotchas that fall into play here. Publishing causes events to fire. You may not want events to fire across environments. Connection Strings become incredibly messy. The differences between environments can become muddled. Caching and Indexing confusion (Thanks Derek!) Event Queue cluttering and confusion Environments Let's talk about environments. When I refer to an environment I mean: All of the instances of Sitecore that make up the collection of code bases and config files that are treated with the same level of consideration and protection. For example: The Production environment may include: 2 CM servers 3 CD servers 1 processing server 1 reporting server. All of these servers have share distinct copies of databases (master, web, core, etc). In addition, your backup measures are vast, the servers are protected and security is very important. But your QA environment may only have 1 server of each above. And if in the middle of an upgrade may be a different version level. And it might not be backed up as much. Same with your Dev Environment. Rate of change is constant. Summary The Best Practice is that you don't want to cross streams between these environments using publishing mechanisms. Instead, proper file and item deployment methodologies should be employed such as: TDS or Unicorn item serialization synchronization Configuration file transformation based on environment and role Database backups and restores to lower environments between projects to keep them fresh.
Should I configure multiple publish targets to publish to multiple environments? We have several environments: Our production / live site. Our staging / QA site. Our development site. Local developer's machines. I know sitecore supports several ways to publish, including packages and 3rd party tools like TDS, but is there any reason I couldn't (or shouldn't) just configure a publish target for each environment? When I publish from our development site to our QA site, for instance, I could just publish and check the QA target.
As you have already found, that button is defined by the /sitecore/content/Applications/WebEdit/Default Rendering Buttons/Properties item in the core database. To make that button appear in the main toolbar, change the Type field so there is no selection rather than the default Common. Changing the Header field should modify the text when you have Type set to common. When it appears in the toolbar, there is no text on the button, but you can change the tooltip field to change what shows when you hover over it. As an alternative to globally changing this button, you could also copy the button under the Custom Experience buttons folder, modify it as needed and then select it for only the renderings you really need it on.
Move/Rename Experience Editor 'Edit component properties' button In specific instance, I prefer to make use of rendering parameters when creating a Sitecore rendering. However, our content authors find it's placement and button description unintuitive. I see that these buttons are configured in the core database at the following path: /sitecore/content/Applications/WebEdit/Default Rendering Buttons. Editing the button's Header field and order in the folder does not appear to affect the display in Experience Editor. Is there any way to rename the 'Edit component properties' button and move it out of the 'More' dropdown, into the main toolbar?
Common uses I've seen is to make the following two things easier: Preview of the site before it's published where users don't have sitecore access. This preview can be used internally in the organisation to see what is about to go live. Good especially if you have limited number of editors; full details here http://getfishtank.ca/blog/2-big-improvements-to-publishing-in-sitecore-7 Keeping the site up when deploying: let's say you make breaking content changes - like moving global settings etc. Anything where you need new code and new content to be deployed together. With 2 publishing targets you can drop new code on one CD and publish to one target while keeping old site running on other CD and other target. Once happy you can swap.
When should I define a new publish target? This is a follow up to Should I configure multiple publish targets to publish to multiple environments? In that question, I asked if I should define publish targets to publish between environments. The answer was that that was not best practice. So, to follow up, when should I define a publish target other than the default "internet" target?
Would that work for you? ancestor-or-self::*[@@templateid='{website-root-template-id-here}']/*[@@templateid='{shared-content-template-id-here}']/*[@@templateid='{contacts-node-template-id-here}'] This'll travel up the content tree to the nearest website root node (from any page) and then down to the respective Contacts node.
Site-relative datasource locations We have a multisite setup, where Shared Content is stored in a node for each site as a sibling to the site frontpage. For example: - Website 1 -- Home --- Some page -- Shared Content --- Contacts - Website 2 ... In the above example, how would i use the Contacts folder as a DataSource Location in a TreeList or Multi List field etc.?
SPE is only required for environments that use the Sitecore interface. If you are going to use the Content Editor or Experience Editor then install the module. Essentially only the CM needs SPE.
Where should I install Powershell module for SXA? Solution can be installed on many environments - QA, Staging, Prod. In every of these environments Sitecore instances have different roles - CD, CM, Job, Publishing and etc. Should I install Powershell on all these instances if I use SXA?
Check the root settings of EXM as explained here. The Embed Images checkbox controls whether to embed images in the message or to insert links to images. You might need to untick this.
EXM Messages sent with images as attachments on version 3.3 In EXM 3.3, for some reason, all of our dispatched emails are getting sent where the images that included in our rich text field (which are all of them) are getting sent as attachments as well as showing up in the email. This was not the case in ECM 2.2, and this is an upgraded solution. Is there a setting to change this so that the images are embedded into the email, not sent as attachments?
DataSource Location inside rendering parameters has different context. You could achieve your goal by extending resolveRenderingDatasource pipeline. Allows developers to override the default logic for resolving the data source for renderings. Pipeline args type is: ResolveRenderingDatasourceArgs and it contains: public string Datasource { get; set; } You can find you context item like that: Item item = args.CustomData["contextItem"] as Item ?? Context.Item; Having raw value of Datasource field (value from Standard Values of your rendering parameters) with your query and context item, you could execute your query to get results in correct context. By reading Datasource property you can access that value from Standard Values before it is resolved by Sitecore. Then you can process it and convert to an item ID running query not in Rendering item context (like Sitecore would normally do without your intervention, situation that you described) but in Context Item context. Datasource property in your case contains (relative XPath query (./ or ancestor-or-self etc))
Relative rendering DataSource Locations How do I define DataSource Location for rendering parameters, relative to the context item? When defining a DataSource Location for rendering parameters (Droplink or TreeList etc), using a relative XPath query (./ or ancestor-or-self etc), it seems that the DataSource Location is relative to the actual rendering item and not the context item.
Starting with version 8 or 8.1 it was changed how to add a button to experience button. Please follow next link to add new button to experience editor: http://reyrahadian.com/2015/04/15/sitecore-8-adding-edit-meta-data-button-in-experience-editor/ Before it was very simple, you didn't need to add new code for editing hidden field: https://blog.istern.dk/2012/05/21/running-sitecore-field-editor-from-a-command/
How do I add a button to the Experience Editor Ribbon? I would like to add a button to the Experience Editor ribbon that will open a modal or new window with a set of fields from the context item. I had some custom code to do this with the old Sheer UI ribbon but would like to implement this within the new Speak UI ribbon. I have found Sitecore's documentation to create the button: Customize the Experience Editor ribbon However, I'm having a hard time finding a good example of what to perform within the execute method of my custom javascript. What javascript would I need to open a window that displays a pre-configured set of fields that exist on the context item?
The reason you see only the latest version in normal mode is the fact that there is only one version in web database. Normally Search Results rendering returns all versions of your item. This is unexpected behaviour and I would consider this as a bug (by default we should get only the latest version, this is the default Sitecore behaviour). SXA ticket for that has been created and the issue should be fixed in the next release. What you can do for now? This probably won't solve your problem because I don't think that there is a way to select distinct items based on some property within Sitecore search query but you can try. You can filter your searach results with Search Scope. Navigate to tenant/site/settings/scopes Create new search scope item Build Sitecore query to filter you results (in this case I request only items with version number 1) Assign your Search Scope to Search Results rendering
How can I hide old page versions in SXA Search Results in Preview mode? I created multiple versions for my page. I see only last version in Search Results SXA component when page is rendered in normal mode (what is expected). Although, when I switch to Preview mode, all the variants are shown. How can I filter the data to render only the latest page version in Experince Editor Preview? Reproduced in Sitecore Experience Accelerator 1.1 rev. 161004 for 8.2.
You should use Rendering variants for this. When you edit the search results rendering properties, there is a field which allows you to select rendering variant. You can choose from the couple of default ones but you can define your own. In order to define a variant you have to: Insert new Variant definition in the Presentation\Rendering Variants\Search results Insert two child items of type Field and name them Image and Description (actually you can name them whatever you want but the name is propagated to Field field which is used to identify which field should be used to get the data from) You can read more in the documentation Here is the list of SXA renderings with information which of them supports component variants
How can I customize Search Result in SXA? Out of the box SXA Search Results component shows only page Title. How can I customize that component to show page Image and Description?
I would say that these are the files specific for the Project layer so they should be placed in a module there. I would expect a project representing a Website there so I would add them in such a project. From the Helix docs: The Project layer provides the context of the solution. This means the actual cohesive website or channel output from the implementation, such as the page types, layout and graphical design. It is on this layer that all the features of the solution are stitched together into a cohesive solution that fits the requirements.
Where should environment-specific configs be placed in Helix (Habitat) compliant solution? Where should environment-specific configs be placed in Helix (Habitat) compliant solution (in the VS solution and the file system), such as connection strings?
Sitecore is a great CMS to use for zero downtime, here are some thoughts: Have multiple publishing targets This will solve the issue of fields being renamed etc. Details here https://sitecore.stackexchange.com/a/1413/87 User sessions Ideally you're going to want to shove the session into the database, perhaps Mongo for the latest versions 8.x onwards or SQL is fine too, then you don't need to worry about sessions getting blown away. However there are some sites where the session has been abused to store all kinds of wonders that stops it serialising to disk. In this scenario you can do two things. Drain boxes from the load balancer before deployments Use app_offline.htm to get rid of users gracefully https://stackoverflow.com/a/1153545/861315 but you will need a way of ensuring your load balancer drops the box out to stop users getting the app_offline.htm WFFM Most modules will use their own databases, so this won't cause you problems CM box This is the only sticking point really, unless you have multiple CM servers then there is always going to be a blip here, unless you deploy side by side in IIS and just flip over to serve the new code - for this to work you need to be confident that you can trust your release to be dropping all code each release (or virtualise the Sitecore folders and just drop production code each time) Core and Web databases These are pretty robust and not something you'll need to worry about - or at least nothing I can think of.
Most important caveats for continuous delivery and zero downtime Currently I am working on the physical view of our Sitecore architecture, part of this view is how we do deployments which cause no downtime for endusers and preferably our content editors. So far, we have automated all of our deployments, because we have 20 different sitecore instances (all existing of 4x CD and multiple CM's) and we have tons of deployments a day. From the CI and automated deployments, our next step is to be able to deliver zero downtime deployments. Multiple strategies have come into my mind and most strategies fit a specific situation, which will work or won't work for different situations, so I am not looking for the one-size-fits-all solution, but for the challenges that we will face. From what I've come up with, I can think of the following: User Sessions. Graceful remove CD's from a load balancer or don't use sticky sessions databases. what data is stored in web/core when someone visits a CD server. Is there any data that is stored? (I know that, for example, userprofiles, passwords, groupmemberships et cetera) are stored in the core database. Are there any queues that I have to take care of? WFFM/other modules -> where do they store data? I believe they use some queues as well? Itemdata: develop defensively, make sure that renderings (and other logic) don't freak out when a field is removed/renamed.
Purpose of keepalive.aspx Here's the full code of the page in Sitecore 8.0: <%@Page Language="C#" %> <%@ Import Namespace="Sitecore.Analytics" %> <!DOCTYPE html> <html> <head id="Head1" runat="server" enableviewstate="false"> <title>Keep Alive</title> <script runat="server"> protected override void OnPreInit(EventArgs e) { Tracker.Enabled = false; } </script> </head> <body> <form id="form1" runat="server" enableviewstate="false"> Keep Alive Page </form> </body> </html> In Sitecore 8.2 it's even shorter: <%@Page Language="C#" %> <!DOCTYPE html> <html> <head id="Head1" runat="server" enableviewstate="false"> <title>Keep Alive</title> </head> <body> <form id="form1" runat="server" enableviewstate="false"> Keep Alive Page </form> </body> </html> It's pretty clear this page doesn't do anything meaningful—it even has no code behind. So its purpose, indeed, is to keep the application pool alive. Extending Sitecore client sessions As G Killian has discovered, this page is also regularly requested from JavaScript to extend browser sessions of users logged into Sitecore Desktop. Image source requests to this page ensure that the user won't be logged out from Sitecore provided that they keep their browser open. A great find! Disabling IIS pool recycling Yes, you can (mostly) disable automatic IIS pool recycling, although it is a bit more complex than just removing the idle timeout. See more in this answer: https://serverfault.com/a/333948 I believe Sitecore included its own keep-alive mechanism because IIS does recycle apps by default, and Sitecore wanted to override that behavior out of the box.
What is the purpose of keepalive.aspx? I know that this the page is called every 15 minutes (by default) by a scheduled task. <agent type="Sitecore.Tasks.UrlAgent" method="Run" interval="00:15:00"> <param desc="url">/service/keepalive.aspx</param> <LogActivity>true</LogActivity> </agent> Does it have any other purpose than keeping the application pool from timing out and make sure other scheduled tasks are run? Can the same not be achieved by setting the application pool idle timeout to 0 in IIS?
I would go with Sitecore PowerShell Extensions. It supports your version as well. My idea is to run query and process all items you want to check. In the past I used something like this to compare revisions between master and web database: function RevisionsMatch($itemToCheck){ if($(Test-Path "web:$($itemToCheck.Paths.Path)")){ $webItem = Get-Item "web:$($itemToCheck.Paths.Path)" -lang $itemToCheck.Language if($webItem -ne $null) { if($webItem.Fields["__Revision"].Value -eq $itemToCheck.Fields["__Revision"].Value){ $true } } } $false } How to use it $items = Get-ChildItem -Path "/sitecore/content/Playground" | Where-Object { (RevisionsMatch $_) -eq $false } As a output you get filtered items that have different revision number in master and web database If you want to create a fancy report, here some blog post about creating one: http://blog.najmanowicz.com/2014/10/25/creating-beautiful-sitecore-reports-easily-with-powershell-extensions/ If you are not able to install any additional module on your instance, you can always output report on some aspx page using the same strategy with comparing revisions. EDIT: If you want to exclude items with publishing restriction from your results you could write filtering function (it takes an item as input and returns it without any modification if condition are meet, otherwise nothing will be returned) function ValidatePublishingRestrictions($itemToCheck){ if($itemToCheck.'__Never publish' -eq 1){ Write-Host "Skipping item [$($itemToCheck.ID)] because of publishing restrictions" }else{ $itemToCheck } } And do something like this: $items = Get-ChildItem -Path "/sitecore/content/Playground" | Where-Object { (RevisionsMatch $_) -eq $false } | ForEach-Object { ValidatePublishingRestrictions $_ } That way you will get only items that can be published. Notice, I added logging there so you can read which items were excluded: Skipping item [{F0A490C2-9DF8-47F6-8E94-85713FCAA4CA}] because of publishing restrictions
How to find out what's pending to be published I need to do a full site publish but there could be content, without workflow with changes that can't be published. How could I build a "report" with the list of items with changes that would be published with a Site publish. To make it "easier" we are still on 6.6 I have tried the "compare servers" module, but it takes too long and end up failing. I'm thinking about Razl, but i'm not sure if it Supports 6.6 and gives any sort of report. Would you consider doing it at SQL level? How?
Utilizing data extension points The first thing I would consider is whether your data can be stored as part of the standard Sitecore entities. Contact The xDB contact has the following fields where you can store custom data that will be saved to MongoDB: Facets Attachments Tags Interactions CustomValues If you use any of the above, you won't have to implement any MongoDB-specific code, as xDB will store and retrieve data for you. Raw database access xDB provides the MongoDbDriver class (located in Sitecore.Analytics.Data.DataAccess.MongoDb) that allows you to read and write to MongoDB directly. This is a part of the data access layer used by xDB itself. Here's how you use it. First, get an instance of the driver: var driver = MongoDbDriver.FromConnectionString("analytics"); You can also set up your own MongoDB connection string rather than using "analytics". Then you get a collection instance: MongoDbCollection collection = driver["YourCollectionName"]; Since MongoDB is schemaless, you can just work with a non-existing collection. It will be created on first access. Once you have a collection object, you can do CRUD, as well as some extra data and schema operations. Fetching data MongoCursor<YourCustomData> cursor = collection.FindAs<YourCustomData>( Query.LTE("CreatedDate", DateTime.Now)); IList<YourCustomData> results = cursor.Skip(5).Take(10).ToList(); You can also use lambda expressions to refer to fields: MongoCursor<YourCustomData> cursor = collection.FindAs<YourCustomData>( Query<YourCustomData>.EQ(_ => _.SomeField, "FieldValue")); Inserting data var data = new YourCustomData { SomeField = "SomeValue" }; collection.Insert(data); Creating an index collection.EnsureIndex(true, "DataFieldName"); MongoDbStorage If you're fine with CRUD only, you can use a convenience wrapper around the MongoDbCollection. MongoDbCollection collection = MongoDbDriver.FromConnectionString(connectionStringName)["CollectionName"]; var storage = new MongoDbStorage<YourCustomData, CustomIdType>(collection); MongoDbStorage has the following methods: Insert Save Update Delete Load Count Registering custom types in the driver Note that the driver will serialize/deserialize data for you. But first, you will need to register your types using the helper methods provided by xDB: MongoDbObjectMapper.Instance.RegisterModelExtension<YourCustomData>(); You can also specify the collection name to use and the way to get the identifier of your custom objects (that's what will be stored in _id): MongoDbObjectMapper.Instance.RegisterModelExtension<YourCustomData, CustomIdType>("CollectionName", d => d.CustomId); Registering custom types is something that should be done once per application lifetime. You can register your types in a static constructor or in a custom initialize pipeline processor.
How can I utilise MongoDB for non-xDB related things in my Sitecore solution? Assuming we have a sparking new Sitecore installation running, and have already invested in the relevant MongoDB infrastructure to keep the solution running 24x7 and so on - how can I make further use of this infrastructure in my solution? I realise that it would probably need to involve something like the C# and .NET MongoDB Driver for very low level access to MongoDB, but are there other and more appropriate resources available? How would a "Hello World! from MongoDB" example look, when wired up to a Sitecore solution? Including registering the necessary Api Controllers and so on? It would involve basic CRUD operations.
Yes - there are several advanced ways this can be used - but as I see it the main drawback will be that you expose yourself to a heavy denial of service attack. The in-memory provider will block writes and therefore hinder creations of new sessions if it runs out of memory - so a session flood attack (probably the easiest attack there is) will bring your system down.
Can I use the in-memory storage engine for my MongoDB based sessions? MongoDB 3.2+ offers the option of putting some or all of the structures into an in-memory engine. I was thinking to try out this capability for discardable data such as Sitecore sessions - for which we have no use after the SessionEnd event. Are there any obvious drawbacks to this approach? Will this scale properly - e.g. will MongoDB manage redundancy itself in a multi-server/master-slave configuration?
Personally I've always seen and treated Solr as a transient index, not a persistent storage solution. Whereas MongoDB has always been treated as a storage solution, and not much of an index. But this is my personal treatment, not saying that Solr can't be used as a persistent store. If you need to access the data directly as Key/Value pairs and there isn't much querying going on, then I'd say go for MongoDB. If you need to query the data to retrieve a subset then perhaps I'd lean towards Solr for it's more sophisticated indexing. Multi-lingual data being searched, searching bodies of text data, faceting results? Totally choose Solr. From personal experience setting up a reliable 3+ server Solr Cloud cluster configuration was pretty challenging at first, and has resulted in many hours of troubleshooting at times when the cluster wasn't performing as well as it should have been (or just randomly failing unexpectedly). I'd say that Mongo's clustering / redundancy capabilities are more polished and better documented than Solr, so if operational ease is a factor then perhaps that'd sway you? Mongo you also have better access to official commercial support. As an alternative you would probably be best off by combine the two. MongoDB cluster for persistent storage and key-value retrieval, more simplified Solr setup to index and allow fast access via more complex queries. Edit based on clarifications: If you can rebuild the data from an external source and can only pick one technology, then it sounds like Solr is your choice (for the above reasons). You should make sure to weigh up the pain of re-indexing from scratch as part of a disaster recovery plan to be sure you're comfortable with that operation should some sort of disaster occur, but Solr should be as stable and secure.
What weighs in when migrating lots of external content to MongoDB and/or SOLR? I am tasked with importing a large bulk of transaction data and make it available to my Sitecore solution. We're talking roughly 10 million transaction records that we need to be able to utilise real-time on the site. I've already ruled out importing all of this into a Sitecore Bucket or so; it would add massive overhead to the solution which we don't need right now. We have SOLR, MongoDB and MS SQL Server available as our remaining storage options. I'd like to keep MS SQL server out of the mix for now - and have it focusing on other tasks. But when it comes to MongoDB vs SOLR, it becomes more difficult to see exactly why I would choose one over the other. Looking at System Properties Comparison MongoDB vs. Solr - they have most things in common . They are both: Document Stores (SOLR is a Document Store specialised for searching) Schema-free (we have about 20 different transaction types, more will come) There are a few things MongoDB offers, but none seem relevant to our solution: User/Role access rights Immediate Consistency So I'm left wondering; why would I choose one over the other? Are there performance benefits to consider? (MongoDB being written in C++, SOLR in Java) - scalability concerns? Anything I've overlooking? To clarify; I'm looking for the key thing - should one exist - that sets these two technologies apart and would allow me to weigh in one over the other. Or reassurance that in this case, it's a case of tomatoes vs tomatoes. Update: Edited to clarify requirements We are receiving between 2500 and 3000 new transactions per day 99% of our queries will be of the nature "give me all transactions for entity x between dates start and end On administrator discretion, a transaction migration can be triggered during the day. It's important that data doesn't go offline while this takes place Data doesn't live here. It is sourced from elsewhere and worst-case can be re-integrated from ground up in a disaster scenario Migration happens nightly. We don't need a real-time view of transaction data
I think your best option (requiring no code or overwrites) would be to configure UrlRewrite to filter out the header. There are already half a dozen reasons why you might have this module installed already on your server - might as well use it. Open up UrlRewrite for your site, and click "View Server Variables". Then add your X-Frame-Options header. Then proceed to create an Outbound Rule where you explicitly rewrite your X-Frame-Options header to DENY as required. Source: Remove Unwanted HTTP Response Headers
How to set X-Frame-Options to deny? I have a recently upgraded solution, now running on Sitecore 8.1-upd3. Apparently in this version, Sitecore includes a http module to include a X-Frame-Options header, set to SAMEORIGIN: <add type="Sitecore.Web.XFrameOptionsHeaderModule, Sitecore.Kernel" name="SitecoreXFrameOptionsHeaderModule" />. All very nice, but my customer wants it set to DENY for the CD servers. I checked the code from the module and the value is rather hardcoded, although there is a check not to overwrite an existing value: HttpResponse response = HttpContext.Current.Response; if (!Enumerable.All<string>((IEnumerable<string>) response.Headers.AllKeys, (Func<string, bool>) (key => key != "X-Frame-Options")) || !(response.ContentType == "text/html")) return; response.Headers.Add("X-Frame-Options", "SAMEORIGIN"); What would be the best way to set this header to DENY? (considering maintainability, performance, effort, ...)
So out of the box it is not possible to use different search handler through Sitecore SOLR content search. Sitecore's SOLR implementation is based on SOLR.NET, which hard codes the search handler to use in the "SolrQueryExecuter" class. /// <summary> /// Default Solr query handler /// </summary> public static readonly string DefaultHandler = "/select"; The DefaultHandler to use from the SolrQueryExecuter class. The original code can be found here. https://github.com/mausch/SolrNet/blob/master/SolrNet/Impl/SolrQueryExecuter.cs You could implement your own executer class an patch it through the SolrNET Startup container you are using. Register<ISolrQueryExecuter<T>>(c => new SolrQueryExecuter<T>(c.GetInstance<ISolrAbstractResponseParser<T>>(), connection, c.GetInstance<ISolrQuerySerializer>(), c.GetInstance<ISolrFacetQuerySerializer>(), c.GetInstance<ISolrMoreLikeThisHandlerQueryResultsParser<T>>())); The initialization code for the default SolrQueryExecuter do in the SolrNET.Startup.Init method. The Original code can be found here: https://github.com/mausch/SolrNet/blob/master/SolrNet/Startup.cs The SolrNET.Startup.Container is a public property, and thus can be altered. However this will not give you the option to choose which one to use on query time.
Can I set up Sitecore ContentSearch to use a separate Search- and Requesthandler on SOLR per site? As the question says; do I have any options of setting/defining my own Search- and Request-Handlers for Sitecore ContentSearch, based on the active site? Skimming through ContentSearch configs, I'm not even sure where the default SearchHandler is defined, much less if there is code anywhere than I can hook into, to control it. Example: Scenario could be; where we have say /products and /productsinstock search handlers; where the latter one would - as an example - the following filter added. <lst name="appends"> <str name="fq">inStock:true</str> </lst>
The above queries are correct for checking for any renderings that have not been set by standard values. For those set my standard values only the queries will return no results. If the page has been edited in content editor or experience editor then results will be returned.
Database Query for Sitecore database final renderings fields I want to query the Final renderings fields for an item in Sitecore directly against the database to check if they have ever had values. I have created the following query but want to be sure it's correct: SELECT TOP 1 [Id], [ItemId], [FieldId], [Value], [Created], [Updated], [DAC_Index] FROM [VersionedFields] WHERE fieldid = '04BF00DB-F5FB-41F7-8AB7-22408372A981' AND ItemId = '947EBF93-E9F2-4C12-8BC3-78B75B595428' My query doesn't return any results for this item but I'm assuming this is because it has never had any renderings added to the page or edited and it is just using the renderings set on the standard values of my page template. Also I would like to do a similar query for the renderings field but I don't get any results for this either so wanted to be sure this query is also right: SELECT TOP 1 f.[Id], [ItemId], [FieldId], [Value], f.[Created], f.[Updated], f.[DAC_Index], i.Name FROM [SharedFields] f INNER JOIN [Items] i ON f.itemid = i.id WHERE fieldid = 'F1A1FE9E-A60C-4DDB-A3A0-BB5B29FE732E' AND ItemId = '947EBF93-E9F2-4C12-8BC3-78B75B595428' I'm doing these queries as I want to see if my page item has ever had any renderings set in experience editor in the database backups I have - or if it just has the values from standard values and it's never been updated. Further Information: Sitecore 8.1 update 2 To be clear the question I need to answer is: do these queries confirm my page has never had any updates to the renderings?
In a clean install of Sitecore 8.1 update-3, the templates and their related sections/fields are always created in English, no matter what language the user may be working in from the ribbon: But if your user/developer has changed their language preference in their profile (Control Panel > Region and language options > Display language) then the template is created if their preference language. Short Answer The simplest solution is to ensure that the language preference for all your developers/users is English when working with templates. Long Answer The issue is in the Sitecore Template Builder code itself. If you feel this is a bug then you should report it to Sitecore and ask for a fix. My investigation leads me to believe that the issue is in \sitecore\shell\Applications\Templates\TemplateBuilder\TemplateBuilder.xml and it's related CodeBeside located in Sitecore.Shell.Applications.Templates.TemplateBuilder.TemplateBuilderForm in Sitecore.Client.dll An initial check is made that the user has the correct write permissions to create/edit templates in the language selected from the ribbon, but the sections and fields are created without passing this selected language into account. Instead, all calls are made without any language parameter being passed so it uses Sitecore.Context.Language, i.e. the user preference language stored in their profile. There is no easy way of overriding the methods you need; Save(), SaveTemplate(), SaveSection() and SaveField() are all either non-virtual or private static. Wrapping HandleMessage() in LanguageSwitcher("en") also does not work since the call is initiated with Context.ClientPage.Start() and the language reverts back to the user preference. You could fix it but not cleanly, it means overriding a lot of code which increases the possiblility of issues if you upgrade and Sitecore changes their own internal implementation.
Force template versions in English In a multi-language solution, the developers switch back and forth between multiple languages when creating content, testing, etc. If the developer forgets to change the context language to English, before creating a new template, only a version in the current context language will be created (along with sections, fields, __Standard Values etc). Is there any way to force an English version, when a template (and children) is created? Update We are not currently using any language fallback features, so we are not facing any concrete issues. The request is mostly for consistency in the solution.
There are a few options that may work for you: Disable the tracker in code behind Set Tracker.Enable to false in the pre-initialization stage of your page: protected override void OnPreInit(EventArgs e) { Sitecore.Analytics.Tracker.Enabled = false; } Disable tracking for the page item If your error page is represented by a Sitecore item, you can do the following: Open the Content Editor; Select your error page item in the content tree; Click the button "Attributes" in the ribbon "Analyze"; Go to the "Settings" tab; Check the checkbox "Disable analytics for this page"; Publish. Disable tracking on the <site> definition Put your error page into a separate site and set the enableTracking attribute to false on the site definition. Disable tracking in a custom <startAnalytics> processor xDB uses the startAnalytics pipeline to check whether or not it should be active in the current request. You can add your own processor to this pipeline: <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <startAnalytics> <processor type="Your.Custom.Processor, Your.Assembly" patch:after="processor[@type='Sitecore.Analytics.Pipelines.StartAnalytics.CheckPreconditions, Sitecore.Analytics']" /> </startAnalytics> </pipelines> </sitecore> </configuration> In your custom processor, you'll need to set Tracker.Enabled to false based on some condition. For example, you can do it if a certain cookie is present or if a custom query string parameter takes a specific value.
Disable xDB tracking for single requests I am using our own Sitecore Error Manager in a Sitecore 8.2 project. If an item is not found or an error occurs, our error page is called within the current client request. This error handler calls a configured Error content page within Sitecore. Since the introduction of the xDB, a call to this page takes > 10 seconds before the internal request finishes. This happens, because we forward all client cookies to this call, including the Analytics cookie. At the end of this pageload, we see the following in the logfile: Overriding expired contact session lock for contact id: 41a8f96f-7aa8-413e-9731-eecbb414bd24 This happens because the user currently has an open request. The nested request runs into the session lock which eventually get released. Question: Is it possible to disable the Tracker for this nested request by request parameter or a cookie or something? It is not neccessary at all. Not forwarding the analytics cookie is my least favorited solution since the request would be tracked with a new visitor session, which fills the contacts with garbage data. I tried to stop the tracking in the Analytics settings of the nested page itself but had no luck with this. The problem still appears.
Check that the users' Roles have access to the Languages they are attempting to edit. You can do this by opening the Access Viewer, selecting the role, and navigating to System/Languages. Don't just check the Read and Write settings, it's the Language Read and Language Write settings that control access to Items based on that language. If Language Write is set to deny, the user will not be able to edit any content in that language. To see those, you will have to click the Columns button and make sure that they are selected.
Content editors are not able to edit versions of different language Sitecore 7.1 Has anyone experienced that content editor is able to change only one language (Dutch in this example) but not the English? Both languages have more than 5 versions. The strange thing is, when you select the languages on the top right side, English is not even shown. The role for content editors is the custom one, since certain items had to be hidden.
Disclaimer: I've never actually tried this myself. But looking at the code you're using, there are two base conditions for the conditions you're dealing with. And based on your own statement; it works when you use one of these - you just want to get rid of having to define an operator for your condition. public abstract class TypedQueryableOperatorCondition<T, TItem> : OperatorCondition<T>, IQueryableRule<TItem> where T : QueryableRuleContext<TItem> where TItem : IObjectIndexers and public abstract class TypedQueryableStringOperatorCondition<T, TItem> : StringOperatorCondition<T>, IQueryableRule<TItem> where T : QueryableRuleContext<TItem> where TItem : IObjectIndexers Both of these are operator based. Now - based on previous experience (and this is where I'm guessing, in fact) - Sitecore will only spawn your Conditions if the class satisfies a certain signature. And given both of the above are operator conditions, none of them will do what you want. My proposal would be to create another base class: public abstract class TypedQueryableWhenCondition<T, TItem> : WhenCondition<T>, IQueryableRule<TItem> where T : QueryableRuleContext<TItem> where TItem : IObjectIndexers And then your concrete class like: public class ContactPropertyCondition<T> : TypedQueryableWhenCondition<T, IndexedContact> where T : VisitorRuleContext<IndexedContact> This should give you the required method signature and with any luck, Sitecore will instantiate it for you.
Binary rule for list segmentation We have custom facets for contacts and these facets are used for segmentation in lists (segmentation rules defined at '/sitecore/system/Settings/Rules/Definitions/Elements/Segment Builder'). Segmentation works fine if the condition type inherits TypedQueryableOperatorCondition<T, IndexedContact> and 'Text' of the condition item contains [operatorid,Operator,,compares to] But now we need segmentation based on a boolean flag facet, so what I want to do is add this condition and see the text like where contact property is true without selecting 'compare operation' which is useless here. The trouble is that Sitecore (v8 upd 4) does not even load the condition class if [operator] phrase is missing in the Text.
After reviewing Sitecore's upgrade documentation (All 8+ versions are listed here: https://dev.sitecore.net/Downloads/Sitecore_Experience_Platform.aspx. Each page has a link to it's Upgrade Guide which indicates pre-requisites for installation) the upgrades you would need to perform to get to Sitecore 8.1 Update 3 would be: Upgrade to Sitecore 8.0 Initial Release (rev. 141212) Upgrade to Sitecore 8.1 Initial Release (rev. 151003) Upgrade to Sitecore 8.1 Update 3 (rev. 160519) At the time of writing this, Sitecore 8.2 Initial Release (rev. 160729) is the most recent version. If you were to choose to go to this version, you could skip Step 3 above and perform the upgrade for Sitecore 8.2 Initial Release, instead.
Upgrade from 7.5 to 8.1 Update 3 We are currently running version Sitecore.NET 7.5 (rev. 141003) and would like to upgrade to Sitecore 8.1 Update 3. Does it make sense to do an incremental upgrade in the following order? Sitecore.NET 7.5 (rev. 141003) Sitecore 8.0 Sitecore 8.1 Sitecore 8.1 Update 1 Sitecore 8.1 Update 2 Sitecore 8.1 Update 3
I've researched this a bit myself and come up with the following answer. If there's a better, more general way of answering this for every dialog, or if anyone has more specific information about how everything is set up please don't hesitate to answer! As of Sitecore 8.1 Update 3 (I'm not sure how many versions this is applicable for), a certain set of dialoges are defined in the core database under the following location: /sitecore/client/Applications/Dialogs (Item ID: {648AFADA-20C7-413A-9636-44703A16DFCF}). Highlighted in the image below is the dialog that I'm specifically asking about: SelectMediaDialog (Item ID: {ACA0FE9D-0FFD-4043-96DC-B702D1B44F39}). Under every node that has a template of Speak-DialogPage, there's a SearchConfigs folder that resides under each Speak-DialogPage's PageSettings node. The SearchConfigs folder contains a set of items that are used to define which search facets are available. The fields on these items are "predefined" and have explicit hardcoded meaning. For example the RecentlyUploadedByMe item which defines the Recently uploaded by me facet seen in the first screenshot has the following fields set: The Base Templates field defines which templates to search on, and is currently set with all known media types: Certain filters that limit the search to items created by the current user and items created within the last seven days. The latter set of "Date" and "User" fields appear to be used by the Sitecore.ItemWebApi.Pipelines.Search.SetSearchParameters (in "Sitecore.Speak.ItemWebApi.dll") processor. This processor will check for that particular set fields and then modify the search query in the appropriate fashion. So if you wanted to extend the or modify the available behavior, you'd have to extend the SearchPanel Config template, create your own processor and then patch it in. Here's the currently decompiled code for the Sitecore.ItemWebApi.Pipelines.Search.SetSearchParameters processor, so you can see it in action: public override void Process(SearchArgs args) { Assert.ArgumentNotNull((object) args, "args"); Item searchDescriptor = args.SearchDescriptor; if (searchDescriptor == null) return; this.SetTemplateFilter(args); if (searchDescriptor["UpdatedWithin7Days"] == "1") { DateTime to = DateTime.UtcNow.AddDays(1.0); DateTime from = DateTime.UtcNow.AddDays(-7.0); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => MethodExtensions.Between<DateTime>(i.Updated, from, to, Inclusion.Both))); } if (searchDescriptor["CreatedWithin7Days"] == "1") { DateTime to = DateTime.UtcNow.AddDays(1.0); DateTime from = DateTime.UtcNow.AddDays(-7.0); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => MethodExtensions.Between<DateTime>(i.CreatedDate, from, to, Inclusion.Both))); } if (searchDescriptor["UpdatedByCurrentUser"] == "1") { string userName = Context.GetUserName().Replace("\\", string.Empty); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => i["parsedcreatedby"] == userName)); } if (!string.IsNullOrEmpty(searchDescriptor["UpdatedBySpecificUser"])) { string userName = searchDescriptor["UpdatedBySpecificUser"].Replace("\\", string.Empty); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => i["parsedcreatedby"] == userName)); } if (searchDescriptor["CreatedByCurrentUser"] == "1") { string userName = Context.GetUserName().Replace("\\", string.Empty); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => i["parsedcreatedby"] == userName)); } if (!string.IsNullOrEmpty(searchDescriptor["CreatedBySpecificUser"])) { string userName = searchDescriptor["CreatedBySpecificUser"].Replace("\\", string.Empty); args.Queryable = Queryable.Where<ConvertedSearchResultItem>(args.Queryable, (Expression<Func<ConvertedSearchResultItem, bool>>) (i => i["parsedcreatedby"] == userName)); } string queryString1 = WebUtil.GetQueryString("pageSize", searchDescriptor["PageSize"]); if (!string.IsNullOrEmpty(queryString1)) args.PageSize = MainUtil.GetInt(queryString1, 0); string queryString2 = WebUtil.GetQueryString("pageIndex"); if (string.IsNullOrEmpty(queryString2)) return; args.PageIndex = MainUtil.GetInt(queryString2, 0); }
In the "Select Media" dialog, where are the search facets defined at in Sitecore? This is for Sitecore 8.1 Update 3. In the Select Media dialog that pops up on certain media fields (for example, clicking Browse on an image field), I want to know where the search facets are defined at. Are they defined within the CMS or in a configuration file? Can you modify the behavior of these facets or create your own? The search facets I'm specifically interested in are highlighted in the screenshot below: All image files All video files My images Recently uploaded images Recently uploaded videos Recently uploaded by me
Making wildcard queries work I had exactly the same issue with a custom Lucene query. The fix was to use .MatchWildcard() instead of .Contains(). In your case, to prevent escaping in both instances, you'd need to replace i["fieldName"].Contains(role) with // C# 6 i["fieldName"].MatchWildcard($"*{role}*") // C# 5 i["fieldName"].MatchWildcard(string.Format("*{0}*", role)) A potentially better approach I have doubts as to why you even need a wildcard query. With a wildcard query, by querying *extranet\\Foo* you will match extranet\\FooBar as well, which is probably not your intention. I think you want to match the exact role names, so Equals() instead of a wildcard query would work faster and more precisely. var readPredicate = userRoles.Aggregate( PredicateBuilder.False<T>(), (current, role) => current.Or(i => i["read_roles"].Equals(role))); var denyPredicate = userRoles.Aggregate( PredicateBuilder.True<T>(), (current, role) => current.And(i => !i["denied_roles"].Equals(role)));
Why is Sitecore not sending a correctly formed query to Solr? I have a site that I have upgraded from v7.5 to v8.1. In addition I have changed from Solr 4.7 to Solr 4.10. In my general search routine I am trying to filter out content items based on Sitecore role membership and which roles have read access to an item and which roles are denied. To accomplish this we have two custom fields in the Solr index. One is called read_roles and one is called denied_roles. For the purposes of this question all that really matters is read_roles. The read_roles field in the Solr index looks like this: "read_roles_sm": [ "Emailcampaign\\Common Opt Out", "Emailcampaign\\Two-Column Message Opted Out", "extranet\\Anonymous Role", "extranet\\Approved Role", "extranet\\DistribA", "extranet\\DistribB" ], In my C# code that does the searching I have a method called ApplySecurityFilter that looks like this: public static IQueryable<T> ApplySecurityFilter<T>(this IQueryable<T> query) where T : SearchResultItem { var userRoles = Sitecore.Context.User.Roles.Select(r => r.Name); var readPredicate = PredicateBuilder.False<T>(); readPredicate = userRoles.Aggregate(readPredicate, (current, role) => current.Or(i => i["read_roles"].Contains(role))); var denyPredicate = PredicateBuilder.True<T>(); denyPredicate = userRoles.Aggregate(denyPredicate, (current, role) => current.And(i => !i["denied_roles"].Contains(role))); if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(readPredicate); } if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(denyPredicate); } return query; } This all works fine in v7.5 with Solr 4.7. The code runs and translates my Linq style query in to a query that Solr can handle. In the end when I look in the log files this is part of the query that gets sent to Solr. &amp;fq=(((-denied_roles_sm:(*extranet\\Anonymous\ Role*) AND read_roles_sm:(*extranet\\Anonymous\ Role*)) AND _latestversion:(1)) And that works great. Now when I run the exact same code in v8.1 with Solr 4.10 for some reason the query that gets sent to Solr is slightly different. It looks like this: &amp;fq=(((-denied_roles_sm:("\*extranet\\Anonymous\\ Role\*") AND read_roles_sm:("\*extranet\\Anonymous\\ Role\*")) AND _latestversion:(1)) As you can see for some reason the Solr provider seems to have modified the text of the role name that gets sent to Solr. And there are no matches and therefore I get no results returned. I can't figure out why the upgraded version of my site is sending the query to Solr in a slightly different way. Any ideas?
There are OOTB options. Take a look at this answer here. Removing all references to an item using OOTB tools All of the proposed answers will require you to (temporarily) delete the item and rely on Sitecore's remapping tool. But you won't lose your rendering. As far as safe goes; it's the safest way I can think of. And requires no coding.
Safely replacing all references to an Rendering with another I have a controller rendering which is referenced by the standard values on most of my page templates and I need to substitute it everywhere it is used to use a different controller rendering instead. I want to do this in a safe way without deleting the item. I know I could delete it and then use the Sitecore out of the box 'linke to another item' option that is given in the popup when confirming the delete. However I want to keep my existing item for the time being. I have seen posts such as this: https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/programmatically-update-layout-details-with-the-sitecore-asp-net-cms But I wondered if there is an easier/better/safer way to do this. Also I know I need to consider both the Renderings and Final renderings fields as I using Sitecore 8.1 update 2. -- Update -- Additional information is that the rendering in question is synced with Unicorn to Staging and Prod so the solution here needs to account for this item existing in other environments. Ideally I'd do it once locally and unicorn would track the changes and push the change out to Staging and Production. One issue though is that we don't have all content locally and we don't sync content with unicorn (just templates, layouts etc).
I suggest you use a SearchDataSource and then bind it to your ListControl. Check this post for binding example: https://visionsincode.wordpress.com/2016/10/17/put-json-data-in-your-searchdatasource-and-bind-it-to-searchabledroplist-sitecore-speak/ Now, in your code, if you do this (jsondata.Communications needs to be an array): providerHelper.getData( this.AdditionalInfoDataProvider, $.proxy(function (jsondata) { cintelUtil.setText($that.CompanyValue, renderUrl(jsondata.Company, jsondata.CompanyUrl), true); /* working correctly */ cintelUtil.setText($that.IndustryValue, jsondata.Industry, true); /* working correctly */ cintelUtil.setText($that.SubIndustryValue, jsondata.SubIndustry, true); /* working correctly */ cintelUtil.setText($that.RevenueRangeValue, jsondata.RevenueRange, true); /* working correctly */ cintelUtil.setText($that.IsKnownExecutiveValue, jsondata.IsKnownExecutive, true); /* working correctly */ cintelUtil.setText($that.IsKnownCustomerValue, jsondata.IsKnownCustomer, true); /* working correctly */ cintelUtil.setText($that.IsKnownBlogUserValue, jsondata.IsKnownBlogUser, true); /* working correctly */ cintelUtil.setText($that.OptInValue, jsondata.OptIn, true); /* working correctly */ $that.YourSearchDataSource.set('items', jsondata.Communications); providerHelper.initProvider(this.AdditionalInfoCommunicationDataProvider, "", url, this.AdditionalInfoCommunicationMessageBar); })); Since this is SPEAK version 1 (using set) I think you should do this: $that.YourSearchDataSource.set('items', jsondata.Communications); SPEAK2 is so much cleaner, so you can use this: $that.YourSearchDataSource.Items = jsondata.Communications; You will also need to create column definitions for the list control; here is an example from the LatestVisitors list on the dashboard in the Experience Profile: Then you will need to create a Columnfield for each column: Sent, ContactType, and Message Don't forget to enter the JSON field name (from the JSON array) in the DataField on the Columnfield: Finally, go to your layout and select your list control to get its properties. Locate the DataSource attribute and point it to your new ColumnDefinitions item: That should be it, I hope it will help you :-)
Example of populating list in experience profile page with JSON data I am setting up a custom tab with custom facet data in the Experience Profile. I am successfully returning text values to the screen. Now, I want to populate data into a list control. Are there any examples of this. In my AdditionalInfoPanel, I have a GenericDataProvider and a ListControl. My list has three columns: for Sent, ContactType, and Message. My javascript file looks like this: define([&quot;sitecore&quot;, &quot;/-/speak/v1/experienceprofile/DataProviderHelper.js&quot;, &quot;/-/speak/v1/experienceprofile/CintelUtl.js&quot;], function (sc, providerHelper, cintelUtil) { var app = sc.Definitions.App.extend({ initialized: function () { var localUrl = &quot;/customfields/&quot;; providerHelper.setupHeaders([ { urlKey: localUrl } ]); var url = sc.Contact.baseUrl + localUrl; var communicationData; var $that = this; providerHelper.initProvider(this.AdditionalInfoDataProvider, &quot;&quot;, url, this.AdditionalInfoTabMessageBar); providerHelper.getData(this.AdditionalInfoDataProvider, $.proxy(function (jsondata) { cintelUtil.setText($that.CompanyValue, renderUrl(jsondata.Company, jsondata.CompanyUrl), true); /* working correctly */ cintelUtil.setText($that.IndustryValue, jsondata.Industry, true); /* working correctly */ cintelUtil.setText($that.SubIndustryValue, jsondata.SubIndustry, true); /* working correctly */ cintelUtil.setText($that.RevenueRangeValue, jsondata.RevenueRange, true); /* working correctly */ cintelUtil.setText($that.IsKnownExecutiveValue, jsondata.IsKnownExecutive, true); /* working correctly */ cintelUtil.setText($that.IsKnownCustomerValue, jsondata.IsKnownCustomer, true); /* working correctly */ cintelUtil.setText($that.IsKnownBlogUserValue, jsondata.IsKnownBlogUser, true); /* working correctly */ cintelUtil.setText($that.OptInValue, jsondata.OptIn, true); /* working correctly */ communicationData = JSON.stringify(jsondata.Communications); console.log(communicationData); /* SEE NOTE 1 FOR THIS OUTPUT */ providerHelper.initProvider(this.AdditionalInfoCommunicationDataProvider, &quot;&quot;, url, this.AdditionalInfoCommunicationMessageBar); providerHelper.getListData(this.AdditionalInfoCommunicationDataProvider, communicationData); /* SEE NOTE 2 FOR ERROR */ })); } }); function renderUrl(text, url) { if (url !== null &amp;&amp; url.length > 0) { return &quot;<a href=\&quot;&quot; + url + &quot;\&quot; target=\&quot;_blank\&quot;>&quot; + text + &quot;</a>&quot;; } else { return text; } } return app; }); NOTE 1: The output of this console.log is: [{"Sent":"2016-10-18T17:25:36.831Z","ContactType":"Product Information","Message":"Looking to get information about software","IsEmpty":false}] NOTE 2: The resulting error is: caught TypeError: Cannot read property 'set' of undefined / DataProviderHelper.js:74 I am trying to figure out how to correctly bind the data in jsondata.Communications to the ListControl. I am using Sitecore 8.1 Update 2 UPDATE 1: Using suggested changes below... this is my JavasScript: define([&quot;sitecore&quot;, &quot;/-/speak/v1/experienceprofile/DataProviderHelper.js&quot;, &quot;/-/speak/v1/experienceprofile/CintelUtl.js&quot;], function (sc, providerHelper, cintelUtil) { var app = sc.Definitions.App.extend({ initialized: function () { var localUrl = &quot;/customfields/&quot;; providerHelper.setupHeaders([ { urlKey: localUrl } ]); var url = sc.Contact.baseUrl + localUrl; var communicationData; var $that = this; providerHelper.initProvider(this.AdditionalInfoDataProvider, &quot;&quot;, url, this.AdditionalInfoTabMessageBar); providerHelper.getData(this.AdditionalInfoDataProvider, $.proxy(function (jsondata) { cintelUtil.setText($that.CompanyValue, renderUrl(jsondata.Company, jsondata.CompanyUrl), true); cintelUtil.setText($that.IndustryValue, jsondata.Industry, true); cintelUtil.setText($that.SubIndustryValue, jsondata.SubIndustry, true); cintelUtil.setText($that.RevenueRangeValue, jsondata.RevenueRange, true); cintelUtil.setText($that.IsKnownExecutiveValue, convertBooleanToYesNo(jsondata.IsKnownExecutive), true); cintelUtil.setText($that.IsKnownCustomerValue, convertBooleanToYesNo(jsondata.IsKnownCustomer), true); cintelUtil.setText($that.IsKnownBlogUserValue, convertBooleanToYesNo(jsondata.IsKnownBlogUser), true); cintelUtil.setText($that.OptInValue, convertBooleanToYesNo(jsondata.OptIn), true); console.log(JSON.stringify(jsondata.Communications)); $that.AdditionalInfoCommunicationDataSource.set('items', jsondata.Communications); })); } }); function renderUrl(text, url) { if (url !== null &amp;&amp; url.length > 1) { return &quot;<a href=\&quot;&quot; + url + &quot;\&quot; target=\&quot;_blank\&quot;>&quot; + text + &quot;</a>&quot;; } else { return text; } } function convertBooleanToYesNo(value) { if (value == 'true' || value == true) { return 'Yes'; } else if (value == 'false' || value == false) { return 'No'; } else { return value; } } return app; }); Here you can see the Renderings of my panel: Here you can see my List binding: Here you can see a couple of my Column Fields: I no longer get an error, but the 'Communications' data is still not loaded in the grid. :-( Any ideas? CLOSING UPDATE @gorhal had the solution. One further step was to ensure the &quot;Items&quot; property of the ListControl was bound to the datasource items: {Binding AdditionalInfoCommunicationDataSource.Items}
You cannot. Lucene is a "local filesystem" technology. If you want something that is shared between multiple Content Delivery server instances; you need to switch from Lucene to SOLR. If you're using the recommended Sitecore ContentSearch APIs this is (mostly) a relatively simple matter of switching your configuration files and setting up the SOLR index properly. Benefits of using Solr: It is heavily optimized for search performance with a powerful query cache. It can handle a large number of documents. There is detailed configuration support for language indexing. You can shard indexes across multiple servers. With Solr Cloud you can also split an index across multiple physical locations. From Sitecore Search Scaling Guide
How to maintain Sitecore Lucene Indexes in a huge content delivery web farm? Sitecore keeps a local copy of the lucene index in the file system of each instance and doesn't support sharing in the indexes between instances. How can I achieve this?
I rebuilt the index completely and that seems to have fixed the problem. I am no longer getting the NULL error.
Why would SearchResultItem.Paths be null? I am using Sitecore 8.1 with Solr 4.10 doing a general site search. I have a repeater on my search results page and I am binding the results to that repeater. For some reason in my QA environment I am getting an error when I try to access searchHit.Document.Paths. It is always coming back as null. This works fine in my local development environment. Could it be a configuration problem? Do I need to re-index? Here is the code from my repeater. It fails on the IF statement because searchHit.Document.Paths is NULL. protected void rptResults_OnItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { var searchHit = (SearchHit<GeneralSearchResultItem>) e.Item.DataItem; var hypItem = (HyperLink) e.Item.FindControl("hypItem"); var spnIcon = (HtmlGenericControl) e.Item.FindControl("spnIcon"); var litTitle = (Literal) e.Item.FindControl("litTitle"); var litDescription = (Literal) e.Item.FindControl("litDescription"); var mediaLibraryRootItem = Sitecore.Context.Database.GetItem("/sitecore/media library"); if (searchHit.Document.Paths.Contains(mediaLibraryRootItem.ID)) { hypItem.NavigateUrl = searchHit.Document.ItemUrl; litTitle.Text = searchHit.Document.MediaTitle; litDescription.Text = TruncateString(searchHit.Document.MediaDescription, 200); } else { hypItem.NavigateUrl = searchHit.Document.ItemUrl; litTitle.Text = searchHit.Document.Title; litDescription.Text = TruncateString(searchHit.Document.Description, 200); } var iconClass = searchHit.Document.IconClass; if (iconClass != "") { spnIcon.Attributes["class"] = "icon " + iconClass; } } }
Based on comments, the answer to this question appears to be data issue within the Sitecore Database itself. It appears the issue resolved itself after performing a database restore. So, some conjecture on how this might happen: If the Display Name field was somehow duplicated indicating that there were two fields with the same Name in the database, but with different Item ID's, I could see how this would possibly happen. But to be honest, I'm having a difficult time replicating a similar scenario. A failed upgrade package install which might have left bad item id's in the database. Index or cache confusion Resolution to fix this issue as it stands appears to be to restore the database.
Unable to change DisplayName of the item In this curious case I'm facing here, I'm unable to change any item's Display Name. I have tried changing DisplayName from Ribbon menu, from Appearance section and Sitecore Rocks. I can write new text but after save when item is reloaded it is still old Text in DisplayName. I have tried cache clearing as well. I have tried lot different of ways to track down if the issue is with Sitecore setup, or My code (like may be events handlers, pipelines, etc), or may be database. Finally found that issue is with database when i tried this database with clean Sitecore instance pointing it. And I was able reproduce the editing not working anymore in clean Sitecore instance. Next I'm not sure how to identify what is the issue in this database that I'm unable to edit Display Name only. Rest of the fields I'm able to edit. Note: Sitecore 7.5 update-2 Kindly help.
You could probably write a custom event handler for the item:versionAdded event. In the event handler you can extract the item the event was fired for and inspect for any data source items below it in the tree, adding versions to the data source items as you go. Just be careful you don't end up in a loop, as saving an item from an event handler will cause event handlers to fire for that item, quite possibly the same event handler again, so you'll need to ensure you've got appropriate guarding on the event handler code, like checking to ensure the target item inherits from some given template. The benefit the event handler has is that it will also work in the Content Editor. Create a new language version of an item in the Content Editor and the event handler is still fired, so you're language versions of the data sources would also be created there.
Adding a new language version of a component in Experience Editor We're building a multi-language site, focusing on Experience Editor. When browsing to a page that doesn't have a version in the current language, you are given the option to add a language version: This functionality doesn't appear to extend to any components in use on the page. If I add a rendering and datasource it against an existing component that doesn't have a version for the current language, it is displayed in the fallback language as read-only. The only way I can see to add a new language version is to switch to Content Editor, find the component, and then add the new language using the versions drop-down. Is there an easier way of allowing editors to do this without leaving Experience Editor?
If you decompile and have a look at the Sitecore.Data.Items.ItemEditing class, in Sitecore.Kernel, you will find that all the EndEdit(bool) method does (and the relevant parts of its overload methods do) is essentially wrap the the call to ItemManager.SaveItem with an EventDisabler. Solution 1: To apply the same technique in order to make sure that your new item only indexes once for the entire creation and editing process, instead once for creation and once for editing, you could do the following: using (new EventDisabler()) { var newItem = parent.Add(name, templateId); } newItem.Editing.BeginEdit(); newItem.Fields["Foo"].Value = fooFieldValue; newItem.Editing.EndEdit(); The problem with this solution, however, is that it will disable all events on create, not just indexing events. What if you have item:created or item:added events? Solution 2: An an alternative, you could do the following: IndexCustodian.PauseIndexing(); var newItem = parent.Add(name, templateId); IndexCustodian.ResumeIndexing(); newItem.Editing.BeginEdit(); newItem.Fields["Foo"].Value = fooFieldValue; newItem.Editing.EndEdit(); The problem here is that when you call PauseIndexing you are actually pausing indexing for the entire site. Sure, you're doing it for a very short amount of time, but you are still setting yourself up for failure. Solution 3: Another alternative is to try something like the following: using (new BulkUpdateContext()) { var newItem = parent.Add(name, templateId); newItem.Editing.BeginEdit(); newItem.Fields["Foo"].Value = fooFieldValue; newItem.Editing.EndEdit(); } This should do what you are looking for, except that it won't work as expected if you want to add child/descendant items to your item or one of its descendants (if adding from a branch template) in the same closure. By example, the following will not work as expected, because the parent, newItem, for the childItem won't be available when the childItem is added: using (new BulkUpdateContext()) { var newItem = parent.Add(name, templateId); newItem.Editing.BeginEdit(); newItem.Fields["Foo"].Value = fooFieldValue; newItem.Editing.EndEdit(); var newChildItem = newItem.Add(childName, childTemplateId); ... } Conclusion: Unfortunately, I don't think there is a way to temporarily disable indexing for a particular item or for an item creation without using one of the above. Hopefully, one of them will fit your needs.
"Silently" Create Item - Create Item Without Triggering Indexing or other Events I know that when I edit items, I can pass true to the EndEdit method to save the item without triggering events/indexing on save. Since I almost always want to edit an item after creating it, it seems silly to me that my item should be indexed twice. How can I make it so that the item is only indexed once, after saving?
The Azure Module has been deprecated from Sitecore 8.2. We will be updating the module for 8.1 to support; new Azure SQL and SDK and most important change to Redis Cache Session State Provider (as the In-Role Cache service being shut down end of November). The new Sitecore Cloud offering will be launched with Sitecore 8.2 update 1. Using ARM (Azure Resource Manager) Templates, Azure Web Apps, Application Insights, Azure Search and Redis Cache. As @BasLijten and @Trayek mention I strongly recommend you to wait on SC 8.2 update 1, it's going to be really cool in the cloud :)
Sitecore Azure deployment error - Sitecore.Azure.UI.Pipelines.PreAutomation.CheckHostedService failed I'm attempting to deploy an 8.2 site to Azure. In the Sitecore Azure tool, when I deploy to the Local Emulator, the web files are partially copied to the package location and the long error below is thrown. xDB Cloud config files are disabled. The deployment to the Azure cloud environment also fails with a "Sitecore.Azure.UI.Pipelines.PreAutomation.CheckHostedService failed" error, but one step at a time. I'm running SC 8.2, Azure SDK v. 2.9 (also tried 2.7.1). The site runs fine in IIS 8.5. ManagedPoolThread #10 16:31:01 ERROR Sitecore.Azure.Pipelines.DeployAndRun.DevFabric.CreatePackage,Sitecore.Azure,Process Exception: System.Exception Message: Job started: DevFabricDeploy|xDB Cloud Edition Configuration is failed|Create package is failed|#Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at Sitecore.Azure.Pipelines.CreateAzurePackage.Azure.XDBCloudEditionChanges.Action(RolePipelineArgsBase args) at Sitecore.Azure.Pipelines.BasePipeline.RolePipelineProcessor.Process(RolePipelineArgsBase args) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) at Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) at Sitecore.Pipelines.Pipeline.Start(PipelineArgs args, Boolean atomic) at Sitecore.Pipelines.Pipeline.Start(String pipelineName, PipelineArgs args, Boolean atomic) at Sitecore.Azure.Pipelines.DeployAndRun.DevFabric.CreatePackage.StartPipeline(AzureRolePipelineArgs args, CreateAzureDeploymentPipelineArgs deploymentArgs) at Sitecore.Azure.Pipelines.BasePipeline.RolePipelineProcessor.Process(RolePipelineArgsBase args) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) at Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) at Sitecore.Pipelines.Pipeline.Start(PipelineArgs args, Boolean atomic) at Sitecore.Azure.Managers.PipelineJobManager.Worker(Pipeline pipeline, PipelineArgs pipelineArgs) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args) at (Object , Object[] ) at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) at Sitecore.Jobs.Job.ThreadEntry(Object state)
Update: I have removed technical details about the vulnerability, since it is still present on many Sitecore installations world-wide. The Quick-and-Dirty fix If you want to remove the vulnerability quickly and without restarting your Sitecore instances, just delete PushSession.ashx—it's used very rarely anyway, and only in multi-cluster setups. You can apply the full fix later.
Technical vulnerability details on Sitecore critical vulnerability (SC2016-001-128003) What are the technical vulnerability which are covered by the critical vulnerability (SC2016-001-128003)? The KB article doesn't cover what the vulnerability is.
I ended up getting it working, but not using the RenderControl() method. It turns out, that I could just call the GetControl() to get the control for the sublayout afterall, and append that control to the child controls for the actual view. Moreover, I found that it was necessary to set the datasource, before calling the GetControl() method: var renderings = myItem.Visualization.GetRenderings(Sitecore.Context.Device, true); foreach (var rendering in renderings) { rendering.Settings.DataSource = myItem.Paths.FullPath; Control control = rendering.GetControl(); this.Controls.Add(control); // There 'this' refers to the actual View }
Sitecore 8 Webforms - Calling RenderControl() on Sublayout returns null I'm currently having some issues, while trying to render a sublayout programatically on the server-side. Basically, I want to render a sublayout found on the item myItem, that has a single rendering (sublayout) on it. The criteria is that it should render out correctly for normal mode and Experience Editor mode. Currently, this is what I've done: var builder = new StringBuilder(); using (StringWriter writer = new StringWriter(builder)) using (HtmlTextWriter htmlWriter = new HtmlTextWriter(writer)) { var renderings = myItem.Visualization.GetRenderings(Sitecore.Context.Device, true); foreach (var rendering in renderings) { var renderControl = rendering.GetControl(); rendering.Settings.DataSource = myItem.Paths.FullPath; renderControl.RenderControl(htmlWriter); } } var output = builder.ToString(); Looking at the output, this is empty. I've also tried just to call the RenderControl() and output it to a string, which is then set to null. I should also note, that I do have a PageContext in the control where this code is executed. I can also verify that I can add the renderControl as a child to a ASP placeholder control, which then renders out correctly - but only for preview mode, since is doesn't render the control out with support for the Experience Editor. What am I missing?
With a default install of Sitecore the Publishing runs as a Job. If IIS or the server is restarted, or the Application Pool for your site is Recycled the publishing task will be terminated, even if the Job did not fully complete. Once your site is brought back online, you would be required to republish in order to complete the operation. Enabling Sitecore.Publishing.Recovery.config will allow for the Publish resume the Publish when the system restarts. The initialize pipeline during application starting up is responsible for kicking off the publishRecovery pipeline, which in turn restarts the publishing. If you are running multiple CMs then presumably you have a dedicated Publishing Instance set up. This file should only be enabled on that server. Also be sure to select the correct type of recoveryStrategy in the config; FileSystemPublishRecoveryStrategy which is fine for single instances machines or DatabasePublishRecoveryStrategy if you need to take multiple instances (including DR for example) into account. Also take note of the following note from the config: Important: The publishing recovery feature is currently released as an experimental feature.
What is the impact of enabling Sitecore.Publishing.Recovery.config What is the impact of enabling Sitecore.Publishing.Recovery.config? Our CM environment consists of load-balanced Azure VMs with Azure PaaS for content delivery.
The behavior you are describing is expected if your presentation version-specific. Support for versioned Presentation Details is a native feature of Sitecore 8, and you can control the versioned (final) or the shared presentation when editing the presentation details of your item. In the screenshot above, note that there is a Shared Layout and a Final Layout tab in the Layout Details (Presentation Details) dialog. The Shared Layout tab corresponds to the presentation that is "shared" and should display regardless of the language version. In contrast, the Final Layout tab corresponds to the presentation that is "versioned" and should display only when the item is rendered in the context language. This means that presentation set in the Final Layout tab is specific to the language version of the item you are editing. If you want the same presentation settings to apply to all language versions of the item, make sure to set up your presentation in the Shared Layout tab.
Language item-fallback error when using Sitecore.Mvc.Helpers.SitecoreHelper.Placeholder method When trying to use @Html.Sitecore().Placeholder() method on a language versioned fallback item, it yields no results. I have verified that the context item falls back in Sitecore, and that the @Html.Sitecore().CurrentItem.IsFallback is true on fallback items, and pointing to the right item with @Html.Sitecore().CurrentItem.IsFallback: Has anyone encountered a similar error, and found a solution?
I would discourage you from copying your items into bucket in this case. According to Sitecore's documentation: When you store items in an item bucket, the parent-to-child relationship between the items is removed, and instead the items are organized in a folder structure according to the date and time they were created. Therefore, the item buckets feature is primarily designed for storing content items that do not need to be stored in a hierarchy. Your description of a problem states that you do have an important parent-to-child relationshipt. In such a case I would recommend one of the two possible solutions: If you have small number of products (I assume 3k is number of all the items including FAQs, newsletters, etc.) you can easily go with importing them as regular items If you plan to have larger database of products you could add only the products into a bucket and other items (FAQs, newsletters, etc.) as regular items under a separate item and connect them using for example multilist. Does this approach solves your problem?
Create bucket items from external database We are migrating our legacy application in sitecore. We have a large database that we want to reuse in our sitecore application specially dbo.Product table. Product table contains ProductName, ProductID and other foreign key references. We are using buckets for Product creation in sitecore, I want to create all the Products from external database with existing fields(ProductID, ProductName etc) and apply corresponding renderings.There are many child items under each product. What is the best approach to solve this puzzle? Product Structure :
You could create a function that checks the fieldtypes.. based on the renderField pipeline, which is executed in the fieldRenderer you should include these types: rich text single-line text text image link general link internal link multi-line text memo date datetime word document integer number That should be the complete list (on a Sitecore 8.1). There are some surprises in there, like "word document". But also note that DropList is not in there! (also mentioned here that droplist is supported by <sc:text> but not by the FieldRenderer.
Which Sitecore fields can be rendered using a FieldRenderer From my knowledge, there is a set of fields that can be rendered out using a FieldRenderer like text, numbers, dates, etc. Additonally, there are also fields that cannot be rendered out, such as fields that stores ID's or list of ID's, like links, references, etc. Instead of hard-coding my knowledge, I would like to know if there is a way where I can check if a field (type) has FieldRenderer support, or not (in code). Is this possible?
The solution I used was the publishing Roles (as in the description) in addition to a workaround for the bug in Sitecore mentioned above. You can find the full solution here Update: In short, the workaround to overcome the bug in Sitecore was to override Sitecore's 'PublishForm' and uncheck the publish with sub-items checkbox by default. So every time the publish dialog is opened the 'Publish with sub-items' checkbox is NOT checked.
How to revoke publishing of sub-items for a role? I need to prevent certain roles from publishing sub-items. I was able to hide the 'Sub-items' option in the publish dialog by revoking 'Read' from '/sitecore/system/Settings/Security/Policies/Publish/Can Perform Republish' under Core DB. However, if the last time that user published with the sub-items 'checked' it will still publish with subitems even after revoking the 'Can Perform Republish'. So the option is hidden but its value is still checked!!! Is this expected or is it a bug in Sitecore? Sitecore 8.1
The code looks like it should work. I would make the following changes to just make things a bit more robust: Add a [HttpGet] attribute to the Login action result. It could be that over https the route is hitting the Get action result first, but because it is not limited to Get it will accept Post also. [HttpGet] public ActionResult Login() Check your $form.attr('action') value. Make sure that this is either a relative path /Account/Login or if it includes the scheme (https/http), make sure the right one is in there.
Error when using custom routes with https: "Attempt to retrieve context object of type 'Sitecore.Mvc.Presentation.RenderingContext' from empty stack." We have a login/register modal that is being called via javascript on the front end. I created a custom route to point to the right action controller, and it works fine in every environment - except when we try with https. So, http://website.com/account/login works, but https://website.com/account/login throws the following error: Exception type: InvalidOperationException Exception message: Attempt to retrieve context object of type 'Sitecore.Mvc.Presentation.RenderingContext' from empty stack. The line that this error hits on is this (first line in the login controller): var datasource = SitecoreContext.GetItem<LoginForm>(RenderingContext.Current.Rendering.DataSource); Here's the custom routing in RegisterRoutes.cs: RouteTable.Routes.MapRoute("AccountLogin", "Account/Login", new { controller = "Account", action = "Login" }); Using Sitecore 8.1 rev. 160302. Edit: I should additionally note that this error is happening only after the user submits login information, but that the line this is hitting is not in the HttpPost version of the controller, which makes this mystery extra puzzling! Order of operations: Page hits the login controller (non httppost version) and loads the login view with no issues Javascript triggers the modal popup and user fills out login information and clicks the submit button 500 error is thrown and returned to the javascript from the non httppost version of the login controller. (I cannot tell at this point if httppost is also getting hit.) Additonal Edit: Adding javascript and controller action result methods. Javascript $.ajax({ url: $form.attr('action'), type: 'post', dataType: 'json', data: $form.serialize() }) .done(function (data) { console.log("data"); console.log(data); clearInterval(spinner); $self.find(".spinner").hide(); $(".login-subscribe .tabs .tab:not(.selected) a").removeClass("disabled"); if ($.isEmptyObject(data)) { window.location.reload(); return; } if (typeof data !== 'undefined') { if ('userRef' in data) { $('.modal-overlay').hide(); //success - do stuff } if ('errorMsg' in data) { $self.prop("disabled", false) .parent() .find("input[required]") .addClass("error") .end() .find(".errorMsg") .html(data.errorMsg) .show(); } } }) .fail(function (error) { console.log("fail"); console.log(error); $self.parent() .find("input[required]") .addClass("error") .end() .find(".errorMsg") .show(); }); Controller action result methods: public ActionResult Login() { var datasource = SitecoreContext.GetItem<LoginForm>(RenderingContext.Current.Rendering.DataSource); if (datasource == null) { return DataSourceNotConfiguredResult; } LogInViewModel logInViewModel = new LogInViewModel(datasource); return View(Views.LogIn, logInViewModel); } [HttpPost] public ActionResult Login(string Email, string Password, string RememberMe) { if (!string.IsNullOrWhiteSpace(Email) &amp;&amp; !string.IsNullOrWhiteSpace(Password) &amp;&amp; !string.IsNullOrWhiteSpace(RememberMe)) { bool rememberMe = false; if (RememberMe.ToLower() == "true") { rememberMe = true; } Tuple<AccountResultCode, string> loginResult = userAccountUtilities.Login(Email, Password, rememberMe); if (loginResult.Item1 == AccountResultCode.Success) { if (string.IsNullOrWhiteSpace(loginResult.Item2)) { return Content("{}", "application/json"); } return Content(loginResult.Item2, "application/json"); } else { string errorMsg = ErrorMessaging(loginResult.Item1); errorMsg = "{\"errorMsg\": \"" + errorMsg.Replace("\n", "").Replace("\"", "\\\"") + "\"}"; return Content(errorMsg, "application/json"); } } return Content(""); }
The code you have posted will always return true by the nature of how Sitecore security works. If SelectItems() returns an item, that means the Sitecore.Context.User can read it. If the current user did not have access to the item, it would return null. So you have options depending on your use case. If you just want to restrict the current context users read access to an item, then just set the security on the item, the Sitecore API will do the rest for you. If you want to check a users security, then you need to be logged in as someone who has read access and then use a User object to check the secuity. var user = Sitecore.Security.Accounts.User.FromName(domainUser, false); var item = Sitecore.Data.Database.GetDatabase("master") .SelectItems("/sitecore/content/Settings/Item1")[0]; // Option 1, pass in the user var readAccess = item.Security.CanRead(user) // Option 2, use a switcher using (new Sitecore.Security.Accounts.UserSwitcher(user)) { readAccess = item.Access.CanRead(); }
How to check access permissions on items for a user via the Security API? I am trying to check Read permission for the current user on a specific item like the following: Sitecore.Data.Database.GetDatabase("master") .SelectItems("/sitecore/content/Settings/Item1")[0] .Security.CanRead(Sitecore.Context.User) This always returns true even though the 'Access Viewer' shows revoked 'Read' permission for the same user. The revoking has been done using Roles. What is wrong with this code? UPDATE: This code is being run from publish:begin event. The Sitecore.Context.User does have the required (logged-in) user. I see this on the AccessViewer (I have edited the code to CanWrite()): But both options mentioned in the answers always return True.
From what I can find - the encodeNameReplacements are only used in MainUtil.DecodeName, MainUtil.EncodeName and MainUtil.EncodePath - These are used in both resolving url's and building them. So if the encoding is not there or if it encoded to something different it should still work ok. I could not find anything that explicitly set ,-d-, in the Url. Everything goes through one of those 3 methods. If you go with removing the encoding completely and are running v7.2u1 or earlier, you may need to set the relaxedUrlToFileSystemMapping attribute to true so that IIS doesn't try to map it to a valid Windows file path. This was updated in v7.2u2 and later. <httpruntime relaxedUrlToFileSystemMapping="true" />
Ramifications of removing encodeNameReplacement for dot (.) Sitecore has a number of encodeNameReplacements in config OOTB, I fully understand what they are and what they do since I have previously posted about it. The issue we have is we have a number of compressed (software) files, which are of the format filename-something.tar.gz. By default, when the files are uploaded Sitecore takes only the last part of the file (.gz) as the extension and then see's the dot in the rest of the filename (filename-something.tar) and this fails default ItemNameValidation regex (at this point the file is internally renamed to filenamesomethingtar.gz instead of a complete failure, but still not acceptable to us). Following a Sitecore Support ticket we updated this setting to allow dots in the filename... The issue is the encodeNameReplacements kick in: <encodeNameReplacements> ... <replace mode="on" find="." replaceWith=",-d-,"/> ... </encodeNameReplacements> With this in place, the media url is being generated as filename-something,-d-,tar.gz I could remove this replacement, but is this likely to raise other issues elsewhere in Sitecore backend? EDIT: We are running Sitecore 8.1 Update-3 As I said, I understand how the encoding and decoding works and the ,-d-, is set by the encodeNameReplacement setting I mentioned (which also applies to media url generation since Sitecore 7.2). But some of these values are valid URL characters. I can only assume they were added for a particular reason in the first place, namely to get around some issues in the back-end system. Removing this setting will require extensive testing of standard Sitecore features which we would like to avoid. I'm confident nothing in our own code will not break, not so much about Sitecore's so am trying to understand this so we can minimize issues.
You're missing Windows Process Activation Service on your computer. Check Control Panel > Programs > Programs and Features > Windows Process Activation Service. More details here: https://serverfault.com/questions/384237/service-was-was-not-found-on-computer
Error when trying to install Sitecore using SIM - "Service WAS was not found on computer" I'm currently trying to install Sitecore 8.1 rev. 160519 using SIM Tool 1.4.0.92 rev 150618 and I'm getting this error message in the logs: > 1 12:48:04,739 ERROR Service WAS was not found on computer '.'. System.InvalidOperationException: Service WAS was not found on computer '.'. ---> System.ComponentModel.Win32Exception: The specified service does not exist as an installed service --- End of inner exception stack trace --- at System.ServiceProcess.ServiceController.GenerateNames() at System.ServiceProcess.ServiceController.get_ServiceName() at System.ServiceProcess.ServiceController.GenerateStatus() at System.ServiceProcess.ServiceController.get_Status() at Microsoft.Web.Administration.ServerManager.GetServiceStatus(String serviceName) at Microsoft.Web.Administration.ApplicationPool.get_State() at SIM.Adapters.WebServer.Website.get_ApplicationPoolState() at SIM.Tool.Base.InstanceHelperEx.EnsureAppPoolState(Instance instance, Window mainWindow) at SIM.Tool.Base.InstanceHelperEx.PreheatInstance(Instance instance, Window mainWindow, Boolean ignoreAdvancedSetting) at SIM.Tool.Base.AuthenticationHelper.LoginAsAdmin(Instance instance, Window owner, String pageUrl, String browser) at SIM.Tool.Windows.MainWindowComponents.LoginAdminButton.OnClick(Window mainWindow, Instance instance) at SIM.Tool.Windows.MainWindowHelper.c__DisplayClass2d.b__25(Object param0, RoutedEventArgs param1) The other symptom is that IIS refuses to start my site. This is occurring on a Windows Server 2012 R2 machine. Has anyone encountered this message before?
The GeoIP service can be made to resolve at zipcode level. That said; you cannot rely on it to personalize your content for your visitor - real time. For that you need to look at other options - like creating your own MaxMind integration or looking at other alternatives. See also: Sitecore IP Geo location Service-Personalization with Geo-based conditions does not work
Sitecore GeoIP service with zipcode We have a need to detect the user location at the Zipcode level and present him with personalized content. We are looking to see if Sitecore GeoIP service with 8.1 supports Zipcode accuracy? Please let me know if anyone has worked with GeoIP service at Zipcode and % of accuracy that we get?
If you enable security via the SearchSecurityOptions in the CreateSearchContext checking the access rights should be done for you. Although I have heard that the TotalResults property is not ok when doing is and items are filtered out - also heard that paging might not be accurate. But the result set should be ok. More info also here. Adding security information inside the index is tempting but very tricky. Security on an item can be changed in so many ways (user changes role, inheritance is broken on a parent, language security changes...) that it is very difficult to keep all the information up to date (without rebuilding the index each time).
How to query Solr and only return content items that the current user has permissions to view? I am building a Sitecore 8.1 / Solr 4.10 site. I want to be able to do a general site content query through the web database and only return content items that the current user has permissions to view. To me this seems like a simple request and should be a no-brainer. However we never figured this out properly. So we built what seems like a convoluted solution where we have 2 different custom fields in our Solr index - one called read_roles that is a list of all of the roles that have read access to the indexed item. And another called denied_roles that is a list of all of the roles that do not have read access to the indexed item. Then in our search method we apply a security filter using the following code: public static IQueryable<T> ApplySecurityFilter<T>(this IQueryable<T> query) where T : SearchResultItem { var userRoles = Sitecore.Context.User.Roles.Select(r => r.Name); var readPredicate = PredicateBuilder.False<T>(); readPredicate = userRoles.Aggregate(readPredicate, (current, role) => current.Or(i => i["read_roles"].Equals(role))); var denyPredicate = PredicateBuilder.True<T>(); denyPredicate = userRoles.Aggregate(denyPredicate, (current, role) => current.And(i => !i["denied_roles"].Equals(role))); if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(readPredicate); } if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(denyPredicate); } return query; } This seemed to work in Sitecore v7.5 but now I am having trouble in Sitecore 8.1. Is there some simpler way of restricting the results in a Solr query to only be items that the current user has read access to? Corey
If you are talking about following templates (not any custom that I am not aware of): Dictionary folder: {267D9AC7-5D85-4E9D-AF89-99AB296CC218} Dictionary entry: {6D1CD897-1936-4A3A-A511-289A94C2A7B1} Then the answer is YES. In one open source module we haven't change many dictionary items for a long time (5 years already) and everything is fine.. Sitecore Package structure wasn't changed since Sitecore 7.5 for sure so I don't see any contraindications.
Sitecore Package Created on One Version and Imported to a Different Version If I create a Sitecore package for some Dictionary items with Sitecore 7.5, can I import the package to a site running on Sitecore 8.1 Update 3?
You can't do that out of the box with Fortis because under the hood it is just using the standard Sitecore Field Renderer. This is what is adding the width and height attributes. There is a nice solution here that adds a new processor to the RenderField pipeline that strips out those attributes if a parameter called responsive is added. With Fortis you would call it like this in your razor view: @Model.ImageField.Render(new { responsive = true }) The code for the processor is as follows. It uses a simple regex to remove the width and height attributes from the rendered markup if the responsive parameter exists. It then removes the responsive tag that gets added by the field renderer too. namespace SitecoreCustomization.Pipelines.RenderField { public class GetImageFieldValueResponsive { public void Process(RenderFieldArgs args) { if (args.FieldTypeKey != "image") return; if (args.Parameters.ContainsKey("responsive")) { string imageTag = args.Result.FirstPart; imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+height\s*=\s*\S+", "$1", RegexOptions.IgnoreCase); imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+width\s*=\s*\S+", "$1", RegexOptions.IgnoreCase); imageTag = Regex.Replace(imageTag, @"(<img[^>]*?)\s+responsive\s*=\s*\S+", "$1", RegexOptions.IgnoreCase); args.Result.FirstPart = imageTag; } } } } Then you can patch it in like this: <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <renderField> <processor patch:after="*[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']" type="SitecoreCustomization.Pipelines.RenderField.GetImageFieldValueResponsive, SitecoreCustomization"/> </renderField> </pipelines> </sitecore> </configuration>
Is there a way to supress rendering width and height attribs using Fortis Image.Render? Using Fortis Image.Render, is there a parameter to suppress rendering the Width and Height attributes? Example of the image: @Model.ImageField.Render(new { @class = "my-class-name" })
The problem here is with FillDB .. it uses quite a rough-and-ready script to make items, and so it generates items that do not have a unique revision field (it leaves this field blank so it defaults to the Standard Values field - it does this for quite a lot of the standard fields). For the Publishing Service to publish an item it must have a valid revision field, this is why it is skipping those items. We use the revision field to track uniqueness of edits to items so we can compare edits of the same version. What is happening is that the Publishing Service will look at the revision field and see no change (as the Standard Values item has not changed, so its revision field is still the same) and so thinks there is no work to do and skips the item(s). Are these issues not logged in the publish service log ? If so I will raise this as a bug to provide more user feedback.
Sitecore Publish Service not publishing new items I'm experimenting with the new Publish Service in a sandbox environment created with Sitecore Instance Manager. I followed the setup steps and I am able to publish individual items successfully. For example, I blanked out the Default Workflow field on the Sample Item standard values and published it successfully. I created a new folder under Home, then tried to fill that folder with items using the FillDb.aspx page. That all worked fine, I got a pile of folders and Sample Items under that new folder. However, I cannot publish them. I've tried Publish Site, Full Republish from the Publishing Dashboard, and clicking on my new folder and doing Publish Item with Publish Subitems checked. Neither my new folder or any of the children will publish. The publish jobs show 0 versions published, save the Full Republish which shows ~4600 items. I generated 100,000 items so that number is way low. Any ideas what might be going on?
I'm not sure it's necessarily a case of that they won't fix it, it's just a case of priority. Like all development projects, they'll have a backlog of issues and features that they want to address, and how they go about prioritising them is up to them. I'm not sure of the original decision behind the 302 redirect, and I can't think of a good reason why it should work like how it does. My honest guess would be that it was just built as a straight-forward redirect as a simple development approach, rather than a conscious decision to not account for correct status values. That is pure speculation on my part though. Though I'm supplying this as answer, someone maybe able to offer more insight here, if there is any to be had. The best thing to do would be to make sure they're aware of it as something you'd like to see changed. Raise it on the UserVoice and also considering reaching out to support.
Why does Sitecore redirect with status code 302 for page not found errors? I know that there are solutions for this, and I have written some myself, but what I don't understand is why Sitecore doesn't redirect with 404 OOTB for page not found errors. Does anyone know if there is a reason why Sitecore doesn't fix this chose to implement it this way and/or if there is any reason why they have patched it?
It looks like there is an issue with the CreateCrmEntity save action. I logged a ticket with Sitecore Support but in the meantime I was able to resolve the issue by adding the Context property to the save action as follows: public class CreateCrmEntity : Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity { public ActionCallContext Context { get; set; } public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { Context = actionCallContext; base.Execute(formId, adaptedFields, actionCallContext); } } You can then update the Assembly and Class fields in the Save Action definition here: /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions/Create CRM Entity
WFFM Dynamics CRM Campaign Itegration - Chaining save actions We're currently trying the integrate the WFFM Save Actions provided in the Dynamics CRM Campaign Integration (2.2) to create a contact, then create an CRM Entity and assign it to the contact. The module appears to provide this option, allowing us to select "Previous Save Action" as the "Use value from" and then selecting the previous save action. However even though the create contact action executes successfully, the create entity step fails with 64724 10:28:56 WARN [WFFM] 'Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity' does not contain a definition for 'Context' Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException Message: 'Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity' does not contain a definition for 'Context' Source: Anonymously Hosted DynamicMethods Assembly at CallSite.Target(Closure , CallSite , Object ) at Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity.GetValue(XCrmField field, AdaptedResultList list) at Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity.SetProperties(ICrmEntity entity, AdaptedResultList fields) at Sitecore.CrmCampaignIntegration.Submit.CreateCrmEntity.Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext, Object[] data) at Sitecore.Forms.Core.Dependencies.DefaultImplActionExecutor.ExecuteSaving(ID formID, ControlResult[] fields, IActionDefinition[] actionDefinitions, Boolean simpleAdapt, ID sessionID) 64724 10:28:56 WARN [WFFM] The 'Create CRM Entity[id={2232D4D2-7A72-44AA-A3C2-65F018A9E2B2}]' save action failed: We experienced a technical difficulty while processing your request. Your data may not have been correctly saved. This issue doesn't occur when I use "CRM" as the field source and select an existing contact. So it seems like the pass through of the previous action doesn't happen, i.e. the Form Context doesn't exist. Any thoughts on how to solve this one or work around it?
It seems I was very close with overriding Sitecore's FormsAuthenticationProvider. With our first attempt we could successfully prevent cookie replay attacks, but we were unable to access the Sitecore backend! Only GetActiceUser() is called when signing in to the Sitecore backend, the other methods not at all. So, on recommendation of Sitecore Support, we just call base when we are on the Sitecore backend. Here is the custom provider: using System; using System.Linq; using System.Web; using Sitecore; using Sitecore.Security.Accounts; using Sitecore.Security.Domains; namespace Custom.Security.Authentication { public class CustomFormsAuthenticationProvider : Sitecore.Security.Authentication.FormsAuthenticationProvider { private const string LoggedInSessionKey = "LoggedIn"; private static readonly string[] SitesToSkip = new[] { "shell", "login", "admin" }; public override bool Login(User user) { if (!base.Login(user)) { return false; } if (IsValidSite()) { HttpContext.Current.Session[LoggedInSessionKey] = true; } return true; } public override bool Login(string userName, bool persistent) { if (!base.Login(userName, persistent)) { return false; } if (IsValidSite()) { HttpContext.Current.Session[LoggedInSessionKey] = true; } return true; } public override bool Login(string userName, string password, bool persistent) { if (!base.Login(userName, password, persistent)) { return false; } if (IsValidSite()) { HttpContext.Current.Session[LoggedInSessionKey] = true; } return true; } public override void Logout() { if (HttpContext.Current.Session != null &amp;&amp; HttpContext.Current.Session[LoggedInSessionKey] != null) { HttpContext.Current.Session.Remove(LoggedInSessionKey); } base.Logout(); } public override User GetActiveUser() { if (!IsValidSite() || IsMarkedAsLoggedInOrNoSession()) { return base.GetActiveUser(); } return Context.Domain.GetAnonymousUser() ?? Domain.GetDefaultAnonymousUser(); } private static bool IsValidSite() { return !SitesToSkip.Contains(Sitecore.Context.GetSiteName(), StringComparer.OrdinalIgnoreCase); } public static bool IsMarkedAsLoggedInOrNoSession() { return HttpContext.Current == null || HttpContext.Current.Session == null || HttpContext.Current.Session[LoggedInSessionKey] != null; } } } Don't forget to let Sitecore know about your custom provider. Change web.config as follows: <authentication defaultProvider="forms"> <providers> <clear /> <add name="forms" type="Custom.Security.Authentication.CustomFormsAuthenticationProvider, Custom" /> </providers> </authentication> All this is wrapped up in a (personal) blog post on preventing cookie replay attacks in Sitecore.
How to prevent a cookie replay attack? As a result of a security audit, we must prevent an attacker from being able to do a cookie replay attack. Apparently this weakness has been around in the .NET framework for ages. There is also an old Microsoft Knowledge Base article on that subject. In contrast to the workarounds mentioned in the MS KB, the blog post recommends to mitigate this weakness by implementing the following: When signing in, set a boolean session variable to true. When signing out, set the session variable to false. Check the session variable on each request. If the value is false (or non-existing), return not authenticated. Is this method sufficient to prevent a cookie replay attack? If it is, we would like to implement this in Sitecore in a way that developers don't have to think about it. Our idea is to override Sitecore's FormsAuthenticationProvider: Override all three Login methods and initialize the boolean session variable if login succeeded. Override the Logout method to set the session variable to false. Override the GetActiveUser method and take action if the conditions are not met. But how to override GetActiveUser exactly? Do we return Context.Domain.GetAnonymousUser() ?? Domain.GetDefaultAnonymousUser(), like the AuthenticationHelper class does when there is no valid user? Or is there a better way to transparently implement this in Sitecore? Relevant information: Website is only accessible with https Cookies are already flagged as httponly and secure On log out, we call AuthenticationManager.Logout(); and Session.Clear(); Sitecore v7.2 rev 140314 .NET 4.5
The replace button doesn't appear on Experience Editor in 2 cases : When rendering doesn't have any renderings or sublayouts in Complatible Renderings field. When Renderings or sublayouts are not in Allowed Controls of the Placeholder Settings.
"Replace Rendering" in Experience Editor disabled We have renderings which have compatible renderings configured. The button in the Experience Editor (Sitecore 8.1 Update-3) shows up on our local development environments and renderings can be replaced without problems. However on our testing environment, the button is gray (disabled). What could be the cause of this? I searched for the command to look in the code what could be the cause of that. I see that it executes chrome:rendering:morph but I don't find a class which maps to this command. Anyone knows which command this is? It seems that something causes the command to be disabled.
Assuming you're using EXM 3.3 (or later) this can be done by overriding the dispatchprovider. You'll find this element under /sitecore/exm/eds/dispatchManager in the configuration (Sitecore.EDS.Providers.CustomSMTP.config or Sitecore.EDS.Providers.Dyn.config) e.g. <dispatchManager defaultProvider="default"> <providers> <clear /> <add name="default" type="Sitecore.EDS.Providers.CustomSmtp.DispatchProvider, Sitecore.EDS.Providers.CustomSmtp"> <param ref="exm/eds/connectionPool" /> <param ref="exm/eds/environmentIdentifier" /> </add> </providers> </dispatchManager> You'll need to override the SetMessageHeaders method e.g. protected override void SetMessageHeaders(EmailMessage message) { base.SetMessageHeaders(message); message.Headers.Set("Your-Header-Name", "Your-Value"); } In EXM 3.4 and later, this configuration element has changed and is now called <dispatchProvider defaultProvider="default"> <providers> <clear /> <add name="default" type="Sitecore.EDS.Providers.CustomSmtp.DispatchProvider, Sitecore.EDS.Providers.CustomSmtp"> <param ref="exm/eds/connectionPool" /> <param ref="exm/eds/environmentIdentifier" /> </add> </providers> </dispatchProvider>
EXM: Adding "List-Unsubscribe" header to emails We are currently trying to improve spam-scores for our customers' email campaigns and have used the tool https://www.mail-tester.com/ which states that we are being penalized by not including a List-Unsubscribe header/functionality. Does anyone know (or have implemented) functionality to the EXM pipeline that adds the List-Unsubscribe header to emails? Googling and the Sitecore knowledge base has failed me so far.
You can use this to set it to empty. With this you don't need to wrap the change with BeginEdit and EndEdit $item."__Display Name" = "" You only need the quotes here as there is a space in the name, a field without a space can be accessed like so: $item.MyField If you actually want to reset the field value, rather than explicitly set it as empty, use: Reset-ItemField -Item $item -IncludeStandardFields -Name "__Display Name"
How to reset DisplayName to empty using Sitecore PowerShell Extensions? I wanted to know better way to reset Display Name to empty using PowerShell scripts. I have written below script.. $item = Get-Item "/sitecore/content/home" $item.Editing.BeginEdit() $item["{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}"] = "" $item.Editing.EndEdit() which works but I'm not sure its the correct way or not. I also tried something like $item[Sitecore::FieldIDs::DisplayName] = "" which doesn't work .. Please help.
As the comments on the question rightly point out; there could be a number of potential sources for this event that happened to you. As such, I don't know if a real answer could ever be found. That said, I will attempt an answer. What you're getting here is just my experience summed up to the best guess I can come up with. I will also provide you means to verify. Here's the things you said that I will factor in: after applying the fix to our client sites How many? To me, this particular wording suggests to me that you have a medium-to-large client count and potentially all these sites are hosted in an environment you control. most of them went down for on average 30 minutes before going back up again This tells me it's variable; and site dependent. And in so, we can pretty much already rule out the patch itself - if it was a direct cause of the delay, it would be relatively equal for all sites. Applying the patch, however, restarts the application pool I checked the Sitecore Logs for one of our sites, and the only exception that caught my eye was the following This exception does not seem related to what you're experiencing. And if there are no other log entries as you state, we can conclude the sites weren't mass failing while this event took place. So with all of these assumptions in place; I think - individually - your client sites are "slow starters". While there could be any number of reasons for this; more often than not it comes down to sub-optimal information architecture and poorly designed components that query too heavily. Under these conditions, a "1st pagerequest" is usually dis-proportionally slow, subsequent requests are "fine" since Sitecore has now managed to cache all of this. To worsen the problem; you may have applied the patch rapidly. To all of the sites. All at once. And if my line of reasoning above holds true; this now means X number of sites resetting their application pools, performing sub-optimal queries en masse - completely flatlining your underlying SQL servers, not to mention CPU and memory resources of your web servers. And under these circumstances; a 30 minute or more recovery time from an application pool reset is entirely likely. To validate if my theory holds true; try resetting the apppool on 1 of your sites. Then time how long it takes for the site to respond. Then reset 2 apppools and time the first site again (after requesting home page on both). If it takes longer than the first time, this would be the smoking gun as they say. And if not; this is the information I believe we'll need - to be able to provide a better answer. Your hosting/infrastructure setup. VMs? Shared SQL servers? How many sites were updated and how quickly? "Cold Start" request time for your home page, after an app pool reset Number of items in your [EventQueue] and [History] tables This is the best I can come up with, on the given information. I hope it helps you.
After applying the Q3 2016 Security Update our sites went down As you all might know Sitecore issued a critical security hotfix, after applying the fix to our client sites, most of them went down for on average 30 minutes before going back up again, and one of them is still down, does anyone know what is causing this? I checked the Sitecore Logs for one of our sites, and the only exception that caught my eye was the following, but I still doubt that it is the cause: ERROR SessionEndPipeline failed. Exception: System.ArgumentNullException Message: Value cannot be null. Parameter name: owner Source: Sitecore.Kernel at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName) at Sitecore.Diagnostics.Log.Warn(String message, Object owner) at Sitecore.WFFM.Core.Extensions.Warn.IsNull(Object obj, String name) at Sitecore.WFFM.Analytics.AnalyticsTracker.RegisterFormDropouts() at (Object , Object[] ) at Sitecore.Pipelines.PipelineMethod.Invoke(Object[] parameters) at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args, String pipelineDomain) at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args) at Sitecore.Pipelines.EndSession.SessionEndPipeline.Run(SessionEndArgs sessionEndArgs) at Sitecore.Web.Application.RaiseSessionEndEvent(HttpApplication context)
There is already one blog post on this topic on Internet Code snippet from the blog as below: Add-ItemLanguage -Path "master:\sitecore\content" -Language "en" -TargetLanguage "de-DE" -IfExist OverwriteLatest -IgnoredFields "" For recursive you can try below PowerShell script Get-ChildItem /sitecore/content/home -Recurse | Where-Object { $_."TemplateName" = "Sample Item" } | ForEach-Object { Add-ItemLanguage $_ -Language "en" -TargetLanguage "de-DE" -IfExist OverwriteLatest -IgnoredFields "" }
Create new language version for content branch Is there a way in Sitecore Powershell Extensions to create new language versions of a branch in the content tree? I need it to copy exactly the presentation details set on the current language to the new language. I've found this article https://www.cognifide.com/our-blogs/sitecore/quickly-create-new-language-versions-on-your-sitecore-cms/ so would like to do the same but with SPE.
It's not so much of a technical difference, as you can see, with a few settings you can get the goal to act just like an event. The difference is more of a conceptual one: Goals Goals are "events" that occur at the end of a key user journey. They offer meaningful insight into how well your site is doing: Examples: Completing a booking form Registering for the site Requesting a brochure Signing up to the mailing list Page Events Page events could for absolutely anything you want to track that doesn't necessarily mean a "successful goal" state was reached. Conceptually these are likely less important but also meaningful to track. They are called Page Events as often they related to something the user carried out whilst on the page. Examples: A search returned no results The user expanded an accordion option The user canceled the registration dialog
When would you use a Page Event? In Experience Marketing terms we have something called a Page Event. Sitecore's documentation explain a Page Event like as such: Events track visitor activity on a website. Tracking events helps build up a more complete picture of a visitor’s behavior as they navigate your website. You should assign engagement value points to all events to reflect their relative importance to your organization. Aside from a Page Event we also have a Goal: Goals are activities that visitors can perform on your website. You create goals to track and measure how visitors engage with the website and campaigns – both online and offline. Looking at the Goal template in Sitecore I noticed two sections - Options and Experience Profile Options, with two interesting fields: When you create a Goal, uncheck Is Goal and check Show in Events, the Goal behaves just like a Page Event (correct me if I'm wrong here). So when and why would you ever use a Page Event? Both Page Events and Goals get an engagement value assigned, both can be assigned to items (pages) and even if you specifically want a Page Event to be tracked you can still use a Goal that is configured to act like a Page Event.
When is the decay rate actually applied to the Contact Behaviour Profile? Daily, weekly, monthly? According to martin miles, and martin davies it is per interaction. Is that configurable somewhere? Martin Miles PDF presentation says at a given rate, which can be specified using the rules engine. I'll update answer as to how this works, when I get a chance. A visitor’s behavior profile from their previous visit can now influence personalization rules in their current and future visit. Behavior Profiling are now stored both on the Interaction and Contact. Behavior Profile on the Contact can decay at a given rate per interaction. Source: Martin Mile Presentation PDF (page 17) Profiles items now have a "Decay Rate" field which specifies the percentage by which a contact's profile score should decrease at the start of each interaction. Source: Martin Davies Blog Post
What does a profile's Decay Rate actually do? Profiles have a Decay rate field. The Sitecore documentation explains it as: ...you can control how long an individual profile or pattern card is relevant to the Contact Behavior Profile by setting the decay rate. The decay rate is a percentage that expresses how relevant the profile will remain over time. But that is not clear enough for me. When is the decay rate actually applied to the Contact Behaviour Profile? Daily, weekly, monthly? Or is that configurable somewhere?
The minimal out of the box sitecore role that gives you such capabilities(considering no overrides were done) is sitecore\Sitecore Client Designing If you need to assign a role to your own custom role you can give read access over the buttons chunk beneath /sitecore/content/Applications/WebEdit/Ribbons/Chunks/Layout Modes And the the actual tab sections are located beneath /sitecore/content/Applications/WebEdit/Ribbons/WebEdit/Advanced/Layout where you should assign read permissions if they are not already assigned.
Where is shared and final layout in the security Editor I want to let the editors change between shared layout and final layout in the Experience Editor, but currently, they can't view that option without adding a new role to them. How can I grant access to that part using the security editor? Edit: Sitecore 8.1, they have a custom version of Sitecore Client Authoring.
After currently executing "line of code" will finish its job then script execution will be immediately suspended once you click Abort. So you don't have to control execution by your own. What is currently running must finish its work (single instruction, let's say Write-host 'test', this cannot be interrupted anywhere between). This is more or less the answer that I got from Adam for the same question I asked him some time ago. To proof that theory you can check how this script works: Write-Log "Start!!!" Start-Sleep 5 Write-Log "End!!!" Results without stopping ISE ManagedPoolThread #4 16:48:50 INFO Executing a script in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session'. ManagedPoolThread #4 16:48:50 INFO Start!!! ManagedPoolThread #4 16:48:55 INFO End!!! ManagedPoolThread #4 16:48:55 INFO The script execution in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session' completed in 5002 ms. Results with Abort buttong clicked ManagedPoolThread #15 16:48:58 INFO Executing a script in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session'. ManagedPoolThread #15 16:48:58 INFO Start!!! 21564 16:48:58 INFO Aborting script execution in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session'. ManagedPoolThread #15 16:48:58 INFO The script execution in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session' completed in 716 ms. EDIT: Working with pipes. Question: So if my script starts off with a big Get-ChildItem and pipes that to a custom function, there is no way to stop it until that pipeline is complete? Short answer is: you still don't have to do anything additionally. Script will be suspended after the last instruction is executed. Let's take a look on this example. function Check-Item($i){ Write-Log "Checking item: $($i.ID)" Start-Sleep 1 $i } Write-Log "Start!!!" gci -path "/sitecore/templates/branches" -r | ? { $_.Name.Length -gt 0 } | ? { $_."__Long description" -ne $null } | ? { Check-Item $_ } | % { Write-Log $_.Name } Write-Log "End!!!" Notice logs: 18608 17:17:19 INFO The script execution in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session' completed in 3 ms. ManagedPoolThread #11 17:17:19 INFO Executing a script in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session'. ManagedPoolThread #11 17:17:19 INFO Start!!! ManagedPoolThread #11 17:17:19 INFO Checking item: {C93C0945-607B-4916-B8D9-FE9F9BA783CA} ManagedPoolThread #11 17:17:20 INFO System ManagedPoolThread #11 17:17:20 INFO Checking item: {3E635C68-A2AA-47CD-A297-7DA9B05D56FE} ManagedPoolThread #11 17:17:21 INFO Analytics ManagedPoolThread #11 17:17:21 INFO Checking item: {07624A03-BB2F-45D8-ABE1-15E2B1705FF3} ManagedPoolThread #11 17:17:22 INFO Profile ManagedPoolThread #11 17:17:22 INFO Checking item: {67759D75-62E4-4945-8199-913BBECD1879} ManagedPoolThread #11 17:17:23 INFO $name ManagedPoolThread #11 17:17:23 INFO Checking item: {8F66D1E0-DEBA-4D68-8713-DD982C1ABDE4} ManagedPoolThread #11 17:17:24 INFO Profile Cards ManagedPoolThread #11 17:17:24 INFO Checking item: {D7192472-9456-4B1A-AE1C-6A904200E561} 20708 17:17:25 INFO Aborting script execution in ScriptSession '$scriptSession$|qz15dry1es3umdudogfjfe0d|ISE Editing Session'. Later you will also see error: ManagedPoolThread #5 17:04:34 ERROR Error while executing GetChildItems(string path='master:/sitecore/templates', string recurse='True') Exception: System.Management.Automation.PipelineStoppedException Message: The pipeline has been stopped. But it is handled in code, just logged.
PowerShell ISE: Function of Abort button? I have noticed that clicking the Abort button in the PowerShell ISE doesn't actually cause the background job to terminate. I guess I shouldn't be surprised since arbitrarily terminating a thread that is running unknown code could cause some pretty big problems. However, it got me wondering... Does the abort command set some kind of flag that I could check in my script to make it support aborting cleanly? Or is there some other way to make my scripts support the abort command?
Because Sitecore supports server-side responsive rendering, it's very easy to use the Device feature of the CMS to support AMP. AMP Layout (using Razor) This example is adapted from Google's example markup and Razorified: <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>Hello, AMPs</title> <link rel="canonical" href="@LinkManager.GetItemUrl(RenderingContext.Current.ContextItem)" /> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <script type="application/ld+json"> { "@@context": "http://schema.org", "@@type": "NewsArticle", "headline": "Open-source framework for publishing content", "datePublished": "2015-10-07T12:02:41Z", "image": [ "logo.jpg" ] } </script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> </head> <body> <h1>@Html.Sitecore().Field("Your Title Field Name")</h1> @Html.Raw(GoogleAmpConverter.Convert(RenderingContext.Current.ContextItem["ContentFieldName"])) </body> </html> Note the canonical tag that links back to the Default Device for the context Item. Also note that I'm assuming the field you want to render for body copy is also attached to the context Item. Your needs may be different. Some folks may want to have a very limited Rich Text field just for AMP output, others may want to try to re-use as much of their current content as possible, which is why we have the next section... Rich Text Conversion Assuming the page you're trying to AMP-ify is a fairly basic content page, we want to take the normal Rich Text field that represents the content of the page, and strip it of anything that AMP doesn't like. With HtmlAgilityPack and a little patience, you can use a class like the one below to clean up your normal Rich Text field for AMP: public class GoogleAmpConverter { private readonly string source; public GoogleAmpConverter(string source) { this.source = source; } public static string Convert(string source) { var converter = new GoogleAmpConverter(source); return converter.Convert(); } public string Convert() { var result = ReplaceIframeWithLink(source); result = StripInlineStyles(result); result = ReplaceEmbedWithLink(result); result = UpdateAmpImages(result); return result; } private string ReplaceIframeWithLink(string current) { // Uses HtmlAgilityPack (install-package HtmlAgilityPack) var doc = GetHtmlDocument(current); var elements = doc.DocumentNode.Descendants("iframe"); foreach (var htmlNode in elements) { if (htmlNode.Attributes["src"] == null) { continue; } var link = htmlNode.Attributes["src"].Value; var paragraph = doc.CreateElement("p"); var text = link; // TODO: This might need to be expanded in the future var anchor = doc.CreateElement("a"); anchor.InnerHtml = text; anchor.Attributes.Add("href", link); anchor.Attributes.Add("title", text); paragraph.InnerHtml = anchor.OuterHtml; var original = htmlNode.OuterHtml; var replacement = paragraph.OuterHtml; current = current.Replace(original, replacement); } return current; } private string StripInlineStyles(string current) { // Uses HtmlAgilityPack (install-package HtmlAgilityPack) var doc = GetHtmlDocument(current); var elements = doc.DocumentNode.Descendants(); foreach (var htmlNode in elements) { if (htmlNode.Attributes["style"] == null) { continue; } htmlNode.Attributes.Remove(htmlNode.Attributes["style"]); } var builder = new StringBuilder(); var writer = new StringWriter(builder); doc.Save(writer); return builder.ToString(); } private string ReplaceEmbedWithLink(string current) { // Uses HtmlAgilityPack (install-package HtmlAgilityPack) var doc = GetHtmlDocument(current); var elements = doc.DocumentNode.Descendants("embed"); foreach (var htmlNode in elements) { if (htmlNode.Attributes["src"] == null) continue; var link = htmlNode.Attributes["src"].Value; var paragraph = doc.CreateElement("p"); var anchor = doc.CreateElement("a"); anchor.InnerHtml = link; anchor.Attributes.Add("href", link); anchor.Attributes.Add("title", link); paragraph.InnerHtml = anchor.OuterHtml; var original = htmlNode.OuterHtml; var replacement = paragraph.OuterHtml; current = current.Replace(original, replacement); } return current; } private string UpdateAmpImages(string current) { // Uses HtmlAgilityPack (install-package HtmlAgilityPack) var doc = GetHtmlDocument(current); var imageList = doc.DocumentNode.Descendants("img"); const string ampImage = "amp-img"; if (!imageList.Any()) { return current; } if (!HtmlNode.ElementsFlags.ContainsKey("amp-img")) { HtmlNode.ElementsFlags.Add("amp-img", HtmlElementFlag.Closed); } foreach (var imgTag in imageList) { var original = imgTag.OuterHtml; var replacement = imgTag.Clone(); replacement.Name = ampImage; replacement.Attributes.Remove("caption"); current = current.Replace(original, replacement.OuterHtml); } return current; } private HtmlDocument GetHtmlDocument(string htmlContent) { var doc = new HtmlDocument { OptionOutputAsXml = true, OptionDefaultStreamEncoding = Encoding.UTF8 }; doc.LoadHtml(htmlContent); return doc; } } Disclaimer: This isn't heavily tested, but addresses the main AMP vs. HTML issues you're likely to encounter. Differentiating your AMP page output from your normal page output This is a two-step process. 1: Configure a Sitecore Layout Device for AMP Create a new Device and establish a querystring parameter for switching to this device mode: You could also probably get fancy and use agent detection, but I don't think there's a dedicated AMP agent, so it's important to have a way to explicitly differentiate between your default output and your AMP output. Querystrings are your friend. 2: Create a meta tag in your Default Device Layout that references your AMP Device layout for the context Item. <link rel="amphtml" href="@LinkManager.GetItemUrl(RenderingContext.Current.ContextItem)?google=amp"> Profit! Keep in mind that although you could AMP-ify your entire website, it's only supposed to be for newsy-article kind of stuff. Don't expect to be able to include tons of anciliary content, cross-sells or calls to action. This is mostly about goodwill content for mobile users.
How do I implement Accelerated Mobile Pages (AMP) with Sitecore? This is just a general question. Has anyone implemented AMP with Sitecore before? Is it possible, how difficult and could you point me in the direction of documentation?
Disclaimer: This Ain't Pretty -- But It Works So after many hours of my nighttime and sleep chewing over this question, I have finally figured out the path. I will warn you, it's not easy. First let's discuss environment. I'm using Sitecore 8.1 - Update 3. For the most part this is a vanilla install. Second, there are two sides to Sitecore: Content Editor and Experience Editor. They are not the same, though they LOOK like they are. They use different controls but to the everyday developer, it looks like they share the same Field Type. Step 1 - Follow Akshay's Blog Provided In Question In following Akshay's Blog, I was able to get the Content Editor side working, with minimal issues. There were some changes I had to make, so I will list those here: TelephoneLink.cs using System.Collections.Specialized; using Sitecore; using Sitecore.Diagnostics; using Sitecore.Shell.Applications.ContentEditor; using Sitecore.Text; using Sitecore.Web.UI.Sheer; namespace SitecoreHacker.Sandbox.Controls { public class TelephoneLink : Link { public TelephoneLink() { Class = "scContentControl"; Activation = true; } // Handles the message. public override void HandleMessage(Message message) { Assert.ArgumentNotNull(message, "message"); base.HandleMessage(message); //base handles other message requests if (message["id"] != ID) return; switch (message.Name) { case "contentlink:telephonelink": { var url = new UrlString(UIUtil.GetUri("control:TelephoneLinkForm")); Insert(url.ToString(), new NameValueCollection { { "height", "425" } }); break; } default: { return; } } } } } TelephoneLinkForm.cs using System; using System.Text.RegularExpressions; using Sitecore; using Sitecore.Diagnostics; using Sitecore.Shell.Applications.Dialogs; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.Sheer; using Sitecore.Xml; namespace SitecoreHacker.Sandbox.Controls.Dialogs.TelephoneLink { public class TelephoneLinkForm : LinkForm { protected Edit Class; protected Edit Text; protected Edit Title; protected Edit Url; private string GetTelephone() { var value = Url.Value; var str = value; if (str.Length > 0) { if (str.IndexOf(":", StringComparison.InvariantCulture) >= 0) { str = str.Substring(str.IndexOf(":", StringComparison.InvariantCulture) + 1); } if (!new Regex(@"^(?:\(?)(?<AreaCode>\d{3})(?:[\).\s]?)(?<Prefix>\d{3})(?:[-\.\s]?)(?<Suffix>\d{4})(?!\d)", RegexOptions.IgnoreCase).IsMatch(str)) { return "__Canceled"; } } if (value.Length > 0 &amp;&amp; value.IndexOf(":", StringComparison.InvariantCulture) < 0) { value = string.Concat("tel:", value); } return value; } protected override void OnLoad(EventArgs e) { Assert.ArgumentNotNull(e, "e"); base.OnLoad(e); if (Context.ClientPage.IsEvent) { return; } var item = LinkAttributes["url"]; if (LinkType != "tel") { item = string.Empty; } Text.Value = LinkAttributes["text"]; Url.Value = item.Replace("tel:", ""); Class.Value = LinkAttributes["class"]; Title.Value = LinkAttributes["title"]; } protected override void OnOK(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); var tel = GetTelephone(); if (tel == "__Canceled") { SheerResponse.Alert("The telephone number is invalid."); return; } var packet = new Packet("link"); SetAttribute(packet, "text", Text); SetAttribute(packet, "linktype", "tel"); SetAttribute(packet, "url", tel); SetAttribute(packet, "anchor", string.Empty); SetAttribute(packet, "title", Title); SetAttribute(packet, "class", Class); SheerResponse.SetDialogValue(packet.OuterXml); base.OnOK(sender, args); } } } Step 2 - Change WebEdit Link In Core Find the General Link Field Type and Change the Click to webedit:edittelephonelink Responsible Disclosure Before going further, a note about responsible disclosure. I am aware of my responsibilities as a developer and divulging large amounts of decompiled code on the internet. Therefore, the following code snippets for the rest of this answer have been redacted. THEY WILL NOT COMPILE without first decompiling the original classes and making the changes that I specify. If you need assistance, please contact me directly. Step 3 - Create TelephoneEditLink.cs This is the beginning of the not so pretty. The fact of the matter is I only need to CHANGE one line from the original EditLink class from Sitecore. However, override this class cleanly proved to be a near impossible. So I took the easiest way I knew how. Cut and Paste. Original Class: Sitecore.Shell.Applications.WebEdit.Commands.EditLink namespace SitecoreHacker.Sandbox.Commands { [Serializable] public class TelephoneEditLink : WebEditLinkCommand { public override void Execute(CommandContext context) { ... snip ... } protected static void Run(ClientPipelineArgs args) { ... snip ... if (args.IsPostBack) { ... snip ... } else { var urlString = new UrlString(Context.Site.XmlControlPage); urlString["xmlcontrol"] = "SpeakTelephoneLink"; //THIS IS THE ONE LINE THAT I NEEDED TO CHANGE var urlHandle = new UrlHandle(); urlHandle["va"] = new XmlValue(args.Parameters["fieldValue"], "link").ToString(); urlHandle.Add(urlString); urlString.Append("ro", field.Source); Context.ClientPage.ClientResponse.ShowModalDialog(urlString.ToString(), "550", "650", string.Empty, true); args.WaitForPostBack(); } } private static RenderFieldResult RenderLink(ClientPipelineArgs args) { ... snip ... } } } That ONE LINE that we needed to change introduces a NEW Speak Xml Control called SpeakTelephoneLink which is a direct port of the GeneralLink SPEAK Xml Control. Step 4 - Patch In TelephoneEditLink.cs <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <commands> <command name="webedit:edittelephonelink" type="SitecoreHacker.Sandbox.Commands.TelephoneEditLink, SitecoreHacker.Sandbox" /> </commands> </sitecore> </configuration> Step 5 - Create the SpeakTelephoneLink.xml File Original File: /sitecore/shell/Applications/Dialogs/GeneralLink/GeneralLink.xml You will want to save this file somewhere under /sitecore/shell/Applications. For the purposes of this answer, I am using /sitecore/shell/Applications/Dialogs/SpeakTelephoneLink/ <?xml version="1.0" encoding="utf-8" ?> <control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense"> <SpeakTelephoneLink> <Stylesheet Src="/sitecore/shell/Applications/Dialogs/GeneralLink/GeneralLink.css"></Stylesheet> <Script Src="/sitecore/shell/Applications/Dialogs/GeneralLink/GeneralLink.js"></Script> <FormDialog Icon="Network/32x32/link.png" Header="Insert a link" Text="Select the link type and specify the appropriate properties." OKButton="OK"> <CodeBeside Type="SitecoreHacker.Sandbox.Controls.Dialogs.SpeakTelephoneLink.SpeakTelephoneLinkForm,SitecoreHacker.Sandbox"/> <DataContext ID="InternalLinkDataContext" ViewName="Master"/> <DataContext ID="MediaLinkDataContext" Root="{3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1}"/> <GridPanel Height="100%" Width="100%" VAlign="top" Fixed="true" Columns="3"> <!--Left column--> <Border ID="Modes" Height="100%" Class="left-column" Width="100%" GridPanel.Height="100%" GridPanel.Width="120px"> <!--Internal link--> <Border ID="Internal" onclick="javascript:return scForm.invoke('OnModeChange','internal')" Class="selected"> <a href="#" class="mode" onfocus="this.blur()"> <ThemedImage Class="mode-icon" Src="Network/32x32/link.png" /> <div class="mode-text"> <Literal Text="Internal Link"/> </div> </a> </Border> <!--Media link--> ... snip ... <!--External link--> ... snip ... <!--Telepehone link--> <Border ID="Telephone"> <a href="#" class="mode" onclick="javascript:return scForm.invoke('OnModeChange','tel')" onfocus="this.blur()"> <ThemedImage Class="mode-icon" Src="Network/32x32/earth.png?overlay=NetworkV2/16x16/link.png" /> <div class="mode-text"> <Literal Text="Telephone Link"/> </div> </a> </Border> <!--Anchor link--> ... snip ... <!--Mail link--> ... snip ... <!--Javascript link--> ... snip ... <!--Center column--> <Space GridPanel.Width="8px" /> <!--Right column--> <Border Class="right-column" Height="100%" GridPanel.Width="100%" GridPanel.Height="100%"> <GridPanel Width="100%" Height="100%" ID="MainGrid"> <Border Class="section-header" GridPanel.VAlign="top"> <Literal ID="SectionHeader" Text="Select the item that you want to create a link to and specify the appropriate properties." /> </Border> ... snip ... <Literal Text="Telephone Number:" GridPanel.NoWrap="true"/> <Edit Width="100%" Class="scQuirksBoxModel" GridPanel.Row.ID="LinkTelephoneRow" ID="LinkTelephone"/> ... snip ... </GridPanel> </GridPanel> </Border> </GridPanel> <Button Header="Upload" ID="UploadMedia" def:placeholder="Buttons" Click="UploadImage"/> </FormDialog> </SpeakTelephoneLink> </control> Note the <SpeakTelephoneLink> that wraps this. This was changed from <GeneralLink>. Also note the <CodeBeside>. Step 6 - Create the Code Beside: SpeakTelephoneLinkForm.cs Original Class: Sitecore.Shell.Applications.Dialogs.GeneralLink.GeneralLinkForm namespace SitecoreHacker.Sandbox.Controls.Dialogs.SpeakTelephoneLink { public class SpeakTelephoneLinkForm : LinkForm { ... snip ... protected Edit LinkTelephone; private string CurrentMode { ... snip ... } ... snip ... protected override void OnOK(object sender, EventArgs args) { Assert.ArgumentNotNull(sender, "sender"); Assert.ArgumentNotNull(args, "args"); var packet = new Packet("link"); SetCommonAttributes(packet); bool flag; switch (CurrentMode) { case "internal": flag = SetInternalLinkAttributes(packet); break; case "media": flag = SetMediaLinkAttributes(packet); break; case "external": flag = SetExternalLinkAttributes(packet); break; case "tel": flag = SetTelephoneLinkAttributes(packet); break; case "mailto": flag = SetMailToLinkAttributes(packet); break; case "anchor": flag = SetAnchorLinkAttributes(packet); break; case "javascript": flag = SetJavascriptLinkAttributes(packet); break; default: throw new ArgumentException("Unsupported mode: " + CurrentMode); } if (!flag) return; SheerResponse.SetDialogValue(packet.OuterXml); base.OnOK(sender, args); } ... snip ... private string GetTelephone() { var value = LinkTelephone.Value; var str = value; if (str.Length > 0) { if (str.IndexOf(":", StringComparison.InvariantCulture) >= 0) { str = str.Substring(str.IndexOf(":", StringComparison.InvariantCulture) + 1); } if ( !new Regex( @"^(?:\(?)(?<AreaCode>\d{3})(?:[\).\s]?)(?<Prefix>\d{3})(?:[-\.\s]?)(?<Suffix>\d{4})(?!\d)", RegexOptions.IgnoreCase).IsMatch(str)) { return "__Canceled"; } } if (value.Length > 0 &amp;&amp; value.IndexOf(":", StringComparison.InvariantCulture) < 0) { value = string.Concat("tel:", value); } return value; } private bool SetTelephoneLinkAttributes(Packet packet) { Assert.ArgumentNotNull(packet, "packet"); var tel = GetTelephone(); if (tel == "__Canceled") { SheerResponse.Alert("The telephone number is invalid."); return false; } SetAttribute(packet, "url", tel); SetAttribute(packet, "text", Text); SetAttribute(packet, "title", Title); SetAttribute(packet, "class", Class); return true; } private void SetTelephoneLinkControls() { if (LinkType == "tel" &amp;&amp; string.IsNullOrEmpty(Url.Value)) LinkTelephone.Value = LinkAttributes["url"].Replace("tel:",""); ShowContainingRow(LinkTelephone); SectionHeader.Text = Translate.Text("Specify the Telephone, e.g. 800-555-1212"); } ... snip ... /// <summary>The set mode specific controls.</summary> /// <exception cref="T:System.ArgumentException"> /// </exception> private void SetModeSpecificControls() { HideContainingRow(TreeviewContainer); MediaPreview.Visible = false; UploadMedia.Visible = false; HideContainingRow(UrlContainer); HideContainingRow(Querystring); HideContainingRow(MailToContainer); HideContainingRow(LinkAnchor); HideContainingRow(JavascriptCode); HideContainingRow(Target); HideContainingRow(CustomTarget); switch (CurrentMode) { case "internal": SetInternalLinkContols(); break; case "media": SetMediaLinkControls(); break; case "external": SetExternalLinkControls(); break; case "tel": SetTelephoneLinkControls(); break; case "mailto": SetMailLinkControls(); break; case "anchor": SetAnchorLinkControls(); break; case "javascript": SetJavaScriptLinkControls(); break; default: throw new ArgumentException("Unsupported mode: " + CurrentMode); } foreach (Border control in Modes.Controls) { if (control != null) control.Class = control.ID.ToLowerInvariant() == CurrentMode ? "selected" : string.Empty; } } } } Step 7 - Compile and Deploy If all things work out, you'll see the Telephone Link option.
Adding a telephone link (href=tel:) to the general link field type I want to have fields that are rendered as telephone links, e.g. <a href="tel:12345678">. Can I do this by modifying the standard field type, or by creating a new field type? I have tried using an external link and setting the URL to tel:12345646 in the raw values, but it renders as http://tel:12345646. There is a blog post by Akshay Sura on how to do it: https://www.akshaysura.com/2015/02/22/add-telephone-link-to-the-general-link-field-type-in-sitecore/ But it doesn't work for me on Sitecore 8. It seems to work fine in the Content Editor, but breaks in the Experience Editor.
I know this is late, but here are the undocumented properties for the Admin Service secure installation: ADMIN_SERVICE_CES_SERVER_NAME This is used for the certificate Common Name ADMIN_SERVICE_PORT Port for the secured Admin Service. The dialog will set it to 443 in an attended installation ADMIN_SERVICE_CERTIFICATE_EXPORT_PATH Local path where the certificate will be created ADMIN_SERVICE_PRIVATE_KEY_PASSWORD The password that will be used to secure the certificate's private key. Can be an empty string
Coveo for Sitecore CES silent install fails cert generation Putting this question to the Sitecore crowd as it relates to the overall Coveo for Sitecore install, specifically the installation of Coveo Enterprise Search (CES). I'm trying to automate the installation of Coveo CES server using the MSI bundled in the EXE provided, as outlined here. Installing the EXE manually works, using all of the default options except for enabling the Admin Service, providing the relevant domains, credentials etc, and the admin service certificate is generated successfully. My issue is that when the same configuration is installed silently via command line, the product and services get installed correctly, but the install fails during creation of the admin certificate. It appears there is no parameter available to specify the path for the admin certificate generation, but I'm not sure if this is the core issue. Is there an additional parameter that is missing from the documentation? Or is there another workaround available to get this to work? Here is the installation command I'm trying to execute: "Coveo Enterprise Search 7.0 x64 (8388).msi" /qn /l* ces.log ADDLOCAL=BaseFeature,VCRedist,CESService,Admin,AdminService,CESConsole ISSITECORE=Yes INSTALLLOCATION=C:\cestest LOGONTYPE=account LOGONACCOUNT_DOMAIN=domain LOGONACCOUNT_USERNAME=coveo LOGONACCOUNT_PASSWORD=xxxxxx USE_ADMIN_SERVICE_SECURITY=Yes ADMINSERVICELOGON_USERNAME=coveoservice ADMINSERVICELOGON_PASSWORD=xxxxxx SKIP_SERVICES_CHECK=Yes Here are the relevant lines out of the installation log: Action started 12:48:00: CreateShortcuts. Action ended 12:48:00: CreateShortcuts. Return value 1. Action started 12:48:00: CA_CreateCertificateForAdminService. SFXCA: Extracting custom action to temporary directory: C:\WINDOWS\Installer\MSI30DA.tmp-\ SFXCA: Binding to CLR version v2.0.50727 Calling custom action ManagedInstallerLib!ManagedInstallerLib.AdminServiceSecurity.CreateCertificateForAdminService Generate the self signed certificate. Import the certificate into the stores. Bind the certificate. Exception while securing the Admin Service... An exception has occurred at source : mscorlib System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer&amp; number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at ManagedInstallerLib.AdminServiceSecurity.CreateCertificate(Session p_Session) Done securing the Admin Service... Action ended 12:48:12: CA_CreateCertificateForAdminService. Return value 1. Action started 12:48:12: WriteRegistryValues. Action ended 12:48:12: WriteRegistryValues. Return value 1. Any pointers would be appreciated!
Hetal, I am just going to add it as an answer for potential users to benefit from. It could be one of the following: Glass not being installed/configured properly (Glass DLL's or configs missing or are of previous versions) The Datasource item is not published (mentioned by Marek) In your case it was Glass not properly installed in the Models project. Thanks.
Glass Cast issues after upgrading from Sitecore 7.2 to 8.2 So, I upgraded a Sitecore solution from 7.2 to 8.2. All works well, except for the site. I keep on getting the error in my views like the one below: The model item passed into the dictionary is of type 'Sitecore.Mvc.Presentation.RenderingModel', but this dictionary requires a model item of type 'Web.ViewModels.XXXViewModel'. I did update all my Glass Cast references to sitecoreService.Cast<>(). But still no luck. Did anyone run into this issue? We are using Glass Mapper (Version 4.2.1.188).
We are using Zookeeper with Sitecore 8.1 Update 2, and as per the documentation here: https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html we are using 3 instances. This is the minimum required. Three ZooKeeper servers is the minimum recommended size for an ensemble, and we also recommend that they run on separate machines. This works really well for us and ensures no downtime when indexes are being rebuilt. This is an excellent blog post that we followed to set this up: http://www.chrissulham.com/sitecore-on-solr-cloud-part-2/ A note of caution though as pointed out by Grant Killian in the comments below: Note: SolrCloud setups are under experimental support starting from Sitecore XP 8.2, meaning some issues are possible. In case of related issues, Sitecore Support will help with troubleshooting, while there is no guarantee that a fix will be available. In earlier versions of Sitecore CMS/XP only standalone Solr setups are supported. more info here: kb.sitecore.net/articles/227897 We carried out the following process to install this on our 3 Solr Search Servers in Production: Download Solr 5.2.1 (i'd recommend Solr 5.1 though as Sitecore support will help with issues for Sc 8.2: kb.sitecore.net/articles/227897) Prepare Solr configuration for Sitecore Indexes - Steps 1, 2, 3 and 4. Configuring ZooKeeper ensemble - Steps 1-5 Configuring SolrCloud with ZooKeeper ensemble - All Steps Upload index configuration into ZooKeeper - All Steps Create collections Here are some commands you might find useful: Registering Config: zkcli -zkhost localhost:2181 -cmd upconfig -confdir D:\Solr\server\solr\configsets\sitecore_configs\conf -confname scbasic Creating a Collection: solr create -c sitecore -d D:\Solr\server\solr\configsets\sitecore_configs -n scbasic -shards 1 -replicationFactor 1 -p 8983 Add replica to collection: http://localhost:8983/solr/admin/collections?action=ADDREPLICA&amp;collection=sitecore&amp;shard=shard1&amp;node=172.16.128.32:8983_solr Remove replica from collection: http://localhost:8983/solr/admin/collections?action=DELETEREPLICA&amp;collection=collection1&amp;shard=shard1&amp;replica=core_node1 I wrote some PowerShell scripts to do most of the above for me so I could run them on Staging and Production and I found this easier than calling the API manually. The script loops round an array of the sitecore index names. The Core is created on one of the Solr Servers and then 2 replica cores are created on the other two Solr servers. $SitecoreIndexNames = @('sitecore_core_index', 'sitecore_master_index', 'sitecore_web_index', 'sitecore_analytics_index', 'sitecore_marketing_asset_index_master', 'sitecore_marketing_asset_index_web', 'sitecore_marketingdefinitions_master', 'sitecore_marketingdefinitions_web', 'sitecore_testing_index', 'sitecore_suggested_test_index', 'sitecore_fxm_master_index', 'sitecore_fxm_web_index', 'sitecore_list_index', 'social_messages_master', 'social_messages_web') Here are the key functions: function Create-SolrCore($solrBaseUrl, $coreName, $configSet, $solrCollectionName, $solrConfigSetName) { $restUrl = "{0}/admin/collections?action=CREATE&amp;name={1}&amp;property.name={1}&amp;collection={1}&amp;collection.configName={3}&amp;numShards=1&amp;shard=shard1" -f $solrBaseUrl, $coreName, $solrCollectionName, $solrConfigSetName Write-Host "adding core: $restUrl" $result1 = Invoke-WebRequest $restUrl -Method GET -UseBasicParsing Write-Host "Created Solr core $coreName." } function Create-Replica($solrBaseUrl, $coreName, $configSet, $solrCollectionName, $solrConfigSetName, $replicataIP) { $restReplicaUrl = "{0}/admin/collections?action=ADDREPLICA&amp;collection={1}&amp;property.name={1}&amp;numShards=1&amp;shard=shard1&amp;node={2}" -f $solrBaseUrl, $coreName, $replicataIP Write-Host "adding replica: $restReplicaUrl" $result2 = Invoke-WebRequest $restReplicaUrl -Method GET -UseBasicParsing Write-Host "Created replica for $SolrCollectionName." } function Create-Replicas($indexNames, $nonSwitchOnRebuildIndexNames, $coreNamePrefix, $baseUrl) { $SitecoreIndexNames | % { $index = Convert-SitecoreIndexNameToCoreName($_) try { Create-Replica $SolrBaseUrl $index $SolrConfigSetName $SolrCollectionName $SolrConfigSetName $ReplicataIP } catch { Write-Warning "Unable to add replica for core $index. $_" } } } function Create-SolrCores($indexNames, $nonSwitchOnRebuildIndexNames, $coreNamePrefix, $baseUrl) { $SitecoreIndexNames | % { $index = Convert-SitecoreIndexNameToCoreName($_) try { Create-SolrCore $SolrBaseUrl $index $SolrConfigSetName $SolrCollectionName $SolrConfigSetName } catch { Write-Warning "Unable to create core for $index index. This probably means it already exists. $_" } } } I based these on Kam's Solr Cannon Scripts: http://kamsar.net/index.php/2016/03/The-Solr-Cannon/ Once you have done this you can point Sitecore at the Solr ensemble like so: <?xml version="1.0" encoding="utf-8"?> <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <settings> <setting name="ContentSearch.Solr.ServiceBaseAddress"> <patch:attribute name="value">http://{ipofinstance}:8983/solr</patch:attribute> </setting> </settings> </sitecore> </configuration>
Sitecore Content deliveries and Solr with High availability I'm trying to find a recommendation from Sitecore in terms of configuring Solr for high availability and how to use it properly with Sitecore. Does anybody know where I can find it? If not, I'm considering these options, any preference or alternative? Master-Slave: Is it still "valid" or is it deprecated since SolrCloud? In this case, How should I configure Sitecore on each role to use one server for indexing, and another (load balanced servers) for querying? Zookeeper: How many instances do I really need? I understand (based on this) that I need 3 Zookeepers minimum to keep the cluster running if one goes down, but apparently they should not be on the same machine as the actual Solr instances meaning I need 5 instances (3 ZK and 2 Solr). And again, Or should I configure Sitecore to use the cluster properly?
Technical details Starting from Sitecore 7.2, there is an option to publish an item with "Publish related items" checked. If you do that, the <getItemReferences> pipeline (defined in Sitecore.config) will be executed to get additional items that are then added to the publishing queue. By default, it returns the following items related to the item being published: The item's clones (by the AddItemCloneReferences processor); The media used by the item (by processors AddFileDropAreaMediaReferences and AddItemLinkReferences); All items the published item links to (by the AddItemLinkReferences processor). The item's aliases (by the AddItemAliasReferences processor). If you wish, you can extend this pipeline by adding your custom "related items" logic as a new processor. Link database The link database needs to be up-to-date in order for this feature to work correctly. So if you have problems with publishing related items, try to rebuild the links DB. Items specified as the data source of a rendering component will also be treated as "related". This is possible because they are also stored in the link database (at least, in the latest versions of Sitecore). Keep in mind that the link database will only contain data source items that are specified directly (e.g. using a path or an item ID). Query-based data sources will not update the link database, and hence, such items will not be published using "Publish related items". Feature usage As an example, this feature may be useful when you are publishing a new page, and you want to make sure that all resources used by that page are also published. Publishing related items is only available during an item-level publish, and not during a site-level publish. Important caveat Related items of related items will not be published. This may cause some confusion—see this question for an example. When you publish both the subitems and the related items, then all related items of all subitems will also be published. This may significantly increase the amount of items added to the publishing queue, so be mindful of this behavior. Further reading https://community.sitecore.net/technical_blogs/b/latest_technical_reinnovations/posts/related-item-publishing-updated https://doc.sitecore.net/sitecore_experience_platform/content_authoring/publishing/publish_an_item_to_your_website http://maxslabyak.com/sitecore/publish-related-items-defining-custom-relationships-via-code-sitecore/
What does the "Publish related items" checkbox do in Sitecore? When you publish an item in Sitecore through the Publish item dialog, you are offered several options. You can choose between Smart publish or Republish, you can also choose whether to Publish subitems or not. These options are pretty self-explanatory. However, what exactly does the Publish related items option do?
With MVC 5, you should have the option to add an MVC 5 View Page, like so, Using this option gives you a simple popup to type in a name, then it generates a cshtml file with no scaffolding. @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title></title> </head> <body> <div> </div> </body> </html> Alternately, you can select MVC Partial Page which just generates an empty .cshtml file. MSDN reference: https://www.asp.net/mvc/overview/getting-started/introduction/adding-a-view
Adding Views - VS Adds Scaffolding and NuGets Can people suggest a good way to add views to a project in Visual Studio? The standard MVC way adds scaffolding (Folders named for controllers) and NuGet packages (MVC, Razor, WebPages, etc...) I'm stuck copying existing views and renaming, or adding a text file and adding the .cshtml extension. There must be a way to tell Visual Studio to turn off the scaffolding/NuGet stuff.
About spaces and quotes If there is no space, then field:foo treats foo as a string value. You could write field:"foo" but you don't have to, since the search term doesn't contain a space. If there is a space included, then quotes are required around the value, otherwise the query won't be parsed correctly: field:"foo bar" About backslashes Backslashes are not stored like this: \\. It's just the escaping syntax that is used both in Solr queries and in the JSON representation in the Solr UI. A backslash should actually always be escaped - see this documentation section: http://lucene.apache.org/core/2_9_4/queryparsersyntax.html#Escaping%20Special%20Characters I think that in case of extranet\DistribA, Sitecore's query generator has a defect that does not escape it. It's probably related to the fact that there are no quotes around the search term. Suggested fix I suggest that you don't store backslashes in the index so as to overcome this defect. Sanitize your role names to remove the backslash—both when storing the custom field and when querying the index.
How to query Solr with spaces and slashes in the filters? I have a Sitecore 8.1 instance using Solr 4.10. I have a custom field in my Solr index called read_roles. It is a list of Sitecore roles that can read a given item. Here is an example of what that looks like in the index when viewed through the Solr UI. "read_roles_sm": [ "extranet\\DistribA", "extranet\\Anonymous Role", "extranet\\Approved Role" ] My first question is this: Are these values really stored with two slashes like that? Or is a slash a special character or something and the Solr UI is adding that in only when it is being displayed on the web page? I have code that adds a security filter to my query that looks like this: public static IQueryable<T> ApplySecurityFilter<T>(this IQueryable<T> query) where T : SearchResultItem { var userRoles = Sitecore.Context.User.Roles.Select(r => r.Name); var readPredicate = PredicateBuilder.False<T>(); readPredicate = userRoles.Aggregate(readPredicate, (current, role) => current.Or(i => i["read_roles"].Equals(role))); var denyPredicate = PredicateBuilder.True<T>(); denyPredicate = userRoles.Aggregate(denyPredicate, (current, role) => current.And(i => !i["denied_roles"].Equals(role))); if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(readPredicate); } if (readPredicate.Body.NodeType != System.Linq.Expressions.ExpressionType.Constant) { query = query.Filter(denyPredicate); } return query; } The idea here is give me all results where at least one of the user's roles is in the read_roles field and none of the user's roles are in the denied_roles field. I seem to be running in to all kinds of problems with slashes and spaces and I don't really understand what is going on here and I don't know how to troubleshoot it. I believe this code works fine as long as the user does not belong to any roles with a space in them. Here is an example. If I am not logged in to the site (anonymous user which belongs to the extranet\Anonymous Role) and I try a search it works properly. I get the results that I would expect. And I see this in the Sitecore Search log file as part of the query that was sent to Solr: &amp;fq=(((-denied_roles_sm:("extranet\\Anonymous Role") AND read_roles_sm:("extranet\\Anonymous Role")) However if I log in as a user that is part of the extranet\DistribA role I do not get the results I would expect and I see this in the Sitecore Search log file: &amp;fq=(((-denied_roles_sm:(extranet\DistribA) AND read_roles_sm:(extranet\DistribA)) What I have noticed is that if the role has a space in it then it seems to put quotes around it and also adds a second slash. But if the role name does not have a space in it then it doesn't do that. I feel like I am not understanding something fundamental about how Solr handles things like spaces and slashes in queries. Any help is greatly appreciated.
It's also important to know that while Mongo is not available, analytic data is being collected. Sitecore will store the data to the file system until such time the collection server comes back online. From Akinori Taira @ Sitecore: In the event that the collections database is unavailable, there is a special ‘Submit Queue’ mechanism that flushes captured data to the local hard drive (the ‘Data\Submit Queue’ folder by default). When the collections database comes back online, a background worker process submits the data from the ‘Submit Queue’ on disk. Sitecore 7.5 and 8 have a key in the Sitecore.Analytics config that can control Sitecore's behavior if Mongo is unreachable for any reason (best I can tell, this has been removed as of 8.1): <setting name="Analytics.FailOnDatabaseErrors" value="false" /> The submit queue is enabled/disabled from the Sitecore.Analytics.Tracking config file's UseSubmitQueue key: <!-- ANALYTICS USE SUBMIT QUEUE Specifies if the submit queue should be used when the contact or session submit operations cannot access the database. If set to true, the contact or session is queued until the database is backed up (see the <submitQueue> section). Default: true --> <setting name="Analytics.UseSubmitQueue" value="true" /> The background task that will flush this to Mongo is configured in the Sitecore.Analytics.Tracking.Database.config's SubmitQueue node: <submitQueue> <backgroundService type="Sitecore.Analytics.SubmitQueueService, Sitecore.Analytics"> <!-- Service wakeup interval in seconds. --> <Interval>60</Interval> </backgroundService> </submitQueue> Other reading/Sources: Sitecore Climber answered this quite well here: https://stackoverflow.com/questions/39153295/in-sitecore-how-to-view-the-content-of-the-submit-queue-file And LonghornTaco's great blog post on this subject: https://citizensitecore.com/2016/07/01/xdb-session-info-and-mongodb-availability/
What happens when MongoDB is down? We are building an infrastructure for xDB internally and our internal network team asked us what would happen if the MongoDB instances were down. We, of course are deploying MongoDB with Replica set but they want to be sure it will not bring down the site. I remember from somewhere that Sitecore will cache the entries locally on the CD instances until the MongoDB comes back online and then once up, it will sync. Is this true?
There is a package directory for the Update Wizard packages at the following path under the site root: \sitecore\admin\Packages
Where do upgrade packages go to when uploaded? When you are upgrading Sitecore you install an upgrade package using the update installation wizard located here: http://yourhost/sitecore/admin/UpdateInstallationWizard.aspx Where does it go to when it gets uploaded? I've looked on the file system but didn't find it. I assume it ends up on the database, if so where?
This answer does not exactly match your question, but I believe it matches your requirements based on the comments you have made. If you want the Item Bucket search features on the parent item but do not want the child items added into sub folders you can easily add those features to the parent item. Make sure that you can view Standard Fields and find the Editors field of the parent item. Then you can add the Search editor to the list and move it to the top so it becomes the default: If you have multiple items based off the same template you can also do this on the Standard Values of the item. Then you have all the search features and can just add child items as normal. Edit: To make the sub items hidden then you can set that on the standard values of the templates of the items you add to the parent: This items will only be visible if the Hidden Items checkbox on the View ribbon is ticked:
Is it possible to create a bucket that doesn't use sub-folder buckets? I have an item that will contain a large number of subitems as direct children, which I would like to give bucketing treatment to. Unfortunately these items don't have a reasonable way to be grouped in subfolders. I've created a custom rule in Item Bucket Settings: Example Rule where the item bucket is based on the [Examples] template and where the new bucketable item is basedon the [Example] template create the new folder structure based on the name of the new bucketable item with [0] levels Choosing 0 levels defaults the bucket path to use the creation date of the item in the default yyyy/MM/dd/HH/mm format. Is there a way to bucket these items without the intermediate folders? I'd prefer that they be accessed at http://example.com/examples/example-name rather than http://example.com/examples/ ... path here ... /example-name, and I'd rather not need to introduce a * item just to correct the paths.
For non-rendered fields, or things that are handled via javascript, etc, I use a combination of Edit Frames and EE views. The EE Views let you present the content in a way that can expose content and fields that might not otherwise be easily accessible and Edit frames let you edit fields that aren't rendered or have complex types.
Is it possible to edit fields in the Page Editor that are shown on hover? I have a menu where the submenu area is shown when you hover over the top menu option. The top option is a link field and the submenu is a rich text area. When I hover over the top option the submenu area is shown, but as I move over it the submenu is hidden again. It looks like I cross a before I get to the menu and thus move off of the part of the page I need. I have tried using a click event on the top level menu to add a class that I can use to show the submenu area. This does work, but removing the class is problematic. If I click anywhere outside of the menu the class should be removed, but not all areas seem to raise the click event. For example, if I click on an editable field somewhere else on the page the submenu stays visible and the edit frame chrome for the field I clicked on becomes visible. Here are some snippets: <nav id="main-nav"> <ul> <asp:Repeater runat="server" ID="repNavigation"> <ItemTemplate> <li class="top-nav"> <sc:Link runat="server" ID="topLink" Field="Link" CssClass="<%# GetTopMenuClass((Item)Container.DataItem) %>" Item="<%# (Item) Container.DataItem %>"> <sc:Text ID="topLinkTitle" runat="server" Field="Menu Title" Item="<%# (Item) Container.DataItem %>"/> <div class="triangle"></div> </sc:Link> <div class="submenu"> <div class="submenu-content"> <sc:Text runat="server" ID="submenuContent" Field="Submenu Content" Item="<%# (Item) Container.DataItem %>"/> </div> </div> </li> </ItemTemplate> </asp:Repeater> </ul> </nav> Prior to this code that attaches a click function to the html tag I tried code that attached something similar to every tag. It was unsuccessful, functioning as described above. Same as the code below. var isEditing = jQuery("body.page-editor"); if (isEditing) { var menuFields = jQuery(".top-nav"); var menuFields = jQuery(".top-nav a span[contenteditable=true]"); menuFields.click(function () { var p = jQuery(this).closest(".top-nav"); if (p.hasClass("show-submenu")) { p.removeClass("show-submenu"); } else { jQuery(".top-nav").removeClass("show-submenu"); p.addClass("show-submenu"); } }); } jQuery('html').click(function () { jQuery(".show-submenu").removeClass("show-submenu"); }); jQuery('.top-nav').click(function (event) { event.stopPropagation(); });
The solution that ended up working for me was to use the DeviceDefinition.GetRenderingByUniqueId method with the RenderingReference.UniqueID object: foreach (RenderingReference renderingReference in parentRenderingReferences) { /* ... unrelated code removed ... */ var layoutField = new LayoutField(contentItem.Fields[FieldIDs.LayoutField]); LayoutDefinition layoutDef = LayoutDefinition.Parse(layoutField.Value); DeviceDefinition deviceDef = layoutDef.GetDevice(device.ID.ToString()); // Update the rendering's datasource RenderingDefinition renderingDefinition = deviceDef.GetRenderingByUniqueId(renderingReference.UniqueID); renderingDefinition.Datasource = newDataSourceValue; /* ... unrelated code removed ... */ }
How can you get a unique ID for a rendering on a specific Sitecore item? I need to programmatically update all of the instances of a particular rendering attached to a Sitecore item. This is the code I first tried and failed to use: foreach (RenderingReference renderingReference in parentRenderingReferences) { /* ... unrelated code removed ... */ var layoutField = new LayoutField(contentItem.Fields[FieldIDs.LayoutField]); LayoutDefinition layoutDef = LayoutDefinition.Parse(layoutField.Value); DeviceDefinition deviceDef = layoutDef.GetDevice(device.ID.ToString()); // Update the rendering's datasource RenderingDefinition renderingDefinition = deviceDef.GetRendering(renderingReference.RenderingID); renderingDefinition.Datasource = newDataSourceValue; /* ... unrelated code removed ... */ } Using RenderingReference.RenderingID in the final statement in that code didn't work, as the RenderingID is the ID of the actual rendering item that lives in /layouts/renderings. So if the item has more than one of the same rendering on a template the code never accesses any renderings after the first instance. I tried using RenderingReference.UniqueID, which appeared to be what I was looking for (the ID of the instance of the rendering): foreach (RenderingReference renderingReference in parentRenderingReferences) { /* ... unrelated code removed ... */ var layoutField = new LayoutField(contentItem.Fields[FieldIDs.LayoutField]); LayoutDefinition layoutDef = LayoutDefinition.Parse(layoutField.Value); DeviceDefinition deviceDef = layoutDef.GetDevice(device.ID.ToString()); // Update the rendering's datasource RenderingDefinition renderingDefinition = deviceDef.GetRendering(renderingReference.UniqueID); renderingDefinition.Datasource = newDataSourceValue; /* ... unrelated code removed ... */ } In this case, the resulting renderingDefinition object is null, so that doesn't work either.
Style Sheets are added using SPEAK via Sitecore Rocks in Visual Studio. The point of this answer is not to show you how to install Sitecore Rocks, however, I will should you how to add it. BEST PRACTICE In the Below Examples, we are working with SPEAK UI through Sitecore Rocks. This is recommended, as Sitecore's Content Editor does not support some of the rendering properties that SPEAK UI requires. As such, it is default procedure to always use Sitecore Rocks when editing SPEAK applications. NOTE: that we are editing the CORE database, so publishing is not needed here. Step 1 - Find the Experience Profile Contact Page Settings Step 2 - Add a New Item Step 3 - Search for Page-Stylesheet-File Set a name for the style sheet here. Step 4 - Set Path to Style Sheet File and Save your Item Double click on the new item you created (TestPanelStyle in this example) Note: That this is the physical path location under your Website Root. Step 5 - Save your CSS File in that Physical Path Step 6 - Reload Your Experience Profile Page You'll Notice that your custom CSS Page now shows up. Version Differences Sitecore 8.0 - Sitecore 8.1 Update 2 Notice that the CSS files are explicit and numerous in SPEAK Applications, as exampled here: Sitecore 8.1 Update 3 Update 3 Introduces CSS Minification. The procedure above to add CSS to your Experience Profile Contact Tab is the same, except the resulting source code is the minified CSS.
How can you assign a style sheet to a custom tab in the Experience Profile? I note that the out of the box tabs of the Experience Profile reference a custom style sheet. <link href="/sitecore/shell/client/Applications/ExperienceProfile/Contact/Details/DetailsTab.css" rel="stylesheet" type="text/css" /> <link href="/sitecore/shell/client/Applications/ExperienceProfile/Contact/Outcomes/Outcomes.css" rel="stylesheet" type="text/css" /> <link href="/sitecore/shell/client/Applications/ExperienceProfile/Contact/Overview/OverviewTab.css" rel="stylesheet" type="text/css" /> <link href="/sitecore/shell/client/Applications/ExperienceProfile/Contact/Channels/ChannelsTab.css" rel="stylesheet" type="text/css" /> etc., etc. I would like to assign a style sheet to a custom tab I have added to this page. Is this possible -- and if so, how? I am running Sitecore 8.1 Update 2?
Move the root item. Step 1 Step 2 Result EDIT: Included to add this And yes, as you point out in comments. Instead of publishing this change, execute this operation in both "master" and "web" (and as needed, if you have more databases in play)
What is the fastest way to relocate lots of items in the tree? We have a Sitecore site that currently exists in production with a lot of content, on the order of half a million article items and supporting content around those articles. We have to relocate those items to another area in the tree (for business reasons that aren't relevant to the question). The structure of the items will remain the same, we just need to move them to a different area. The <site> node start paths will be updated to reflect the new path, so no urls will change. I have to get this done as quickly as possible to minimize content authoring downtime. We also need to publish this change, and a full publish takes hours. What's the fastest way to accomplish this?
UPDATE March 2018 Docker is still not supported, but you can find some base images here: https://github.com/Sitecore/docker-images This repository was created by combining efforts / assets from repos such as sitecoreops and sitecore-nine-docker and sitecore-docker repos. Docker is currently (as of May 2017) not supported, but it is on the roadmap. On the other hand Sitecore provide role specific templates for Azure App Services with the latest versions (8.2 update 1+), you can find them here: https://dev.sitecore.net/Downloads/Sitecore_Experience_Platform/82/Sitecore_Experience_Platform_82_Update3.aspx
Where can I find Docker Images for the different Sitecore Installs? I have seen a lot of good tutorials about how to setup Sitecore to be used in a Docker container. However, this still gives me the problem of configuring the different server roles (i.e. CD, CM, Processing and Aggregation, Reporting) based on my understanding of what should or should not be enabled. I would love to have a place where I could get the "vanilla" Sitecore installs with the proper configs enabled/disabled for each server role. I know that there is a PowerShell script that I can in theory use to setup an particular server role, but I was wondering what other resources we had that could make this easier. Why I would need this? Right now I'm looking at upgrading my 8.1 instance to 8.2, and it's looking like it might take as long as 2 months to be sure that I've got all of the configurations done properly.
Sitecore-specific replica set considerations Your question is partially answered here: What are the best practices for MongoDB replica set latency? That question discusses how latency affects a replica set and how to set it up properly for xDB. As a short summary, you should set up xDB to only read from the primary node of your replica set. This will ensure that all CD servers see the same consistent data set. Replica set data synchronization Main article: https://docs.mongodb.com/v3.2/core/replica-set-sync/ Since all of your instances will read and write from the same MongoDB server, replication rates should only bother you in case of a failure. If your primary node fails, you don't want other nodes to be far behind on replication—otherwise, they won't be able to become the new primary. Luckily, that is rarely an issue. Secondary members copy the oplog from their sync source (normally, the primary node) and apply these operations in an asynchronous process. Oplog entries are often more lightweight than actual data modifications—think of the size of an update query vs the size of data it modifies. Even if your application mostly creates new data (which is what xDB does), syncs are done in bulks, which means they're more efficient network-wise. You can always check how big the lag is between your nodes and take measures, such as ensuring there's enough bandwidth between your servers. But this is almost never an issue. One important thing to consider, though, is whether your primary node's inbound bandwidth is much faster than the outbound bandwidth. This may cause increased replication lag in some situations. As a summary, a geographically distributed replica set is a very good idea and is unlikely to give you synchronization problems.
Is it possible to distribute my xDB MongoDB databases over 3 locations? So I've been reading up on geographically distributed MongoDB setups. I am juggling around an architectural approach/concept for a project. This is roughly what I am looking at. A centralised Content Master setup "somewhere" in the Cloud Regional or National Content Delivery servers to Keep the CD server as close to the visitor as possible/feasible Allow the CD server to live communicate with regional/national systems If I understand the linked article above right; I should be able to set up a three-member replica set in the following manner: One MongoDB server on regional/national location/datacenter One MongoDB server in the global location One MongoDB server "somewhere else" in the Cloud And by doing so, I ensure (or do my best to) maximum availability and resilience for the setup. So my question is this; this all looks fine and well "on paper". But will it work in real life? I mean with the potentially massive amount of data being dumped into the local xDB; do I risk that the other 2 members simply never catch up as there isn't enough "bandwidth in the world" to handle the replication?
As JF said in the comments, indexing CD should be avoided at all cost. Also, if you are using several CM, you need to configure them to avoid competition between instances. See: developers.coveo.com/display/SitecoreV4/Coveo+for+Sitecore+Scaling+Guide Now indexing slowness can be caused by several factors. First of all, on the Sitecore side: Heavy processing done by computed fields (avoid web request or queries against the index. Use database calls instead) Heavy processing done by processors on the indexing pipelines. Way too many fields. Coveo will index all the fields on your templates by default. This is fine in a standard environment, but for a large setup, you might want to start including/excluding fields and templates. See: developers.coveo.com/display/SitecoreV4/Understanding+the+coveoIndexingGetFields+and+coveoIndexingGetTemplates+Pipelines On the Coveo side, ensure that you have the proper hardware : https://onlinehelp.coveo.com/en/ces/7.0/administrator/coveo_platform_hardware_and_software_requirements.htm Now if you cleared all the points above and you still have slowness, you might want to look at the Sitecore logs or the Coveo Index Logs (CES7/Logs)
Speeding up Coveo reindex I've got a CM server with Coveo for Sitecore installed (free edition) and Coveo Enterprise Search on a separate server. I set up Sitecore with Coveo on CM and reindexed relatively quickly. When I set up CD, I have it point to the CM server's implementation and call the search API/admin service/etc on the CM. I'm running a reindex on CD now to do the initial population, but it's running incredibly slow. Like, I started it two hours ago and it's through 450ish documents of the over 42000 it has to index. And that's just Coveo_master_index, then I have to do Coveo_web_index. Is there any way to speed this up, because this is crazy. Thanks. UPDATE 10/24: I marked an answer on this one because it answered the specific question, but I've got more coming out of the scaling guide, now posted here: Getting Coveo configured properly in a CD/CM server setup. Thanks.
As asked in comments above; normally /bin files should not be locked for any particular reason (other than when the site is just starting up) - so I'm not entirely sure what's going on. I can help you on the intermittent part of your question however; I would just flip the app pool before starting the file publish task. appcmd recycle apppool /apppool.name There are a few NPM modules that can execute this for you. One would be gulp-run. It would look something like this: gulp.task('reset-apppool', function() { return run('appcmd recycle apppool /apppool.name').exec() .pipe(gulp.dest('output')); }); EDIT: Updated to include after additional information was added to original question The fact that Roslyn is the locked file, this may actually lead to more of an answer. I suspect Roslyn.exe is busy compiling all of the SPEAK views in your solution (or even just your own .cshtml files) and that is why it is locked at the time you deploy again. I sourced some information from this answer: https://stackoverflow.com/a/38309167/81631 And I assume you have the DotNetCompilerPlatform package referenced in your project? If this is all true, there are two things I would try next. Follow the recommendation in the answer - even if I am not entirely sure of the full ramifications of it. To resolve this issue, simply uncheck the "Allow precompiled site to be updatable" option in your publish profile settings. This should pre-compile your views and allow your C# 6.0 (Latest version of Roslyn Compiler) to run like a champ. If this doesn't help; possibly your site is spending too much time on recompiling over and over. I recommend adding the optimizeCompilations attribute to your web.config <compilation> element. <compilation debug="true" optimizeCompilations="true"> See if that makes the problem go away.
Publishing projects fails because of locked files The solution I am currently working on, the team made the decision to use habitats way of publishing projects in our solutions via gulp tasks. We are finding out however that periodically when we try to publish to our web-root the files are locked and the whole publish process fails because of this. This causes two problems:- Unclean half publishes Time wasted, waiting to deploy again So I want to know a few things:- Is there a way to avoid the half publishes or a way to reverse what we have tried to publish? Can we get round this intermittent issue of files being locked by a process? Is this a fix we can do modifying our gulp scripts if not then any other guidance is appreciated. Example lock C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Deploy\Microsoft.Web.Publishing.Deploy.FileSystem.targets(96,5): error : Copying file obj\Debug\Package\PackageTmp\bin\roslyn\csc.exe to C:\inetpub\wwwroot\WebSite.local\Website\bin\roslyn\csc.exe failed. The process cannot access the file 'C:\inetpub\wwwroot\WebSite.local\Website\bin\roslyn\csc.exe' because it is being used by another process. Error!