Tag Archives | SharePoint

My upgrade of SharePoint 2007 to 2010 “script”

One of my most recent projects was the migration of our intranet from SharePoint 2007 to 2010. Since we were going to change the name of the site, I was able to run through this “script” several times as practice to make sure I had everything correct.

I decided to do a detach and attach method. Here are some of the things we did.

  1. We preformed several test a detach and attach upgrades with the new URL. This allowed us to test everything using the new url, and make changes back in the original 2007 site so that it would work once we performed the final live cutover.
  2. All new code/pages/hacks were added to the 2010 site into New documents libraries. These were backed up using this script and restored after every new test detach an attach test. This way all new code would be in place with the final live cutover.
  3. Since we were doing a new Navigation, we created the navigation in the old 2007 site, and hid them by audience. Then one of the steps below is to change the audience which would un-hide the new navigation in the final cutover.

Step 1. Backup all the new code/pages/hacks that have been added to the new site that needs to be restored.

$folderDate=$(get-date -uformat "%Y-%m-%d")
$folderHour=$(get-date -uformat "%H")
$backupDir="\\Path\To\Backup\$folderDate\$folderHour"

foreach ($web in $(Get-SPSite | Get-SPWeb)){
    foreach ($list in $web.Lists) {
    mkdir -force "$backupDir\$($Web.Title.replace(' ','').replace('/','-'))\"
    Export-SPWeb $($web.Url) -itemurl "$($list.RootFolder.ServerRelativeUrl)" -path "$backupDir\$($Web.Title.replace(' ','').replace('/','-'))\$($list.Title.replace(' ','').replace('/','-')).cmp"
    }
}

Now we have captured all the changes that were made to the new site (which we will be restoring after the next cutover test)

Step 2. Remove the previous test cutover site

Remove-SPWebApplication "SharePoint - intranet.company.com80" -RemoveContentDatabases -DeleteIISSite

Step 3. Re-create new app and apppool.

New-SPWebApplication -Name "SharePoint - intranet.company.com80" -Port 80 -HostHeader intranet.company.com -URL "http://intranet.company.com" -ApplicationPool "SharePoint - intranet.company.com80"

Step 4. remove the content database that is created by default

Get-SPContentDatabase -WebApplication "SharePoint - intranet.company.com80" | Remove-SPContentDatabase

Step 5. Backup 2007 site to a share and restore to new SQL server (or new db name on existing SQL server).

Backup:

$SRCSQLSERVER='OldSQLServer'
$DESTSQLSERVER='NewSQLServer'
$sqlcmdBackup="BACKUP DATABASE [Content_Intranet] TO DISK = N'\\path\to\network\share\Content_Intranet.bak' WITH NOFORMAT, NOINIT,  NAME = N'Content_Intranet FullBackup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10"
invoke-sqlcmd -query "$sqlcmdBackup" -Server $SRCSQLSERVER -QueryTimeout 1200

Restore:

$sqlcmdRestore="RESTORE DATABASE [Content_Intranet] FROM  DISK = N'\\path\to\network\share\Content_Intranet.bak' WITH  FILE = 1,  MOVE N'Content_Intranet' TO N'K:\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Content_Intranet.mdf',  MOVE N'Content_Intranet_log' TO N'K:\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Content_Intranet_log.LDF',  NOUNLOAD,  REPLACE,  STATS = 10"
invoke-sqlcmd -query "$sqlcmdRestore" -Server $DESTSQLSERVER -QueryTimeout 1200

Step 6. Mount the restored database and upgrade the uner experience.

Mount-SPContentDatabase -Name Content_Intranet  -DatabaseServer NewSQLServer -WebApplication http://intranet.company.com -Updateuserexperience

Step 7. Re-import exported Document Libraries that contain the new code/pages/apps

Import-SPWeb http://intranet.company.com -Path \\path\to\network\share\date\hour\LibraryName.cmp

Step 8. Clean up navigation by changing audience, change homepage to new page in restored Document Libraries.

Step 9. Alter web.config for Cisco WebVPN

Step 9. Allow inline PDFs

That was it. I did it several times, and it ended up being a smooth cutover.

How to hide a field in a SharePoint EditForm.aspx page, append a replica, add a jQuery autocomplete, and put the selected value in the original field.

If you look at this old post, you can see a technique that I used to hide a form field, and then append read-only data after it. I wanted to use this technique to hide a field in a form, append a replica with a jQuery autocomplete, and based on the selected value from the drop down, put the value in the original filed. I actually wanted a comma separated concatenation of all the selected values (multiple lookups). For example, I wanted to create a form to capture all the people at a meeting, the the attendees field would be hidden and replaced with a input box that can lookup contact GUIDs from a CRM, and once the contact is selected, the GUID is appended to the contents of the original Attendees field.

First up, the code to hide the field I want:

	attendeesRow='<tr id="attendeesRow"> \
		<td nowrap="true" valign="top" width="190px" class="ms-formlabel"><h3 class="ms-standardheader"><nobr>Attendee<nobr></h3></td> \
		<td valign="top" class="ms-formbody" width="400px"> \
		<div id="AddAttendees"><input type="text" id="AddAttendeesSearchTextbox" /> (add an EXISTING CRM Contact)</div><br/> \
		</td></tr>';
	$('nobr:contains("Attendees")').closest('tr').hide();
	$('nobr:contains("Attendees")').closest('tr').before(attendeesRow);

Lines 1-5 is the code for the new replica field
Line 6 hides the existing field
Line 7 prepends the new replicate created in Lines 1-5

Next is the jQuery code to attach an autocomplete to the new text box (AddAttendeesSearchTextbox). I am using a little knockout to organize my code and I use some of the observable arrays to make the page more dynamic.

$('#AddAttendeesSearchTextbox).autocomplete({
	    source: function (request, response) { VM.contactsSearchSourceREST(request, response) },
		delay: 600,
		minLength: 3,
		select: function(event, ui) {
			var selectedObj = ui.item;
			VM.addAttendee(selectedObj.fullname,"","",selectedObj.ParentCustomerIdName,"5",selectedObj.id)
			$(this).val("");
			return false;
		}
	});

And here is the javascript code (part of the view model) that is used for the source of the jQuery AutoComplete (CRM 2011 oData REST endpoint). Just a simple ajax call to CRM 2011.

	self.contactsSearchSourceREST = function (request, response) {
	    var serverUrl = "crm.server.com"
	    var ODATA_ENDPOINT = "/ORGNAME/XRMServices/2011/OrganizationData.svc";
	    var ODATA_EntityCollection = "/ContactSet";
	    var strSelect = "$select=FullName,ParentCustomerId,ContactId"
	    var strFilter = "$filter=substringof('" + request.term + "',FullName) and StateCode/Value eq 0"
	    var URL = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "?" + strFilter + "&" + strSelect
	    //alert(URL);
	    $.ajax({
	        type: "GET",
	        contentType: "application/json",
	        datatype: "json",
	        async: false,
	        url: URL,
	        beforeSend: function (XMLHttpRequest) {
	            XMLHttpRequest.setRequestHeader("Accept", "application/json");
	            XMLHttpRequest.setRequestHeader("Content-Type", "application/json")
	        },
	        success: function (data, textStatus, XmlHttpRequest) {
	            response($.map(data.d.results, function (item) {
	                return {
	                    label: item.FullName + ' (' + item.ParentCustomerId["Name"] + ')',
	                    value: item.FullName + ' (' + item.ParentCustomerId["Name"] + ')',
	                    fullname: item.FullName,
	                    ParentCustomerIdName: item.ParentCustomerId["Name"],
	                    id: item.ContactId
	                }
	            }));
	        },
	        error: function (XMLHttpRequest, textStatus, errorThrown) {
	            alert("failure " + errorThrown);
	            return false;
	        }
	    });
	}

Next is the knockout code (part of the view model) that is used to push the new contact guid into an observable array upon selecting the AutoCompleted contact

    self.Attendees = ko.observableArray();
    self.contact = function(fullname, firstname, lastname,ParentCustomerIdName, activitypartytype, guid) {
	this.fullname = fullname;
	this.firstname = firstname;
	this.lastname = lastname;
	this.ParentCustomerIdName = ParentCustomerIdName;
	this.role = activitypartytype;
	this.guid = guid;
    };
    self.addAttendee = function(fullname, firstname, lastname,ParentCustomerIdName, activitypartytype, guid) {
        self.Attendees.push(new self.contact(fullname, firstname, lastname,ParentCustomerIdName, activitypartytype, guid));
        return
    };

And finally the knockout code to concatenate the GUIDs and put them in the hidden (original) field (Attendees).

    ko.utils.arrayForEach(self.Attendees(), function(contact) {
        total = total + contact.guid + ';'
    	});
    total = total.substring(0, total.length - 1);
    $('input[type=text][title="Attendees"]').val(total)
    return total
	});

Pretty complex, lots of different techniques bing used (knockout, jQuery, ajax). Hope it makes sense.

SharePoint 2010, CSOM and External Lists – must use LoadQuery

I was working on some JavaScript code to pull data from an External List that was pointing to a Microsoft CRM 2011 database. The code was being used to populate a jQuery autocomplete like this post. In that post you can see on line 10, I use the “load” method. This worked, but if I started a new query before the previous one ended, a javascript error was thrown. I am sorry I don’t recall the error – I am blogging this a month or so after I figured it out.

It took me a while, but I found one reference to figure out the issue. It is on page 143 of Scott Hillier’s book “Professional Business Connectivity Services in SharePoint 2010” (I found it via the google query “loadquery external list”)

The work around was that you have to use LoadQuery with External lists, Load is not supported. Not sure where this is documented, but it took me quite a while to figure that one out.

Hope that helps some one?

Using Nivo slider, knockout.js and SharePoint CSOM to create an announcements Slider

I wanted to create a slider that contains images and items from an announcements in my SharePoint 2010 home page. I started writing my own slider, but realized I was just re-creating the wheel. I ended up finding Nivo Slider. It seemed well supported and clean, so I went with that as my jQuery slider. Let’s dive into the code:

First, here is the HTML code I put on the home page. I just added a CEWP and linked it to a text file in a document library. This is the contents of the text file:

<div class="slider-wrapper theme-default">
    <div id="slider" class="nivoSlider">
        <img src="/PhotoLibrary/cityscape1.jpg" title="#htmlcaption" />
        <img src="/PhotoLibrary/cityscape2.jpg" title="#htmlcaption" />
        <img src="/PhotoLibrary/cityscape3.jpg" title="#htmlcaption" />
        <img src="/PhotoLibrary/cityscape4.jpg" title="#htmlcaption" />
    </div>
    <div id="htmlcaption" class="nivo-html-caption">
	<span data-bind="html: sliderCurrentTitle" style="font-weight:bold;text-decoration:underline;"></span>
	<span data-bind="html: sliderCurrentSummary" ></span>
    </div>
</div>

This interesting parts are lines 9 & 10. I set these two spans to Knockout observable arrays. When the slide changes, I am going to update the contents of these values

And here is the JavaScript document.ready code. Explanation of the code is below the block.

$(document).ready(function () {
    $('#slider').nivoSlider({
        effect: 'sliceDownRight',
        pauseTime: 4000,
        beforeChange: function () {
            VM.sliderNextItem()
        }
    });
ko.applyBindings(VM);
VM.sliderRetrieveAnnouncments();
var VM = new viewModel();
})

Lines 2-8: are the settings for the Nivo Slider.
Line 6: This is the most important part of this part of the code. This calls the function for get the next announcement when the slide changes.
Line 10: This line calls the function that initially loads all the announcements into a JavaScript object.

Here is the code to my Knockout View Model (explanations below):

function viewModel() {
    var self = this;
    self.sliderAnnouncement = function (title, summary) {
        this.title = title;
        this.summary = summary;
    }
    self.sliderAllAnnouncments = ko.observableArray();
    self.sliderCurrentTitle = ko.observable();
    self.sliderCurrentSummary = ko.observable()
    self.sliderCurrentItemIndex = 0
    self.sliderNextItem = function () {
        self.sliderCurrentTitle(self.sliderAllAnnouncments()[self.sliderCurrentItemIndex].title)
        self.sliderCurrentSummary(self.sliderAllAnnouncments()[self.sliderCurrentItemIndex].summary)
        self.sliderCurrentItemIndex++
        if (self.sliderCurrentItemIndex > self.sliderAllAnnouncments().length - 1) {
            self.sliderCurrentItemIndex = 0
        }
    }
    self.sliderRetrieveAnnouncments = function () {
        var clientContext = SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><Query><Where><And><IsNotNull><FieldRef Name='Title' /></IsNotNull><Gt><FieldRef Name='Expires' /><Value Type='DateTime'><Today/></Value></Gt></And></Where><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query></View>");
        var collListItem = oList.getItems(camlQuery);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(
	    	Function.createDelegate(this, function () {
	    	    var listItemInfo = '';
	    	    var listItemEnumerator = collListItem.getEnumerator();
	    	    while (listItemEnumerator.moveNext()) {
	    	        var oListItem = listItemEnumerator.get_current();
	    	        listItemInfo +=
					'\n' + oListItem.get_item('Title') +
			    	'\n' + oListItem.get_item('Summary');
	    	        self.sliderAllAnnouncments.push(new self.sliderAnnouncement(oListItem.get_item('Title'), oListItem.get_item('Summary')));
	    	    }
	    	    self.sliderNextItem()
	    	}),
	    	Function.createDelegate(this, function () { alert('There was an error - sliderRetrieveAnnouncments') }));
    }
}

Lines 3-6 this is the announcement object that I will use to hold the info of a single announcement
Lines 7-9: this is the observable items that are displayed on the slider that contain the announcement’s title and summary
Line 10: this is the index of the current announcement that is being displayed. All I am doing is incrementing it with the NextItem function
Lines 11-18: This is fired when the slide changes (a builtin hook of the Nivo slider). Once it has changed the item, it increments for the next slide.
Lines 19-40: This is the CSOM query to retrieve all the items from the announcement list that have not expired.
Line 23: This is CAML query to get the items that have not expired.
Line 26: This line makes the query.
Lines 30-36: This code loops through the successful returned items.
Line 35: This line puts each of the items into observable array that is used to house all the announcements.

I hope this is helpful to some one. I have been pretty happy with the outcome.

Update: I saw this slider in action at SharePoint conference: http://corporatenewsapp.codeplex.com/
Looked pretty sweet. May have to try to backport to SharePoint 2010.

Problems with SharePoint 2010 menus and javascript using a Cisco WebVPN (ASA)

We noticed that the SharePoint 2010 menus were not working with our Cisco ASA’s WebVPN. If the top level menu had children, they would not show on hover. Then we started noticing that all jQuery based functions stopped working. It seemed that much of the Javascript used with SharePoint 2010 would not work with our ASA. The fix was to add this to the web.config for the SharePoint site:

 <system.web.extensions>
     <scripting>
           <scriptResourceHandler enableCompression="false" enableCaching="true" />
     </scripting>
</system.web.extensions>

Obviously you are adding the scriptResourceHandler to an exiting scripting section and not replacing what is already there.

Looping through a SharePoint List Column with jQuery and replacing a GUID with a name from CRM 2011

This is a very specialized piece of code, but it came together nicely, so I thought I would share it.

I have a SharePoint List that has a bunch of Microsoft CRM 2011 Contact GUIDs in it. Some columns have one GUID and others have multiple GUIDs separated by semicolons. My goal was: when a user visits the default view for this list, the GUIDs are looked up agains CRM and displayed as the contact’s full name. I wrote the following code to do just that. The 4th, 5th and 10th columns has guide in them. I use this method to loop through the column.

$('table.ms-listviewtable td:nth-child(4),table.ms-listviewtable td:nth-child(5),table.ms-listviewtable td:nth-child(10)').each(function () {
        var guids = $(this).text().split(";");
        var names = ''
        $.each(guids, function () {
            var guid = this;
            var serverUrl = "http://crmserver.company.com"
            var ODATA_ENDPOINT = "/Organization/XRMServices/2011/OrganizationData.svc";
            var ODATA_EntityCollection = "/ContactSet(guid'" + guid + "')";
            var URL = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection
            $.ajax({
                type: "GET",
                contentType: "application/json",
                datatype: "json",
                async: false,
                url: URL,
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    XMLHttpRequest.setRequestHeader("Content-Type", "application/json")
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    names = names + data.d.FullName + ","
                }
            });
        });
        $(this).text(names.substring(0, names.length - 1));
    });

Line 1: is the jQuery selector for all the columns that have GUIDs. And we loop through each of them.
Line 2: splits the contents of the column.
Line 4: loops through the all the GUIDs in each row/column
Lines 5-9: are setting up the CRM 2011 REST url for the ajax call
Lines 10-24: query the Microsoft CRM 2011 rest endpoint with the contact’s GUID and assign the full name to a variable
Line 25: displays the full name instead of the GUID.

Some slim code that works pretty well.

Using jQuery to hide some columns, append a new column, and popup the contents of the hidden columns

In this previous post, I showed how to hide the 4th and 5th columns of a SharePoint List (I am not talking about EditForm.aspx page, I am talking about the table view). I took this a step further and appended a new row containing an “more info” onClick event that pops up the contents of the hidden columns.

$('td:nth-child(5),th:nth-child(5),td:nth-child(6),th:nth-child(6)').hide()
$('td:nth-child(4)').each(function(){
	$(this).after('<td><img id="MoreInfo" src="/_layouts/images/CNSINF16.GIF" /></td>');
});
$('td.ms-addnew').hide();
$('tr.ms-itmhover').removeClass('ms-itmhover');
$('a[href^="mailto:"]').contents().unwrap();
$('img#MoreInfo').click(function() {
  var notes = $(this).closest('td').next('td').text();
  var description = $(this).closest('td').next('td').next('td').text();
  $('<div><u>Notes</u>: ' + notes+ '<br/><u>Description</u>: '+description +'</div>').dialog()
  });
});

Line 1: hides the 4th and 5th columns
Lines 2 & 3: append a new columns with a clickable gif
Lines 5 & 6: hide the add new and the hoverovers for the rows
Line 7: removes the mailto(s)
Lines 8 – 11: is the onClick for the gif in line 3. This function takes the values of the next two rows and put them in a jQuery modal dialog.

That was fun.

Using _spPageContextInfo, AJAX and SAMAccountName to show a hidden item in a SharePoint page.

I wanted to have a link on a page (could be anything) show only for certain people. I knew there was variable on every page named _spPageContextInfo.userId, which is the current user’s SharePoint user Id. I used the following code to take that userId and query the User Information List to get the SAMAccountName, and then use jQuery to show a hidden link if the use name matches.

    var userId = _spPageContextInfo.userId;
    var SAMAccountName = ''
    var serverUrl = "/_vti_bin/listdata.svc/UserInformationList(" + userId + ")"

    var URL = serverUrl
    $.ajax({
        type: "GET",
        contentType: "application/json",
        datatype: "json",
        async: false,
        url: URL,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            XMLHttpRequest.setRequestHeader("Content-Type", "application/json")
        },
        success: function (data, textStatus, XmlHttpRequest) {
            SAMAccountName = data.d.UserName
        }
    });
    if (SAMAccountName.toLowerCase() === 'UserName1'
        || SAMAccountName.toLowerCase() === 'UserName2'
        || SAMAccountName.toLowerCase() === 'UserName3'
        || SAMAccountName.toLowerCase() === 'UserName4'
        ) {
        $('#HiddenId').show()
    }

Looping through a SharePoint List column and acting on each item in the column using jQuery

I wanted to loop through a couple columns in the Default View of a SharePoint List. The jQuery code below would loop through the 4th, 5th, and 10th columns and alert the contents of that column. Obviously you can do anything you like with the matches. More tomorrow on how I was using this method

$('table.ms-listviewtable td:nth-child(4),table.ms-listviewtable td:nth-child(5),table.ms-listviewtable td:nth-child(10)').each(function () {

alert($(this).Text())
}