How can I customize SharePoint list column aggregation (total) calculations? - sharepoint

I have a SharePoint list column of type 'Single line of text'. Out of the box SharePoint only provides the ability to display a 'Count' total for this column type. I would like to be able to perform a custom aggregation on the data (specifically to sum numeric data held as text to overcome this deficiency).
I have found examples for doing something similar for calculated columns using XSLT and Javascript but I believe that both of these approaches fail where the data is paginated (only aggregating the subset of the list content displayed on screen).
I want to retain the functionality of the ListViewWebPart (rendering, sorting, filtering, view definition, action menus etc.) but add this functionality. How can I do this?

The only things you can do with totals are:
Average; Count; Max; Min; Sum; Standard Deviation; Variance
Not sure how to calculate anything else.

I've not had a chance to fully test it but this is the best I could come up with:
Create a WebPart which contains two controls:
A ViewToolBar with the context of the list/view to be displayed
A Literal containing the rendered HTML of the view to be displayed
This will then render as the original list/view.
On rendering the WebPart, get the items from the view, specifying the RowLimit as the maximum value so that all items in are retrieved (not just the first page).
Iterate over the items, calculating the total in a suitable data type to retain precision.
Render the total as a hidden value in the HTML and overwrite the rendered Count total with Javascript such as by the method described here.
A rough sketch of the code:
public sealed class TextAggregatingWebPart : WebPart {
protected override void CreateChildControls() {
base.CreateChildControls();
var web = SPContext.Current.Web;
var list = web.Lists[SourceList];
var view = list.Views[ViewOfSourceList];
var toolbar = new ViewToolBar();
var context = SPContext.GetContext(
Context, view.ID, list.ID, SPContext.Current.Web);
toolbar.RenderContext = context;
Controls.Add(toolbar);
var viewHtml = new Literal {Text = view.RenderAsHtml()};
Controls.Add(viewHtml);
}
protected override void Render(HtmlTextWriter writer) {
EnsureChildControls();
base.Render(writer);
var web = SPContext.Current.Web;
var list = web.Lists[SourceList];
var view = list.Views[ViewOfSourceList];
var items = list.GetItems(new SPQuery(view) {RowLimit = uint.MaxValue});
foreach (SPItem item in items) {
// Calculate total
}
// Render total and Javascript to replace Count
}
}
Note that this doesn't solve the problem with the Modify View screen only showing Count as a total for text columns. Also there is a possibility that changes to the list between the initial rendering by the view and the retrieval of the items for aggregation could produce discrepancies between the total and the displayed items.

Related

CMS Repeater Select top N row++

I need a load more button to control the repeater shown content.
Here is my steps in the back end after load more button was clicked:
Repeater bind data (Full data/All rows).
Keep the maximum items count (static) from the repeater.
Set total row to show (static) + 1 and initialize the value to select top N row as the limit.
Repeater bind data again (The amount to show only).
Check if repeater items count is less than maximum items count, if not then hide the load more button.
Suppose these steps can give me the expected output?
//Declaration
public static int max = 0;
public static int totalShow = 0;
//SetupControl()
if(!IsPostBack){
rptItems.ClassName = "Blog";
rptItems.Path = "/Shared/%"
rptItems.DataBind();
max = rptItems.Items.Count();
}
//This part is put under a new function
totalShow += 1;
rptItems.SelectTopN = totalShow;
rptItems.DataBind();
lbnLoadMore.Visible = rptItems.Items.Count() < max;
Besides, I'm confusing about the functions as shown below:
Both are from the class CMSRepeater, what's the different? Which one should I use in order to set the limits?
Using static members is definitely not a good approach. Their values would be shared by all users of the application. There are better ways of storing user-specific data:
session (server-side)
JS (client-side) and passing them to the server via query string or hidden field
Regarding TopN and SelectTopN, they do the same thing. It's probably because of backward compatibility.
From the algorithmical point of view, there's no need to bind data multiple times nor to make more than one round-trip to the database. You just need to initialize the datasource/repeater with correct values.
I'd recommend you reading the following articles to get some inspiration:
Turn a Kentico repeater web part into an infinite scroll / lazy loader by Laura Frese
Dynamic jQuery AJAX viewer by Jan Hermann

Select UI Element by filtering properties in coded ui

I have a web application. And I am using coded ui to write automated tests to test the application.
I have a dropdown with a text box. Which on entering values in the textbox, the values in the dropdown gets filtered based on the text entered.
If I type inside textbox like 'Admin', I will get below options like this:
And I need to capture the two options displayed.
But using IE Developer tool (F12), I am not able to capture the filtered options, because the options that are displayed do not have any unique property (like this below). And the options that are NOT displayed have a class="hidden" property
Any way to capture the elements that are displayed by applying some kind of filter like 'Select ui elements whose class != hidden'
Thanks in advance!!
HI please try below code will it works for you or not.By traversing all those controls that have class ="hidden"
WpfWindow mainWindow = new WpfWindow();
mainWindow.SearchProperties.Add(HtmlControl.PropertyNames.ClassName, "hidden");
UITestControlCollection collection = mainWindow.FindMatchingControls();
foreach (UITestControl links in collection)
{
HtmlHyperlink mylink = (HtmlHyperlink)links;
Console.WriteLine(mylink.InnerText);
}
I'm not sure there is a way to do it by search properties, but there are other approaches.
One way would be to brute force difference the collections. Find all the list items, then find the hidden ones and do a difference.
HtmlControl listControl = /* find the UL somehow */
HtmlControl listItemsSearch = new HtmlControl(listControl);
listItemsSearch.SearchProperties.Add(HtmlControl.PropertyNames.TagName, "li");
HtmlControl hiddenListItemsSearch = new HtmlControl(listControl);
hiddenListItemsSearch.SearchProperties.Add(HtmlControl.PropertyNames.TagName, "li");
hiddenListItemsSearch.SearchProperties.Add(HtmlControl.PropertyNames.ClassName, "hidden");
var listItems = listItemsSearch.FindMatchingControls().Except(hiddenListItemsSearch.FindMatchingControls());
You will only be able to iterate this collection one time so if you need to iterate multiple times, create a function that returns this search.
var listItemsFunc = () => listItemsSearch.FindMatchingControls().Except(hiddenListItemsSearch.FindMatchingControls());
foreach(var listItem in listItemsFunc()){
// iterate 1
}
foreach(var listItem in listItemsFunc()){
// iterate 2
}
The other way I would consider doing it would be to filter based on the controls which have a clickable point and take up space on the screen (ie, not hidden).
listItemsSearch.FindMatchingControls().Where(x => {
try { x.GetClickablePoint(); return x.Width > 0 && x.Height > 0; } catch { return false; }
});

Highlight Duplicate list item in SharePoint 2013

I have a SharePoint 2013 (The Cloud version) custom list where 1 column is a text field where contact numbers are keyed in.
How can I get SharePoint to highlight duplicate values in that column so that every time a new item is added to the list, I'll know if the contact number has been used previously?
Ideally, here's what I'd get if I were to enter 816's details for the 2nd time:
CNO....Name.......Issue
816.....Blink........Login Problem (highlighted in red)
907.....Sink.........Access Denied
204.....Mink.........Flickering Screen
816.....Blink........Blank Screen (highlighted in red)
I've been struggling with this for awhile and would be very grateful for any advice. Thanks!
Since SharePoint 2013 uses Client Side Rendering (CSR) as a default rendering mode I would recommend the following approach. Basically the idea is to customize List View on the client side as demonstrated below.
Assume the Requests list that contains RequestNo column.
The following JavaScript template is intended for highlighting the rows when list item with RequestNo column occurs more then once:
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPostRender: function(ctx) {
var rows = ctx.ListData.Row;
var counts = getItemCount(rows,'RequestNo'); //get items count
for (var i=0;i<rows.length;i++)
{
var count = counts[rows[i]["RequestNo"]];
if (count > 1)
{
var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
var tr = document.getElementById(rowElementId);
tr.style.backgroundColor = "#ada";
}
}
}
});
function getItemCount(items,propertyName)
{
var result = {};
for(var i = 0; i< items.length; i++) {
var groupKey = items[i][propertyName];
result[groupKey] = result[groupKey] ? result[groupKey] + 1 : 1;
}
return result;
}
How to apply the changes
Option 1:
Below is demonstrated probably one of easiest way how to apply those changes:
Open the page in Edit mode
Add Content Editor or Script Editor web part on the page
Insert the specified JavaScript template by enclosing it using
script tag into web part
Option 2:
Save the specified JavaScript template as a file (let's name it duplicatehighlight.js) and upload it into Site Assets library
Open the page in Edit mode and find JSLink property in List View web part
Specify the value: ~sitecollection/SiteAssets/duplicatehighlight.js and save the changes.
Result
SharePoint has some basic conditional formatting for Data View Web Parts and XSLT List Views, but the conditions you can use are rather limited. You can compare a field in the current item with a value that you specify. There are no formulas to count the number of items with the same name or similar, which would be the approach to use to identify duplicates.
If you need to identify duplicates, you may want to create a view that groups by the CNO number. Grouping will also include an item count, so you can run down the list and spot groups with more than one item.

Sharepoint webpart combobox of lists

I have a webpart that works off of a list but what I'm trying to do create a dropdown that contains a list of sharepoint lists so that when the user edits the page and selects 'modify shared webpart' they are able to choose a list item and that gets parsed back to the webpart.
Any examples or links to examples appreciated!
Thanks
Dan
What you are looking for is called a Toolpart. Take a look at this example for a tutorial on how to create one.
Overall, your general steps will be:
Create your custom Toolpart class inheriting from Microsoft.SharePoint.WebPartPages.ToolPart
In your custom Toolpart, override CreateChildControls, write the code to iterate over the lists in your SPWeb, and add those to a DropDownList
In your webpart, override GetToolParts and add your custom ToolPart so that it shows up in the right hand side
It sounds like you want to create a custom editor part. In the part you would have one dropdown that shows the names of the lists (you probably want to filter hidden and empty lists) and, when an item is selected from the list, a second dropdown shows the Title column of the items from the selected list.
Here's some code (edited here, so it will need to be cleaned up) to help you get started:
protected Page_Load(...)
{
if (IsPostBack) return;
var web = SPContext.Current.Web;
var query = from list in web.Lists
where list.Hidden == false && list.ItemCount == 0
select list;
DropDownList1.DataSource = query;
DropDownList1.DataTextField = "Title";
DropDownList1.DataBind();
}
protected DropDownList1_SelectedIndexChanged(...)
{
var web = SPContext.Current.Web;
var listName = DropDownList1.Text;
var list = web.Lists[listName];
var table = list.Items.GetDataTable();
DropDownList2.DataSource = table;
DropDownList2.DataTextField = "Title";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}

What is the best way to retrieve distinct / unique values using SPQuery?

I have a list that looks like:
Movie Year
----- ----
Fight Club 1999
The Matrix 1999
Pulp Fiction 1994
Using CAML and the SPQuery object I need to get a distinct list of items from the Year column which will populate a drop down control.
Searching around there doesn't appear to be a way of doing this within the CAML query. I'm wondering how people have gone about achieving this?
Another way to do this is to use DataView.ToTable-Method - its first parameter is the one that makes the list distinct.
SPList movies = SPContext.Current.Web.Lists["Movies"];
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='Year' /></OrderBy>";
DataTable tempTbl = movies.GetItems(query).GetDataTable();
DataView v = new DataView(tempTbl);
String[] columns = {"Year"};
DataTable tbl = v.ToTable(true, columns);
You can then proceed using the DataTable tbl.
If you want to bind the distinct results to a DataSource of for example a Repeater and retain the actual item via the ItemDataBound events' e.Item.DataItem method, the DataTable way is not going to work. Instead, and besides also when not wanting to bind it to a DataSource, you could also use Linq to define the distinct values.
// Retrieve the list. NEVER use the Web.Lists["Movies"] option as in the other examples as this will enumerate every list in your SPWeb and may cause serious performance issues
var list = SPContext.Current.Web.Lists.TryGetList("Movies");
// Make sure the list was successfully retrieved
if(list == null) return;
// Retrieve all items in the list
var items = list.GetItems();
// Filter the items in the results to only retain distinct items in an 2D array
var distinctItems = (from SPListItem item in items select item["Year"]).Distinct().ToArray()
// Bind results to the repeater
Repeater.DataSource = distinctItems;
Repeater.DataBind();
Remember that since there is no CAML support for distinct queries, each sample provided on this page will retrieve ALL items from the SPList. This may be fine for smaller lists, but for lists with thousands of listitems, this will seriously be a performance killer. Unfortunately there is no more optimized way of achieving the same.
There is no DISTINCT in CAML to populate your dropdown try using something like:
foreach (SPListItem listItem in listItems)
{
if ( null == ddlYear.Items.FindByText(listItem["Year"].ToString()) )
{
ListItem ThisItem = new ListItem();
ThisItem.Text = listItem["Year"].ToString();
ThisItem.Value = listItem["Year"].ToString();
ddlYear.Items.Add(ThisItem);
}
}
Assumes your dropdown is called ddlYear.
Can you switch from SPQuery to SPSiteDataQuery? You should be able to, without any problems.
After that, you can use standard ado.net behaviour:
SPSiteDataQuery query = new SPSiteDataQuery();
/// ... populate your query here. Make sure you add Year to the ViewFields.
DataTable table = SPContext.Current.Web.GetSiteData(query);
//create a new dataview for our table
DataView view = new DataView(table);
//and finally create a new datatable with unique values on the columns specified
DataTable tableUnique = view.ToTable(true, "Year");
After coming across post after post about how this was impossible, I've finally found a way. This has been tested in SharePoint Online. Here's a function that will get you all unique values for a column. It just requires you to pass in the list Id, View Id, internal list name, and a callback function.
function getUniqueColumnValues(listid, viewid, column, _callback){
var uniqueVals = [];
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/filter.aspx?ListId={" + listid + "}&FieldInternalName=" + column + "&ViewId={" + viewid + "}&FilterOnly=1&Filter=1",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).then(function(response) {
$(response).find('OPTION').each(function(a,b){
if ($(b)[0].value) {
uniqueVals.push($(b)[0].value);
}
});
_callback(true,uniqueVals);
},function(){
_callback(false,"Error retrieving unique column values");
});
}
I was considering this problem earlier today, and the best solution I could think of uses the following algorithm (sorry, no code at the moment):
L is a list of known values (starts populated with the static Choice options when querying fill-in options, for example)
X is approximately the number of possible options
1. Create a query that excludes the items in L
1. Use the query to fetch X items from list (ordered as randomly as possible)
2. Add unique items to L
3. Repeat 1 - 3 until number of fetched items < X
This would reduce the total number of items returned significantly, at the cost of making more queries.
It doesn't much matter if X is entirely accurate, but the randomness is quite important. Essentially the first query is likely to include the most common options, so the second query will exclude these and is likely to include the next most common options and so on through the iterations.
In the best case, the first query includes all the options, then the second query will be empty. (X items retrieved in total, over 2 queries)
In the worst case (e.g. the query is ordered by the options we're looking for, and there are more than X items with each option) we'll make as many queries as there are options. Returning approximately X * X items in total.

Resources