Modify Welcome Menu username Jquery

Needing to deal with grabbing the username displayed in the top-right SharePoint welcome menu and reverse the lastname, firstname format it was in, I came up with the following Jquery script.

It takes the welcome menu root takes in the style of “Smith, Joe” and turns it into “Joe Smith”, with having to mess with User Profile Synching or feature stapling. You could adapt it for any other need in a jiffy. The important thing to note is that grabbing the client side ID of the welcome menu is done with a wildcard expression, since the clientside ID is prone to changing – for example it could be “zz16_Menu_tt” one time and “zz12_Menu_tt” the next:

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(ReOrderUsername, "sp.js");
        function ReOrderUsername() {
		var userName = $('[id$=_Menu_t]').children("a").children("span").text();
		if(userName.indexOf(", ")!=-1) {
		      var fnstart = userName.indexOf(", ", 0);
		      var fnend = userName.indexOf("<",fnstart);
		      var lastName = userName.substring(fnstart, fnend);
		      var firstName = userName.split(", ").pop();
	              $('[id$=_Menu_t]').children("a").children("span").text(firstName + ' ' + lastName);
	         }
        }
</script>
Read More

SpSite in Nintex Workflow Custom Action

So today I needed to get the URL of the current SharePoint site my Nintex Custom Action Visual Studio solution is executed under, using the SPSite class. Problem was, was not working on the server of the SPSite. Nor would I want to have to install Visual Studio on the production instance where the solution was to live.

Makes sense, just need to grab the httpcontext. SPContext.Current.Site seemed to fit the bill, but alas, it did not work. Lost some time hunting for a solution to the following error:

Could not create activity of type 'CustomActions.MyCustomActivity'. System.IO.FileNotFoundException: The Web application at http://xxx.xxx.com could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
at Microsoft.SharePoint.SPSite..ctor(String requestUrl)

There’s a number of possible causes and it took going through some pain in order to resolve which route to take. The standard contingencies are explained quite well on http://www.thorntontechnical.com/tech/sharepoint/new-spsite-filenotfoundexception. None of those, possibly valid error causes, solved my beef.

In the end I found that we don’t actually need to be local with VS on the SharePoint server the solution is compiled against- it was just a matter of finding out how to reference the application context: the Nintex way. In this case, it was being handled by Nintex and the method used was not seemingly explained in the SDK or documented. Looking a bit deeper it became clear the application context was being fed in by Nintex.

Working from the DeployWorkflowActionWithFeature example in the Nintex Workflow 2010 SDK, we can see that in the EventLogAdapter.cs in the project, the context is initially set up in the following function:

public override CompositeActivity AddActivityToWorkflow(PublishContext context)
        {
            EventLogActivity activity = new EventLogActivity();

            Dictionary<string, ActivityParameterHelper> parameters = context.Config.GetParameterHelpers();

            parameters[Parameter_Message].AssignTo(activity, EventLogActivity.MessageProperty, context);
            parameters[Parameter_EventSource].AssignTo(activity, EventLogActivity.EventSourceProperty, context);

            activity.SetBinding(EventLogActivity.__ContextProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__context));
            activity.SetBinding(EventLogActivity.__ListItemProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__item));
            activity.SetBinding(EventLogActivity.__ListIdProperty, new ActivityBind(context.ParentWorkflow.Name, StandardWorkflowDataItems.__list));

            ActivityFlags f = new ActivityFlags();
            f.AddLabelsFromConfig(context);
            f.AssignTo(activity);

            context.ParentActivity.Activities.Add(activity);

            return null;
        }

That function sets up the __context for use in EventLogActivity.cs as follows:

public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(EventLogActivity));

Now that we have that rolling, we can use the __Context object with SPSite to get our current application URL.
SO, instead of using this:

SPSite site = new SPSite(“http://mysite/sitename”);

Use this:

SPSite site = new SPSite(this.__Context.Site.Url);

You now have the basis to perform all the wonderful SharePoint API stuff you need to do within the context of the Nintex Custom Action.

Read More

Delete Closed Web Part SharePoint 2010

Needing to delete a bunch of closed SharePoint web parts, I dug up the following “nice one” trick : just add ?contents=1 to the URL of any web part page and it will render a checkbox multi-select list of web parts where you can Reset or Delete one or more web parts in a single go:

delete closed web part Delete Closed Web Part SharePoint 2010 SharePoint 2010 web parts sharepoint 2010 blog

Read More

Delete All Items from a SharePoint List – PowerShell

In experimenting with the upper limit thresholds of just how many items you can create in a list, I ran into a little problem in that the web UI went mental and would cause IE to crash (this was with 21,000 list items). Trying to access the files via Webdav was equally non-workable. I needed to get rid of these list items to even be able to roll back the crazy test.

PowerShell to the rescue. Just replace the “http://serverurl” and “ENTER LIST NAME HERE” values with your web URL and List Name.

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

# "Enter your site URL here"
$SITEURL = "http://serverurl"

$site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
$web = $site.OpenWeb()
"Web is : " + $web.Title

# Enter name of the List below
$oList = $web.Lists["ENTER LIST NAME HERE"];

"List is :" + $oList.Title + " with item count " + $oList.ItemCount

$collListItems = $oList.Items;
$count = $collListItems.Count - 1

for($intIndex = $count; $intIndex -gt -1; $intIndex--)
{
        "Deleting : " + $intIndex
        $collListItems.Delete($intIndex);
}

Note that the assembly references at the top refer to SharePoint 2007 assemblies – not to worry, settings in the out-of-the-box SP 2010 Web.config will automagically bump up the references to the current SharePoint 2010 versions – there’s no burning need to go around adjusting assembly references if you come across PoweShell examples like this.

Read More

SharePoint Filter List / Library by Querystring

If you need to filter a list / library, but don’t want to have to make new View .ASPX files, it’s a simple but effective thing to know that standard Views accepts querystring filter values. So can you put in filter/order/etc. values directly into the URL to accomplish your goal. You could always batch create Views using PowerShell with a technique like the one described here, however if you want to keep things in one simple view then go with the query string approach.

http://go.mysharepoint.com/SiteName/LibraryName/Forms/ChangeLogMergeView.aspx?FilterField1=MyColumn&FilterValue1=Custom Value

You’ll need the following querystring values:

FilterField1 (first filter, column to filter by)
FilterValue1 (first filters, the string you want to filter by)

If you have multiple clauses to filter by, just add another pair of FilterField1 / FilterValue2 pairs, and increment by one, so:

http://go.mysharepoint.com/SiteName/LibraryName/Forms/ChangeLogMergeView.aspx?FilterField1=MyColumn&FilterValue1=Custom Value&FilterField2=MyOtherColumn&FilterValue2=Another Custom Value

The one to watch out for is the FilterField which is looking for the CAML Query-style name of the field. So if you wanted to filter by a field name that has spaces in it, you need to replace the spaces with _x0020_  (which represents a space character). So “Date Modified” becomes:

&FilterField1=Date_x0020_Modified

Read More

Nintex – Invalid – May Refer to a Nonexistent File or Folder

If you try to publish a Nintex Workflow and get the following error, check your SharePoint transaction logs – they may have run out of disk space.​

“The URL ‘{file reference.xml}’ is invalid. It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current web.”

27 02 2012 2 09 44 PM Nintex   Invalid   May Refer to a Nonexistent File or Folder SharePoint 2010 sharepoint 2010 blog nintex logs errors

Read More

Hide / Remove Quick Launch, Main Menu, Ribbon Bar SharePoint 2010

SharePoint 2010 introduced some more context-aware UI treats.

In case you need to write a new ASPX which you want to display as popup, or you just need it stripped down with less bells and whistles, just add a query string value to the URL references.

Same default.master, just that SP 2010 allows you to hide left navigation (quick launch), main menu, social widgets, welcome menu and top bar just by adding the Querystring parameter ?IsDlg=1 to the URL. Of course if there is already a base ?parameter on the URL you need to minimize, just add &IsDlg=1 to the end of the URL instead.

i.e. http://intranet.contoso.com/_layouts/create.aspx?IsDlg=1

or

http://intranet.contoso.com/_layouts/create.aspx?SomeExistingParameter=foo&IsDlg=1

Read More

Version History in SharePoint via SQL

Recently I posted about how to get check-in comments with Nintex via MS SQL – turns out there was a bit more complexity involved in the structure of the version history then first thought (surprise surprise). Below is the stored procedure created to reliably extract the highest MAJOR version of a SharePoint document. So, if a document is currently v5.4 in your SharePoint library, this will grab the 5.0 version:

USE [MySharePoint_Content_DB]
GO
/****** Object:  StoredProcedure [dbo].[proc_GetDocVersion]    Script Date: 02/17/2012 13:37:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_GetDocVersion](
@LeafName nvarchar(260)
)
AS
SET NOCOUNT ON

SELECT TOP 1 x.UIVersion FROM (

SELECT
AllDocVersions.UIVersion
AS UIVersion
FROM
AllDocVersions
JOIN AllDocs ON AllDocs.[ID]= AllDocVersions.[ID]
WHERE
AllDocs.LeafName = @LeafName
AND ((CONVERT([nvarchar],AllDocVersions.UIVersion/(512),0)+'.')+ CONVERT([nvarchar],AllDocVersions.UIVersion%(512),0)) LIKE '%.0'
UNION ALL
SELECT
AllDocs.UIVersion
As UIVersion
FROM
AllDocs
WHERE
AllDocs.LeafName = @LeafName
AND ((CONVERT([nvarchar],AllDocs.UIVersion/(512),0)+'.')+ CONVERT([nvarchar],AllDocs.UIVersion%(512),0)) LIKE '%.0'

) x
ORDER BY UIVersion Desc;

Accessing the SQL DB in SharePoint 2010 directly (as opposed to using the SharePoint API’s etc.) is generally considered a cowboy maneuver and can get in you in lot’s of trouble with inconsistent results as well as performance hits. Use this SQL at your own risk, if not as just a means to better understand the plumbing that goes on in the basement of SharePoint.

Additionally, note that if you are accessing version history via the /vti_history// method, there are some major caveats as described in the following (note it’s referring to SP 2007 which uses single-digit version numbers but the description of the potential run-on situation still applies): http://blogs.msdn.com/b/roberthorvick/archive/2007/01/04/wss-rant-linking-to-the-latest-version-of-a-sharepoint-document-considered-harmful-lessons-6-and-7.aspx

Read More

Business Hours in Nintex Workflows

In Nintex Workflows you can define when the workflow will execute in the context of the the business entities “working hours”.

sitesettings Business Hours in Nintex Workflows SharePoint 2010 workflow sharepoint 2010 blog nintex

When refering to business hours, these are the hours of operation defined in Site Settings > Regional Settings of the site where the Nintex Workflow resides. You can also set your public holidays which can be included through Site Settings > Manage Holidays

Also – a special tip – (thanks Colin for clarity) -  although the Pause Workflow action can be set to 1 minute in it’s settings, it will actually never execute in less than 5 intervals as it is dependent on the SharePoint time job. Important to remember as you may be wondering why your workflow takes ages to finish if you try and insert <5 minute intervals. It is actually 5 minutes + the duration of the workflow sequence + the minute interval you selected.

Read More

Create a List View with PowerShell

1. Grab the GUID of the List. Simple way to do it is to go your existing List you want to create the view in, click the “Create View” button (but don’t actually create it in the UI) and copy the value of the ListID querystring variable. You then need to clean it up a bit. For example, take the bold portion of the following URL:

/site/_layouts/ViewType.aspx?List=<strong>%7B8DF8879E%2D5046%2D406D%2DBCBD%2D50C4777AF50D%7D</strong>&Source=http%3A%2F%2Fmy%2Eitgroove%2Enet%2Fsite%2FMyList%2FForms%2FAllItems%2Easpx

Take the extracted string and delete the portions in red, which are the first and last three characters (which are the HTML encoded characters { and } respectively), and replace the instances of %2D in green (HTML encoded characters to indicate a blank space) with a single blank space .

%7B8DF8879E%2D5046%2D406D%2DBCBD%2D50C4777AF50D%7D

So we are left with the string 8DF8879E 5046 BCBD 50C4777AF50D , which is a properly formatted GUID and is your List ID.

2. Plunk the following script into a new text file called CreateListView.ps1 and put it on your SharePoint server:

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=1"4.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null
# reading command line arguments
$siteURL = $args[0]
$strViewName = $args[1]
$ListGUID = $args[2]
# enter your CAML query for the view here...
$strQuery = "0"
# create a new SPsite object and recursively go through all webs
# until a matching list GUID is found
$site=new-object Microsoft.SharePoint.SPSite($siteURL)
foreach ($web in $site.AllWebs)
{
foreach ($list in $web.Lists)
{
$ListTempGUID = $list.ID.ToString()
if ($ListTempGUID.Contains($ListGUID))
{
write-host "************"
write-host "Match has been found. Preparing to create a view: ", $strViewName
write-host "List Title: ", $list.Title
write-host "List GUID: ", $list.ID
$fields = $list.Views["All Items"].ViewFields.ToStringCollection()
$result = $list.Views.Add($strViewName, $fields, $strQuery, 100, $True, $False , "HTML", $False)
write-host "View ", $strViewName , " was created successfully."
break
}
}
}
write-host "Done."
$site.Dispose();

3. To execute the PowerShell, go to your PowerShell command line and execute the following. Note that you need to replace the following sections in green:

- “your_site_collection_URL” with the URL of your site collection e.g. “http://my.itgroove.net/sitecollectionname”
- the “TestView” with your new list name
- the ListID GUID with the List GUID we just extracted

powershell CreateListView.ps1 “your_site_collection_URL” “TestView” “List GUID 8DF8879E 5046 406D BCBD 50C4777AF50D

Read More
Page 2 of 512345