I've added a ComputedIndexFields.config files with the following code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultIndexConfiguration>
<fields hint="raw:AddComputedIndexField">
<field fieldName="AppliedThemes" storageType="yes" indexType="TOKENIZED">be.extensions.AppliedThemes, be.extensions</field>
</fields>
</defaultIndexConfiguration>
</configuration>
</contentSearch>
</sitecore>
</configuration>
I also added a class in said assemlby:
namespace be.extensions
{
class AppliedThemes : IComputedIndexField
{
public string FieldName { get; set; }
public string ReturnType { get; set; }
public object ComputeFieldValue(IIndexable indexable)
{
Item item = indexable as SitecoreIndexableItem;
if (item == null)
return null;
var themes = item["Themes"];
if (themes == null)
return null;
// TODO
}
}
}
I wanted to test the little bit of code i had already written. So i added a breakpoint at the first line of the "ComputeFieldValue(IIndexable indexable)" method and fired up the website ( while debugging ).
I changed several items, saved them en then rebuild the index tree but my breakpoint is never hit.
The class is located in a different project and build into a .dll with the assemblyname "be.extensions"
I'm using sitecore 8 update 2.
Does anyone know what i did wrong or why this code wouldn't be reached ?
( Like is this code send to some Lucene workflow that i simply can not debug )
Your configuration is likely not being patched in due to a change Sitecore made to the structure of the Include file. Namely, the defaultIndexConfiguration node was changed to defaultLuceneIndexConfiguration along with a new type attribute. You can verify that your computed field is being patched correctly using the /sitecore/admin/showconfig.aspx utility page. Also, please note that the storageType and indextype for each computed index field is now defined in the <fieldMap><fieldNames> section, not where you have it now.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultLuceneIndexConfiguration type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider">
<fields hint="raw:AddComputedIndexField">
<field fieldName="yourname">be.extensions.AppliedThemes, be.extensions</field>
</fields>
</defaultLuceneIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
Related
I have implemented a computed field index in Sitecore 7.2. However, the index manager is broken now and I get the following message
Invalid cast from 'System.String' to 'Sitecore.ContentSearch.ProviderIndexConfiguration'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'Sitecore.ContentSearch.ProviderIndexConfiguration'.
I have implemented the following class for my computed field:
namespace Computed.Search
{
public class OfficeLocationComputedField : IComputedIndexField
{
public string FieldName { get; set; }
public string ReturnType { get; set; }
public object ComputeFieldValue(IIndexable indexable)
{
Assert.ArgumentNotNull(indexable, nameof(indexable));
try
{
var result = new List<string>();
var indexableItem = indexable as SitecoreIndexableItem;
if (indexableItem == null)
return null;
var item = (Item) indexableItem;
// Treelist fields map to the MultilistField type as per ~/App_Config/FieldTypes.config
MultilistField field = item?.Fields["officelocation"];
if (field == null)
return null;
var items = field.GetItems();
if (items == null || items.Length == 0)
return result;
foreach (var locationItem in items)
{
//result.Add(locationItem.Name); // if you want the name of the item
result.Add(locationItem.DisplayName); // if you want the display name of the item
//result.Add(locationItem["Title"]); // if you want the value of a field on the item
}
return result;
}
catch (Exception exception)
{
Log.Error($"An Error occured in custom computed index. {exception.Message}", exception);
}
return null;
}
}
}
And the configuration file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultLuceneIndexConfiguration>
<fields hint="raw:AddComputedIndexField">
<field fieldName="officelocation" storageType="YES" indexType="TOKENIZED">Computed.Search.OfficeLocationComputedField, Computed</field>
</fields>
</defaultLuceneIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
I don't know what mistake I am making or what else I need to change?
The Sitecore Invalid cast from 'System.String' to ... exception in 90% cases is cause by the configuration mistakes.
In your case Sitecore tries to cast string to ProviderIndexConfiguration. It's LuceneIndexConfiguration which inherits from ProviderIndexConfiguration.
It looks like Sitecore cannot match you patch file content with default Lucene index configuration.
Make sure that your patch file name is alphabetically after Sitecore.ContentSearch.Lucene.DefaultIndexConfiguration.config.
It the problem persists, add type attribute to defaultLuceneIndexConfiguration tag and set it to type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider":
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultLuceneIndexConfiguration type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider">
<fields hint="raw:AddComputedIndexField">
<field fieldName="officelocation" storageType="YES" indexType="TOKENIZED">Computed.Search.OfficeLocationComputedField, Computed</field>
</fields>
</defaultLuceneIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
The older patch file that I had created and was alphabetically before the Sitecore.ContentSearch.Lucene.DefaultIndexConfiguration.config was still in the Website\App_Config\Include folder. I forgot to remove it. Removing that old file fixed the problem. Everything is working now.
I use Sitecore 7 and in the code I see this line
public static ID HelpLinks
{
get { return GetIdFromConfig("aer.ProductDetails.HelpLinks"); }
}
Developer define this line with this function
static ID GetIdFromConfig(string key)
{
try
{
return new ID(Sitecore.Configuration.Settings.GetSetting(key));
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Warn(String.Format("GetIdFromConfig (key='{0}'): not found ", key), ex, "aed.Classes.ConfigID");
return null;
}
}
I wonder how it define the
aer.ProductDetails.HelpLinks
In order to get Sitecore unique ID and use it in other templates.
is any one know how it define?
Somewhere in settings section in configs (either web.config or some include file from Include folder for your solution) you need to define that key with that name.
Should have something like this:
<sitecore>
<settings>
<setting name="aer.ProductDetails.HelpLinks" value="sitecoreID" />
</settings>
</sitecore>
where sitecoreID is an Sitecore ID format like {DE3A698F-1D7F-4C43-B797-162C5811E270}
Sitecore comes with several standard custom value tokens when creating branch templates (i.e. $name for the name of the new item, $parentid, for the id of the parent).
Is there anyway to add new variables?
Specifically I want a variable that will allow me to access the items path when added?
There is a sitecore blog post for this ADD CUSTOM STANDARD VALUES TOKENS IN THE SITECORE ASP.NET CMS but TBH, it's wrong . I'm not sure why sitecore insist on producing "untested prototype(s)" all the time in these posts. The guy in that blog literally says You can implement a solution based on the following untested prototype o_O
For some reason sitecore are jumping though various hoops to decompile the source and then recreate it (give a man a hammer and everything looks like a nail maybe?). This makes your code very fragile should the default behaviour change and is just totally unnecessary.
You can add a new variable in a few lines of code:
public class NewVariablesReplacer : MasterVariablesReplacer
{
public override string Replace(string text, Item targetItem)
{
//still need to assert these here
Sitecore.Diagnostics.Assert.ArgumentNotNull(text, "text");
Sitecore.Diagnostics.Assert.ArgumentNotNull(targetItem, "targetItem");
string tempTxt = text;
if (text.Contains("$path"))
{
Sitecore.Diagnostics.Assert.ArgumentNotNull(targetItem.Paths, "targetItem.Paths");
Sitecore.Diagnostics.Assert.ArgumentNotNull(targetItem.Paths.FullPath, "targetItem.Paths.FullPath");
tempTxt = text.Replace("$path", targetItem.Paths.FullPath);
}
//Do what you would normally do.
return base.Replace(tempTxt, targetItem);
}
}
This works without decompiling because it retains the base functionality by calling base.Replace(text, targetItem);.
You then need to alter the default behaviour in the xml as in the blog post:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="MasterVariablesReplacer">
<patch:attribute name="value">Sitecore.Sharedsource.Data.NewVariablesReplacer ,Sitecore.Sharedsource</patch:attribute>
</setting>
</settings>
</sitecore>
</configuration>
Out of the box, we have these variables at our disposal:
$name: The item name
$id: The item ID
$parentid: The item ID of the parent item
$parentname: The item name of the parent item
$date: The system date
$time: The system time
$now: The combination of system date and time
Tokens are variables that start with the “$” symbol. When a content item is created in the content tree, the pipeline that gets invoked is:
<expandInitialFieldValue help="Processors should derive from Sitecore.Pipelines.ExpandInitialFieldValue.ExpandInitialFieldValueProcessor">
<processor type="Sitecore.Pipelines.ExpandInitialFieldValue.SkipStandardValueItems, Sitecore.Kernel" />
<processor type="Sitecore.Pipelines.ExpandInitialFieldValue.CheckSharedField, Sitecore.Kernel" />
<processor type="Sitecore.Pipelines.ExpandInitialFieldValue.ReplaceVariables, Sitecore.Kernel" /></expandInitialFieldValue>
The pipeline that does all the work is:
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
MasterVariablesReplacer variablesReplacer = Factory.GetMasterVariablesReplacer();
string text = args.SourceField.Value;
if (variablesReplacer == null)
args.Result = text;
else
args.Result = variablesReplacer.Replace(text, args.TargetItem);
}
In the ReplaceVariables processor, you will see that there is a call to another class that does all the work. This class is defined in the section of web.config.
<setting name="MasterVariablesReplacer" value="Sitecore.Data.MasterVariablesReplacer,Sitecore.Kernel.dll" />
Decompile this class and you will see that the execution order is Replace > ReplaceValues > ReplaceWithDefault with Replace being a virtual method while the others are not. Fortunately for us, this means we can easily override the combined logic with a custom subclass of our own.
<!--<setting name="MasterVariablesReplacer" value="Sitecore.Data.MasterVariablesReplacer,Sitecore.Kernel.dll" />-->
<setting name="MasterVariablesReplacer" value="Client.SitecoreUtil.SettingsOverrides.MasterVariablesReplacer,Client.Sitecore" />
In our custom class, we have to override the Replace method with the same or similar code. Then we need two local private versions of ReplaceValues and ReplaceWithDefault. We can use the same or similar code for ReplaceWithDefault but the ReplaceValues method is where you would define your custom tokens and also tell Sitecore what to do with it. For example, let’s say you want to replace the custom “$test” token with the string “hello” this would be the resulting code.
private string ReplaceValues(string text, Func<string> defaultName, Func<string> defaultId, Func<string> defaultParentName, Func<string> defaultParentId)
{
if (text.Length == 0 || text.IndexOf('$') < 0)
return text;
ReplacerContext context = this.GetContext();
if (context != null)
{
foreach (KeyValuePair<string, string> keyValuePair in (SafeDictionary<string, string>)context.Values)
text = text.Replace(keyValuePair.Key, keyValuePair.Value);
}
text = this.ReplaceWithDefault(text, "$name", defaultName, context);
text = this.ReplaceWithDefault(text, "$id", defaultId, context);
text = this.ReplaceWithDefault(text, "$parentid", defaultParentId, context);
text = this.ReplaceWithDefault(text, "$parentname", defaultParentName, context);
text = this.ReplaceWithDefault(text, "$date", (Func<string>)(() => DateUtil.IsoNowDate), context);
text = this.ReplaceWithDefault(text, "$time", (Func<string>)(() => DateUtil.IsoNowTime), context);
text = this.ReplaceWithDefault(text, "$now", (Func<string>)(() => DateUtil.IsoNow), context);
text = this.ReplaceWithDefault(text, "$test", (Func<string>)(() => "hello"), context);
return text;
}
That is all there is to define custom token variables for Sitecore standard values. All the work is done in the ReplaceValues method.
I followed the steps here to create a new custom rule and add it to the ruleset in VSStudio 2013:
http://blog.tatham.oddie.com.au/2010/01/06/custom-code-analysis-rules-in-vs2010-and-how-to-make-them-run-in-fxcop-and-vs2008-too/
However, despite all my efforts, the custom rule does not show up in the ruleset file.
If I add the rule in the FXCop Editor, it shows up and analyzes the target project correctly.
This is the Rule File, which is an embedded resource in the project:
<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="PSI Custom FxCop Rules">
<Rule TypeName="EnforceHungarianNotation" Category="PSIRules" CheckId="CR0001">
<Name>Enforce Hungarian Notation</Name>
<Description>Checks fields for compliance with Hungarian notation.</Description>
<Resolution>Field {0} is not in Hungarian notation. Field name should be prefixed with '{1}'.</Resolution>
<MessageLevel Certainty="100">Error</MessageLevel>
<FixCategories>Breaking</FixCategories>
<Url />
<Owner />
<Email />
</Rule>
</Rules>
This is my RuleSet:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="New Rule Set" Description=" " ToolsVersion="10.0">
<RuleHintPaths>
<Path>C:\App\PSI\Development\Source\JHA.ProfitStars.PSI\JHA.ProfitStars
.PSI.FxCop\bin\Debug</Path>
</RuleHintPaths>
</RuleSet>
I even tried adding the line below, but now it shows an Unknown rule in the ruleset:
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis"
RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CR0001" Action="Error" />
</Rules>
Could someone please help me understand what I am doing wrong here?
Edited:
BaseClass for rules:
internal abstract class BaseFxCopRule : BaseIntrospectionRule
{
protected BaseFxCopRule(string ruleName)
: base(ruleName, "JHA.ProfitStars.PSI.FxCop.Rules", typeof(BaseFxCopRule).Assembly)
{ }
}
Rules Class:
internal sealed class EnforceHungarianNotation : BaseFxCopRule
{
public EnforceHungarianNotation()
: base("EnforceHungarianNotation")
{
}
public override TargetVisibilities TargetVisibility
{
get
{
return TargetVisibilities.NotExternallyVisible;
}
}
public override ProblemCollection Check(Member member)
{
Field field = member as Field;
if (field == null)
{
// This rule only applies to fields.
// Return a null ProblemCollection so no violations are reported for this member.
return null;
}
if (field.IsStatic)
{
CheckFieldName(field, s_staticFieldPrefix);
}
else
{
CheckFieldName(field, s_nonStaticFieldPrefix);
}
// By default the Problems collection is empty so no violations will be reported
// unless CheckFieldName found and added a problem.
return Problems;
}
private const string s_staticFieldPrefix = "s_";
private const string s_nonStaticFieldPrefix = "m_";
private void CheckFieldName(Field field, string expectedPrefix)
{
if (!field.Name.Name.StartsWith(expectedPrefix, StringComparison.Ordinal))
{
Resolution resolution = GetResolution(
field, // Field {0} is not in Hungarian notation.
expectedPrefix // Field name should be prefixed with {1}.
);
Problem problem = new Problem(resolution);
Problems.Add(problem);
}
}
}
Looks like your path is kind of shaky, remove some spacing and unwanted characters:
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="New Rule Set" Description=" " ToolsVersion="10.0">
<RuleHintPaths>
<Path>C:\App\PSI\Development\Source\JHA.ProfitStars.PSI\JHA.ProfitStars.PSI.FxCop\bin\Debug</Path>
</RuleHintPaths>
</RuleSet>
Also adding the rulesdll to Microsoft Visual Studio [Version]\Team Tools\Static Analysis Tools\FxCop\Ruleslocation would solve the issue of having to use Rulehintpaths.
As I can't detect anything wrong with your custom rules, see if you have selected the option to show all rules:
Also, using the following BaseRule might help:
protected BaseRule(string name)
: base(
// The name of the rule (must match exactly to an entry
// in the manifest XML)
name,
// The name of the manifest XML file, qualified with the
// namespace and missing the extension
typeof(BaseRule).Assembly.GetName().Name + ".Rules",
// The assembly to find the manifest XML in
typeof(BaseRule).Assembly)
{
}
Close your solution. Use the Source Control Explorer to locate your Rule Set File. Doubleclick onto your ruleset. The Rule Set Editor now should show all your custom rules. If this still doesn't work, try to use a relative path in the Path tag of the RuleHintPaths section.
Have a look at the LoadFromFile() method of the Microsoft.VisualStudio.CodeAnalysis.dll:
public static RuleSet LoadFromFile(string filePath, IEnumerable<RuleInfoProvider> ruleProviders)
{
RuleSet ruleSet = RuleSetXmlProcessor.ReadFromFile(filePath);
if (ruleProviders != null)
{
string relativePathBase = string.IsNullOrEmpty(filePath) ? (string) null : Path.GetDirectoryName(ruleSet.FilePath);
Dictionary<RuleInfoProvider, RuleInfoCollection> allRulesByProvider;
Dictionary<string, IRuleInfo> rules = RuleSet.GetRules((IEnumerable<string>) ruleSet.RuleHintPaths, ruleProviders, relativePathBase, out allRulesByProvider);
foreach (RuleReference ruleReference in (Collection<RuleReference>) ruleSet.Rules)
{
IRuleInfo ruleInfo;
if (rules.TryGetValue(ruleReference.FullId, out ruleInfo))
{
if (ruleInfo.AnalyzerId == ruleReference.AnalyzerId)
ruleReference.RuleInfo = ruleInfo;
else
CATrace.Info("RuleSet.LoadFromFile: Rule {0} was listed under analyzer id {1} in the rule set, but the corresponding IRuleInfo returned analyzer id {2}", (object) ruleReference.FullId, (object) ruleReference.AnalyzerId, (object) ruleInfo.AnalyzerId);
}
}
}
return ruleSet;
}
If the relativePathBase is calculated wrong, the rule DLLs will not be found.
I've been storing collections of user settings in the Properties.Settings.Default object and using the Visual Studio settings designer (right-click on your project, click on Properties and then click on the Settings tab) to set the thing up. Recently, several users have complained that the data this particular setting tracks is missing, randomly.
To give an idea (not exactly how I do it, but somewhat close), the way it works is I have an object, like this:
class MyObject
{
public static string Property1 { get; set; }
public static string Property2 { get; set; }
public static string Property3 { get; set; }
public static string Property4 { get; set; }
}
Then in code, I might do something like this to save the information:
public void SaveInfo()
{
ArrayList userSetting = new ArrayList();
foreach (Something s in SomeCollectionHere) // For example, a ListView contains the info
{
MyObject o = new MyObject {
Property1 = s.P1;
Property2 = s.P2;
Property3 = s.P3;
Property4 = s.P4;
};
userSetting.Add(o);
}
Properties.Settings.Default.SettingName = userSetting;
}
Now, the code to pull it out is something like this:
public void RestoreInfo()
{
ArrayList setting = Properties.Settings.Default.SettingName;
foreach (object o in setting)
{
MyObject data = (MyObject)o;
// Do something with the data, like load it in a ListView
}
}
I've also made sure to decorate the Settings.Designer.cs file with [global::System.Configuration.SettingsSerializeAs(global::System.Configuration.SettingsSerializeAs.Binary)], like this:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SettingsSerializeAs(global::System.Configuration.SettingsSerializeAs.Binary)]
public global::System.Collections.ArrayList SettingName
{
get {
return ((global::System.Collections.ArrayList)(this["SettingName"]));
}
set {
this["SettingName"] = value;
}
}
Now, randomly, the information will disappear. I can debug this and see that Properties.Settings.Default is returning an empty ArrayList for SettingName. I would really rather not use an ArrayList, but I don't see a way to get a generic collection to store in this way.
I'm about to give up and save this information using plain XML on my own. I just wanted to verify that I was indeed pushing this bit of .NET infrastructure too far. Am I right?
I couldn't find an answer as to why these settings were disappearing and since I kept on happening, I ended up storing the complicated sets of settings separately in an XML file, manually serializing and deserializing them myself.
I had a very similar experience when using the SettingsSerializeAs Binary Attribute in the Settings Designer class. It worked in testing, but some time later it failed to restore the property values.
In my case there had been subsequent additions to the Settings made via the designer. Source control history showed that the SettingsSerializeAs Attribute had been removed from Settings.Designer.cs without my knowledge.
I added the following code to check that the attribute hadn't been accidentally lost it the equivalent of the RestoreInfo() method.
#if(DEBUG)
//Verify that the Property has the required attribute for Binary serialization.
System.Reflection.PropertyInfo binarySerializeProperty = Properties.Settings.Default.GetType().GetProperty("SettingName");
object[] customAttributes = binarySerializeProperty.GetCustomAttributes(typeof(System.Configuration.SettingsSerializeAsAttribute), false);
if (customAttributes.Length != 1)
{
throw new ApplicationException("SettingsSerializeAsAttribute required for SettingName property");
}
#endif
Also, only because it is missing from your example, don't forget to call Save. Say after calling SaveInfo().
Properties.Settings.Default.Save();
When using the Settings feature with the User scope, the settings are saved to the currently logged in user's Application Data (AppData in Vista/7) folder. So if UserA logged in, used your application, and then UserB logged in, he wouldn't have UserA's settings loaded, he would have his own.
In what you're trying to accomplish, I would suggest using the XmlSerializer class for serializing an list of objects. The use is pretty simple:
To serialize it:
ArrayList list = new ArrayList();
XmlSerializer s = new XmlSerializer(typeof(ArrayList));
using (FileStream fs = new FileStream(#"C:\path\to\settings.xml", FileMode.OpenOrCreate))
{
s.Serialize(fs, list);
}
To deserialize it:
ArrayList list;
XmlSerializer s = new XmlSerializer(typeof(ArrayList));
using (FileStream fs = new FileStream(#"C:\path\to\settings.xml", FileMode.Open))
{
list = (ArrayList)s.Deserialize(fs);
}
From your example I don't see anything incorrect about what your trying to do. I think the root of the problem your describing might be your assembly version changing? User settings do not auto-magically upgrade themselves (at least I couldn't get them to).
I can appreciate your plight, I went through this a few months ago. I coded up a UserSettings class that provided standard name/value pair collections (KeyValueConfigurationElement) under a named group heading something like the following:
<configSections>
<section name="userSettings" type="CSharpTest.Net.AppConfig.UserSettingsSection, CSharpTest.Net.Library"/>
</configSections>
<userSettings>
<add key="a" value="b"/>
<sections>
<section name="c">
<add key="a" value="y"/>
</section>
</sections>
</userSettings>
Anyway see if this meets your needs or provides some insight into implementing a custom ConfigurationSection to allow what you need.
Oh yea, the code is here:
http://csharptest.net/browse/src/Library/AppConfig