Sitecore workbox change sort order - sitecore

By default Sitecore workbox displays the Item name, and sort the item list by Item name.
In one of my previous posts regarding this I managed to change the item name to a custom field.
Now I need to sort workbox by this field. How can I do this?

Assuming that you already have your own implementation of the WorkboxForm as described in the post you linked in your question, you need to change the code of the DisplayState method.
The DataUri[] items inflow parameter of this method gives you the list of all items which are in given state of the workflows. You need to retrieve all the Sitecore items from this parameter and sort them:
DataUri[] items = new DataUri[0];
List<Item> sitecoreItems = items
.Select(uri => Context.ContentDatabase.Items[uri])
.OrderBy(item => item["YourCustomField"])
.ToList();
And use the new list for selecting the current page items. This solution is not optimized for the performance - you need to get every item in given state from database so you can access the custom field.

After studying Sitecore workbox modifications, I came across with following solution.
Step 1 - Modify the GetItems method as follows,
private DataUri[] GetItems(WorkflowState state, IWorkflow workflow)
{
if (workflow != null)
{
var items = workflow.GetItems(state.StateID);
Array.Sort(items, new Comparison<DataUri>(CompareDataUri));
return items;
}
return new DataUri[] { };
}
Here comes the "CompareDataUri" method,
private int CompareDataUri(DataUri x, DataUri y)
{
//Custom method written to compare two values - Dhanuka
Item itemX = Sitecore.Context.ContentDatabase.GetItem(x);
Item itemY = Sitecore.Context.ContentDatabase.GetItem(y);
string m_sortField = "__Updated";
bool m_descSort = false;
var res = 0;
res = string.Compare(itemX[m_sortField], itemY[m_sortField]);
if (m_descSort)
{
if (res > 0)
return -1;
if (res < 0)
return 1;
}
return res;
}
This approach is optimized for performance.

Related

Sitecore dictionary items Editable via page editor

I am trying to implement Sitecore Dictionary items to be edited via PageEditor.
This is my approach.. Just need your thoughts and suggestions.
To make it simple and not to mess up with the pipelines, here is a simple way of what I am doing.
Normally you do a sitecore translate for example,
#Sitecore.Globalization.Translate.Text("SomeKey")
You can encapsulate the Translate to a custom class which might look like
public static class CustomTranslate
{
public static string Text(string key)
{
if (Sitecore.Context.PageMode.IsPageEditorEditing)
{
string val = String.Empty;
Item currentItem = Context.Database.GetItem(ResourcesController.ItemLookUp()[key]);
if (currentItem != null)
{
val = FieldRenderer.Render(currentItem, "Phrase");
}
return val;
}
else
return Sitecore.Globalization.Translate.Text(key);
}
}
The CustomTranslate.Text returns a FieldRenderer in PageEdit mode else returns the Sitecore.Globalization.Translate.Text
Then in your code you can refer the translations as
#CustomTranslate.Text("SomeKey")
The Lookup can be a dictionary of Key and Item ID as shown in below code,
public static class ResourceController
{
public static Dictionary ItemLookUp()
{
///get dictionary path..etc.. code not included
//read all sitecore dictionary Items
Sitecore.Data.Items.Item[] items =
Sitecore.Context.Database.SelectItems("fast:" + dictionaryPath +
"//*[##templateid='{6D1CD897-1936-4A3A-A511-289A94C2A7B1}']");
//build a Dictionary<string,string> using sitecore item key and Guid.
items.All(y => { resourceDictionary.Add(y["Key"], y.ID.Guid.ToString()); return true;}
// Key,Guid dictionary
return resourceDictionary;
}
}
A Simpler and much easier approach ! Thoughts, Comments ?

Sitecore Update Placeholder Key (Programming)

I'd like to update the value of placeholder(PH) key assigned into each page item.
The problem is I changed the value of PH key in master template (actually combined two templates to make only one template) and a number of pages should be updated with new assigned PH key.
How to update placeholder key without clicking each item and changing the value in presentation? If I do like this, it takes a lot of time.
What I want to do in program is:
Set initial path (/sitecore/home/robot/)
Check each item (with each item's sub-item) in initial path
Retrieve each item's assigned controls in presentation
If there is "Breadcrumbs" control with "breadcrumbs" key name
Then, change the value to "/template/dynamic/breadcrumbs"
Do until it retrives all items in the initial path
See the code below. What it does, it gets rendering references for the selected items, checks their placeholders and rendering names and updates xml value of the __Renderings field of selected item, based on the unique id of selected renderings. Then it fires same code for all descendants recursively.
This code
does not update placeholders for components which are inherited from __Standard Values
does not publish changed items automatically.
is case sensitive
requires that user has write access for the items that you want to change
public void Start()
{
string initialPath = "/sitecore/home/robot";
Item root = Database.GetDatabase("master").GetItem(initialPath);
UpdatePlaceholderName(root, "Breadcrumbs", "breadcrumbs", "/template/dynamic/breadcrumbs");
}
private void UpdatePlaceholderName(Item item, string componentName, string placeholderName, string newPlaceholderName)
{
if (item != null)
{
List<RenderingReference> renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, false)
.Where(r => r.Placeholder == placeholderName && r.RenderingItem.Name == componentName).ToList();
if (renderings.Any())
{
string renderingsXml = item["__Renderings"];
item.Editing.BeginEdit();
foreach (RenderingReference rendering in renderings)
{
string[] strings = renderingsXml.Split(new [] {"<r"}, StringSplitOptions.None);
foreach (string renderingXml in strings)
{
if (renderingXml.Contains("s:ph=\"" + placeholderName + "\"") && renderingXml.Contains("uid=\"" + rendering.UniqueId + "\""))
{
renderingsXml = renderingsXml.Replace(renderingXml, renderingXml.Replace("s:ph=\"" + placeholderName + "\"", "s:ph=\"" + newPlaceholderName + "\""));
}
}
}
item["__Renderings"] = renderingsXml;
item.Editing.EndEdit();
}
foreach (Item child in item.GetChildren())
{
UpdatePlaceholderName(child, componentName, placeholderName, newPlaceholderName);
}
}
}

Qt C++ Get data from a selected row of a table view

I have a table view populated with data of Vehicle objects stored in a QList<Vehicle> cars; On this cars list i have to make some actions: search, add, edit, delete; After every action of search, i store the founded objects in another list to populate the table view only with this objects, keeping the original list intact. The original list gets modified only on add, edit or delete. Here comes the problem: i search for an object that i want to edit, it is shown in the table view, i select it and press the edit button; i am using QModelIndexList to get the index of the row. The index of the row will give me the position from the "founded" list, and i need to modify the object in the original list. Below is my implementation.
Is there any other way to this thing without the temporary list? How can i modify the original object using Iterator, instead that for loop?
void MainWindow::on_actionEdit_triggered()
{
QMessageBox msgBox;
QModelIndexList id = ui->tableView->selectionModel()->selectedIndexes();
if(id.isEmpty()){
msgBox.setWindowTitle("Message");
msgBox.setText("Please select a row");
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.exec();
} else{
int row = id.at(0).row();
QUuid carId = temp.at(row).getVehicleID(); // temp -> the "the founded" list
for(int i = 0; i < cars.size(); i++){
Vehicle& current = cars[i];
Vehicle& currentTemp = temp[row];
if(carId == current.getVehicleID() && carId == currentTemp.getVehicleID()){
addDialog = new AddEditDialog(this);
addDialog->loadVehicleToEdit(current);
addDialog->exec();
if(addDialog->getIsEdited()){
current = addDialog->getVehicleToAdd();
currentTemp = addDialog->getVehicleToAdd();
currentTemp.setVehicleId(carId);
current.setVehicleId(carId);
}
}
}
}
//create header
createHeader(model);
//set data to the table view
populate(temp);
}
May be you use proxy model and you need to call mapToSource?

Sitecore workbox only display the latest Version of an item

I have customized workbox by overriding it. By default Workbox displays all versions of items in a particular workflow state.
I need only the last version to appear in the workbox.
Played around with the DisplayStates(IWorkflow workflow, XmlControl placeholder) method, but no luck.
How can I do this?
You need to override DisplayStates() method and filter the DataUri[] items array:
List<DataUri> filteredUriList = new List<DataUri>();
DataUri[] items = this.GetItems(state, workflow);
for (int index = offset; index < num; ++index)
{
Item obj = Sitecore.Context.ContentDatabase.Items[items[index]];
if (obj != null && obj.Versions.IsLatestVersion())
filteredUriList.Add(items[index]);
}
items = filteredUriList.ToArray();

How do I trigger a profile in Sitecore DMS?

I am looking for a way to allow visitors to select what content they want displayed on the site.
Is there a way to programatically trigger a profile in Sitecore DMS?
I've looked at relevant documentation on SDN (http://sdn.sitecore.net/Reference/Sitecore 6/DMS Documentation.aspx), but so far haven't found a way.
EDIT: Raised this on Sitecore Support Portal - will post an answer once I find out more.
I have done something similar on my project. Check out this code sample and let me know if you have any questions. Also, make sure you add profiles to content items too. Call FilterItemByBehavior on a collection of items and it will filter them based on user's past browsing behavior.
private static Dictionary<string, List<string>> AnalyticsFilter()
{
Dictionary<string, List<string>> filter = new Dictionary<string, List<string>>();
if (Tracker.CurrentVisit.Profiles.Count() > 0)
{
foreach (VisitorDataSet.ProfilesRow row in Tracker.CurrentVisit.Profiles)
{
List<string> keys = new List<string>();
foreach (var key in row.Values)
{
if (key.Value >= ResourceHelper.GetInt(new ID(Resources.Settings.AnalyticsProfileSetMinValGuid)))
keys.Add(key.Key);
}
filter.Add(row.ProfileName, keys);
}
}
if(ResourceHelper.IsTurnedOn(new ID(Resources.Settings.AnalyticsUserProfileEnableSwitch)))
filter = ApplyUserProfile(filter);
return filter;
}
public static List<Item> FilterItemByBehavior(List<Item> items, int count)
{
try
{
var filter = AnalyticsFilter();
foreach (var profile in filter)
{
int counter = ResourceHelper.GetInt(new ID(Resources.Settings.AnalyticsProfileTagsFilterMaxGuid));
if (items.Count <= count) break;
foreach (string key in profile.Value)
{
if (items.Count <= count || counter == 0) break;
items = items.Where(i => (((MultilistField)i.Fields[profile.Key]).GetItems().ToList().Select(x => x.Name).Contains(key))).ToList();
counter--;
}
}
return items.Count <= count ? items : items.Take(count).ToList();
}
catch (System.Exception ex)
{
Sitecore.Diagnostics.Log.Error(ex.Message, ex, new AnalyticsHelper());
return items.Count <= count ? items : items.Take(count).ToList();
}
}
I have received a response from Sitecore support on this question. Here it is:
"If you are using pattern cards for personalzation, then you can use the following code as the event handler for "item selected" event for the dropdown list:"
var profile = Sitecore.Analytics.Tracker.CurrentVisit.GetOrCreateProfile("<Profile Name>");
profile.BeginEdit();
profile.Score("<profile key>",<profile key value you want to set>);
profile.Score("<profile key>",<profile key value you want to set>);
profile.UpdatePattern(); //sets the appropriate pattern based on the current profile keys values you have just set.
profile.EndEdit();
This interferes with automatic profile matching, so I am not sure I want to use this approach.