SharePoint 2013-Printing List Item Forms using jQuery and CSS

Author

Rod Stagg

* Add a print button to a SharePoint list item form.

* Displays a print icon linked to the custom print preview form.

* Tracks which list items were printed by the user. Works on both Office 365 and on-premises versions of SharePoint 2013.

printfeature

Capture

Solution Details

Solution designed to meet a requirement from a customer to allow users to easily print a list item from the primary SharePoint list view page in a layout that maximized the allowable printing real-estate while also removing most of the SharePoint toolbars etc. from the printed page.  Also, the customer requested that we track which items had been printed since this solution was part of a larger scheduling solution for SharePoint.   Since the customer is hosting their SharePoint on Office 365 in the cloud we opted to use jQuery and CSS directly on the list item form.  For layout we opted to use a custom list item display form and modify the XSL although this is not necessary to support the jQuery and CSS for printing the list item.

Steps: 

  • jQuery added to list item form with embedded jQuery and CSS overrides in a script editor web-part.
  • Calculated field with a print icon and link to list item form added to the list view.
  • Optional: Customized list item form layout using XSL.

Getting started…

Configure a SharePoint custom list:

  1. Create a SharePoint custom list and add some fields and items.
  2. Create a calculated field named “Print” for the print icon and link and add to the list.  Set the data-type to currency.
  3. Create a field named “Printed”.  Set the data-type to text and add to the list.  This field will be updated when the user selects the print button.

Example calculated field syntax:

=”<a class=’printitem’ href=”&”‘”&”http://mysharepoint.com/Lists/Schedule/print.aspx?ID=”&ID&”‘”&”><img src=”&”‘”&”http://mysharepoint/SiteAssets/Images/print-icon-2.jpg”&”‘”&”></img></a>&#8221;

*Remove the trailing &#8221; for some reason getting added by WordPress

Upload the print icon to a image library.  Update the image source in the Print calculated field if necessary to point to the image location.

Configure the SharePoint list item form:

  1. Place the list item into edit mode. Then from the list item page select edit page.
  2. Add a script editor web-part to the form (located in the media and content category in the gallery) to store the jQuery and CSS.
  3. Insert the jQuery and CSS for adding the print button(s), updating the list item when the print button was pressed, and opening the browser print preview window.
  4. Choose “Stop Editing” to save the form.

HINT: If you require re-ordering the fields, customizing the layout or formatting of individual fields use SharePoint Designer 2013 to create a custom display list item form on the SharePoint list in question.  This will allow you to customize the XSL of the list item form and create 2 or 3 column layouts etc.

Example jQuery/CSS 

<script src=”//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js” type=”text/javascript”></script>
<script type=”text/javascript” src=”/_layouts/15/sp.runtime.js”></script>
<script type=”text/javascript”  src=”/_layouts/15/sp.js”></script>
<script type=”text/javascript”>

// Program flow starts here.
var siteUrl = “SHAREPOINTSITEURL”;

//Function to update the list item printed field when user selects print button
//Accepts the list item id as a parameter that is obtained from the query string

function updateListItem(printListItemId) {

var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle(‘LISTNAME’);
//var oListItemId = getQueryStringParameter(“ID”) ;
var oListItemId = printListItemId;

this.oListItem = oList.getItemById(oListItemId);
oListItem.set_item(‘Printed’, ‘Yes’);
oListItem.update();

clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
//alert(‘Item updated!’);
}

function onQueryFailed(sender, args) {
//alert(‘Request failed. ‘ + args.get_message() +
// ‘\n’ + args.get_stackTrace());
}

// Function to retrieve a query string value for the list item id
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split(“?”)[1].split(“&”);
var strParams = “”;
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split(“=”);
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}

</script>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&#8221; type=”text/javascript”></script>

<script>

$(document).ready(function() {

//Hide some fields we don’t want displayed on the printed page

$(“#printedItemId”).hide();
$(“#printedItemLabelId”).hide();

//Hide some built-in SharePoint O365 toolbars etc. we don’t want on the printed page

$(“.ms-descriptiontext”).hide();
$(“.ms-core-suiteLink”).hide();
$(“.ms-toolbar”).hide();
$(“.ms-core-deltaSuiteLinks”).hide();
$(“#suiteBarRight”).hide();

//Handle button click

$(‘.printMe’).click(function() {
$(“#printedId”).text(“Yes”);
$(“.printMe”).hide();
$(“.printMeDraft”).hide();

//obtains listitem id from a field place on the form

//in cases where the list item ID field is not reliable when passed in the querystring from the list created a simple SharePoint 2013 workflow to populate this field when items are added to the list

var printListItemId = $(“#printedItemId”).text();

//Update list item

updateListItem(printListItemId);

//Open browser print preview

window.print(); return false;

});

//Hide buttons to remove them from printed page

$(‘.printMeDraft’).click(function() {
$(“.printMeDraft”).hide();
$(“.printMe”).hide();

//Hide buttons to remove them from printed page

$(“#printedItemId”).hide();
$(“#printedItemLabelId”).hide();
window.print(); return false;

});

});

</script>

//CSS Styles
<style>
.printMe{
color:#666666;
font-weight:bold;
cursor:pointer;
min-width:150px;
}

.printMe:hover{
color:#333333;
font-weight:bold;
cursor:pointer;
}

printMeDraft{
color:#666666;
font-weight:bold;
cursor:pointer;
min-width:150px;
}

.printMeDraft:hover{
color:#333333;
font-weight:bold;
cursor:pointer;
}

.ms-standardheader{
font-size: 13px;

}

.ms-formbody{
font-size: 13px;

}

.ms-formlabel{
font-size: 13px;

}

</script>

</style>

<button class=”printMe”>Print for Crew</button>
<button class=”printMeDraft”>Draft Print</button>

Next Steps:

Package as a SharePoint app that can be added to any site.
Create a custom print template.
Incorporate PDF.

Summary

Even in 2013 it is sometimes necessary to print to paper.  With SharePoint being used more and more for scheduling and tracking systems, workflows, and calendaring the ability to print a SharePoint list item when necessary is an added benefit.  With the advent of CSOM and JSOM developers are increasingly taking advantage of jQuery, HTML, and CSS to tackle specific gaps in the OOB SharePoint features and particularly in the O365 cloud version.

Have fun!

Rod.

Posted in Javascript, jQuery, Office 365, Sharepoint, SharePoint 2013

Office 365 Branding-Creating a custom masterpage for your Office 365 SharePoint Public-Facing website

In SharePoint 2013, both on-premises and Office 365 brought new options for customizing your SharePoint’s site design.

Highlights:

  • Ability to edit your masterpage in the HTML editor of your choice i.e. Dreamweaver, Visual Studio, or SharePoint Designer 2013.
  • Ability to configure the basic colors of your site from a single theme file.  (Replacing the PowerPoint themes in SP2010)

These two options alone provide a more flexible and straight-forward mechanism for branding your SharePoint 2013 site.

Example screenshot:

ScreenShot

Step 1: Login to your Office 365 tenant:

Login into your Office 365 SharePoint
TIP: Ensure to select the “Keep me signed in” option on your login screen.

Capture

Step 2: Obtain the location of your masterpage files:

  • Navigate to your SharePoint site’s masterpage gallery:
  • Site Settings > Look & Feel > Design Manager
  • From left navigation > Create Themes
  • Locate and copy the path provided by Microsoft for managing your design files for your site: “Map the following location as a network drive: [your path]“

Step 3: Create a shortcut to (map) a network drive to your masterpage gallery:

Instructions for Windows 8: http://windows.microsoft.com/en-us/windows-8/create-shortcut-to-map-network-drive

When you create a shortcut  to a shared folder or PC on a network (also called mapping a network drive), you can get to it from Computer or File Explorer without having to look for it or enter its network address each time.

To create a shortcut to a network drive

  1. Open Computer by swiping in from the right edge of the screen, tapping Search (or if you’re using a mouse, pointing to the upper-right corner of the screen, moving the mouse pointer down, and then clicking Search), entering Computer in the search box, tapping or clicking Apps, and then tapping or clicking Computer.
  2. In the Menu bar, tap or click Computer, and then tap or click Map network drive.
  3. In the Drive list, tap or click a drive letter.You can choose any  available letter.
  4. In the Folder box, enter the path of the folder or computer, or tap or click Browse to find the folder or computer.To connect every time you sign in to your computer, select the Reconnect at sign-in check box.
  5. Tap or click Finish.

Step 4: Edit your masterpage in the web editor of your choice:

From my experience in SharePoint 2013 I prefer to use Visual Studio for editing and saving changes to the masterpage(s).  I have found Dreamweaver to work as well and provides a decent design-time preview and standard features you expect in a web editing tool.

Browse to the mapped drive you created.

TIP: If you receive an error while attempting to open your mapped drive I have found the following to be an acceptable work-around: Navigate to site settings, under Web Designer Galleries choose Masterpage and page layouts link.  Next, from the masterpage and layouts folder, locate the File tab in the ribbon and select “Upload Document” On the upload document screen select the “upload files using Windows Explorer instead”  You should see your masterpage gallery open in windows explorer.

Capture4

Once you have navigated successfully to your network drive containing your design files I recommend creating a new folder on the root masterpage gallery to organize all your design files (masterpage, images, CSS) into a single folder.  Consolidating your custom masterpage files in to a single folder aid in setting virtual paths to your masterpage’s resources and once published provide a visual cue for others to properly assign custom masterpages to thier sites.

  • Make a copy of the Seattle.html or Oslo.html file and rename appropriately i.e. MyCompanyMaster.html.
  • Copy this file into your new custom masterpage folder.
  • Create new subfolders for your masterpage resources i.e. “Images” and “Styles”

Your folder structure may look similiar to this:

Capture5

Right-click the MyCompanyMaster.html file in windows explorer and edit the file in the web editor of your choice.

TIP: Ensure you are always editing the .html version of the masterpage and not the .master version.

Your standard Seattle.html may appear similiar to this:

Capture6

Locate the sections in the masterpage mark-up you would like to alter i.e. add a div for the footer, add or remove snippets, insert HTML markup, link to your custom CSS and image files, etc until the masterpage meets your design requirements.

FYI: In design view SharePoint inserts a commented section highlighting the placeholder for the content that gets rendered on the page at runtime.

TIP: Do not edit any of the built-in SharePoint controls or sections directly, rather navigate to the design manager tool and use the Snippets tool to update properties and then copy the provided mark-up back down to the appropriate section in your masterpage.  This will minimize errors in the Design Manager.

Lessons learned:

The page content area is largely in a div with the id=s4-workspace.

<div id=”s4-workspace”>
<div id=”s4-bodyContainer”>

In the example screenshot above I placed a footer at the bottom of the page that required more flexibility than what appeared the built-in control supported.  To accomplish this I located the correct location in the Seattle masterpage to place a container div proceeding the page content and applied custom CSS styles to ensure the footer always displays below the content of the page.

Example of mark-up changes:
<!–SPM:<SharePoint:ScriptBlock runat=”server”>–>
<!–SPM:var g_Workspace = “s4-workspace”;–>
<!–SPM:</SharePoint:ScriptBlock>–>
<div>
<div class=”grass”>
</div>
<div class=”hills”>
</div>
<div class=”skyline-left”>
</div>
<img style=”position:absolute; bottom:60px; right:0px;” src=”Images/skyline-right.png” alt=”Sound Community Bank” border=”0″ />
</div>
</body>
</html>

Step 5: Saving and previewing your changes on SharePoint:

Saving to SharePoint:

When completed with your edits simply choose save file from your web editor and the changes will be applied to the version in your SharePoint masterpage gallery.  You can preview your masterpage using the Design Manager from Site Settings, Design Manager, Edit masterpages.  If the conversion was successfull your custom masterpage Approval Status will be set to “Draft” and may appear similiar to this:

Previewing on SharePoint:

  • Click on the MyCompanyMaster link to preview your new masterpage.
  • If there are any errors reported with your markup ensure to update the masterpage to correct errors and save.  From my experience the typical errors are isolated to HTML formatting issues i.e. a div tag is missing a closing tag etc.
  • When satisified with the results navigate to the MyCompanyMaster file, select … and publish a major version.  Only published versions will be displayed in the list of available masterpages that can be applied to a site.

Additional options: You do have the option of creating your own HTML layout from scratch and providing you meet some requirements i.e. the mark-up is XML compliant then SharePoint will convert your html to two files, a masterpage.master file and a masterpage.html file.  This option provides significant flexibility to brand your SharePoint similiar to your internet facing website and/or design mockups from your design team.

Helpful links:

How to: Convert an HTML file into a master page in SharePoint Server 2013
http://msdn.microsoft.com/en-us/library/jj822370.aspx

Add snippets to a master page or a page layout in SharePoint Server 2013
http://msdn.microsoft.com/en-us/library/jj822367.aspx

Have fun!

Rod.

Tagged with: , ,
Posted in Office 365, SharePoint 2013

SharePoint 2010 Upgrade Tips and Dreaded User Profile Synchronization Service Stuck on Starting…

SharePoint 2010 Upgrade Tips:

I have been working with SharePoint since way back in 2000 when I started at Microsoft, with every release of the product the upgrade process has been getting easier. If you are upgrading only content databases, no significant customizations are detected, and are not planning on upgrading MySites then upgrading SP2007 to SP2010 is very straight-forward using the database attach method, virtually bullet-proof from  my experience over a multitude of SP2010 upgrades both small and large. If however significant customizations are detected (covering in more detail in subsequent post) have been deployed and/or you are upgrading MySites (focus of this post) then a successful migration requires a solid assessment and planning to limit impact to the business. I always strive to limit the impact of the upgrade on the business keeping the production upgrade in as short of a window as possible: “Everyone leaves on Friday with SP2007 and comes in on Monday with SP2010″:)   To that end sharing a few of the lessons learned during recent SharePoint 2010 upgrades for those of you in the planning stages of an upgrade.  Not a comprehensive guide, for a more comprehensive list of upgrade planning steps the place to start is the SharePoint 2010 Upgrade documentation on TechNet.

Tip #1: Perform Database Attach as the upgrade approach: Database attach is the best upgrade approach providing you put the necessary time into planning the upgrade including planning for several test upgrades particularly if you are upgrading MySites as well. Also provides a viable rollback plan if production upgrade fails-reset the databases to read/write while you address upgrade issues and schedule another pass-live to fight another day:)

Tip #2: Perform Test Upgrades and document results: Always perform test upgrades on a virtual machine in advance of production upgrade to resolve issues and verify a successful upgrade path.

  • Document: Document successful  upgrade path based on test upgrades, including environment variables and PowerShell  scripts with the assumption you could follow step-by-step on production      upgrade. Great documentation to provide IT for future reference as a runbook.
  • Test on production hardware and configuration: Consider a test upgrade pass on the new SP2010 production environment prior to actual production upgrade to identify and address environment variables prior to actual production      upgrade weekend i.e. web part caching issues in production environment  where NLB is configured, web.config modifications, SMTP out-bound and  in-bound email,  Alternate Access Mappings, IIS Bindings, all general configurations. You do not want to address these during actual production upgrade for release!
  • Hint: Plan for available free disk space of 3-times the size of the content database or  user profile database you are planning to upgrade. When upgrading a database exceeding 100GB expect the upgrade process to take some time. I was upgrading a content database of 100GB in one scenario and noticed the upgrade progress stayed at .30% complete for some time, after a duration of 2 hours it eventually upgraded so don’t end the process too soon. Monitor the SharePoint upgrade log file if you suspect it’s taking too long.

Tip #3: Provide adequate time to identify and address customizations:

  • STSADM Pre-Upgrade Checker and PowerShell Test-SPContentDatabase are  required. If you are not familiar with STSADM already then could be rough going:) Overall, being proficient in PowerShell is a pre-requisite skill  for SharePoint 2010 upgrade.
  • Consider how best to deal with the Fab 40 templates and provide ample time if you need  to provide support in SP2010 for existing Fab 40 sites.
  • Determine the need to upgrade InfoPath form administrator templates in Central Administration Form Template Library as these may have to be upgraded manually and there could be custom dlls that need to be migrated as well.
  • Plan for addressing custom applications, services, and custom and/or third-party web-parts.
  • Transfer the customizations into the test upgrade environment and test thoroughly.
  • Consider transferring customizations you plan to keep to production environment prior to actual production upgrade and test against production environment to eliminate environmental variables to address during production upgrade i.e. web part caching issues in environment where NLB is configured, web.config modifications, SMTP out-bound and in-bound email, Alternate Access Mappings, IIS Bindings, and all general configurations.

Tip #4: MySite Upgrades:

  • For MySite upgrades do not forget to create or upgrade the MySite host and set MySite      host URL in Profile Service Application prior to upgrading MySites.
  • Create a new web application to host MySites when possible,  I have found no issues with deploying a new site collection for the MySite host rather than upgrading the SP2007 MySite host with the exception of scenario where the MySite host was originally created in the default web application on port 80. Recommend hosting the MySites site collections as part of a separate web application providing a level of isolation for MySites.
  • Use PowerShell to upgrade MySite SSP and provision UPS application pool etc. Ensure you reference the correct Shared Services Database typically SharedServicesDB etc. rather than the MySite content database when activating User Profile Service Application.

Tip #5: Plan to address the Dreaded User Profile Synchronization Service not starting… You have successfully upgraded your content databases via the recommended database attach upgrade and proceeded to the MySite upgrade process. After completing the upgrade of the profile db following the steps on TechNet to the letter and in preparation had reviewed the UPS Architecture when you advance to the step to configure your profile service application settings i.e. to set the MySite host link SharePoint on the Profile Service Application management link it returns an error page instead of the expected  administration page. Potential cause: the user profile synchronization service is not started.  On more than one occasion I noticed the profile synchronization service was stuck on starting in the manage services administration page for more than 10 minutes after provisioning and activating the UPS and until the service is started you will not be able to access the manage profile service application page.

Resolution: There have been many posts dedicated to resolving the profile sync stuck on starting. Here is one of my favorites http://www.harbar.net/articles/sp2010ups2.aspx that includes significant detail and troubleshooting steps.  TechNet article http://technet.microsoft.com/en-us/library/gg750253.aspx   Recommend reviewing these posts in cases where following the steps I outline below are not successful. There are cases where permissions have not been set properly in AD, NetBIOS issue, or security access issues with the FIM Services themselves that will require access to both SharePoint, SQL, and Active Directory to resolve.  In such cases I involve IT Admin/IT Services team and in some cases contacting Microsoft support. In one case with MS support assistance uncovered changes made to the AD containers were causing synchronization errors.

Quick steps to try before getting too deep into the weeds that has worked for me over the course of several SP2010 Upgrades.

  • Ensure you have installed SharePoint latest SharePoint 2010 cumulative updates http://technet.microsoft.com/en-us/office/sharepointserver/bb735839
  • Ensure the ForeFront Identity Management Services are enabled and set to manual start and configure to run under your service account. DO NOT START YOURSELF-the user profile service will attempt to configure and start these services automatically.
  • Start the Profile Service application from Central Administration (in addition to the Profile Synchronization Service)
  • Reboot the SharePoint server.
  • Verify FIM  services are started. Hint: You can view FIM services in action using the FIM Client located at C:\Program Files\Microsoft Office Servers\14.0\Synchronization Service\UIShell\miisclient.exe
  • Verify the Profile Synchronization Service and User Profile Service status are both reporting as “Started” and no longer “Starting”
  • If the Profile Synchronization Service status is still stuck on starting, try setting the FIM Services to “Automatic-Delayed Start” then Reboot once more.
  • At this point your profile synchronization service status should be reporting as started, review errors in event log, and if successful you will be able to access the Profile Sync Settings page and verify the user profiles have been successfully imported, configure your MySite settings etc.
  • Hint: Do not be shy about deleting the UPS application and re-activating using PowerShell from scratch once more to ensure all configurations are correct.
  • Consider turning off the SMTP service to disable email during user profile upgrade to avoid emails being sent out to Managers from the MySite Cleaner Timer Job.

Summary:

Performing database attach upgrade is a great approach for planning an upgrade that limits the overall impact to the business and provides best roll-back plan. Plan for several test upgrade passes to get to a successful upgrade pass, particularly if upgrading customizations and/or MySites. Document the test results as part of a step-by-step upgrade guide that includes each step, environmental variables i.e. server names, service accounts, database names, general configurations, list of customizations, and accompanying PowerShell scripts will help make the actual production upgrade go smoothly.  Also consider the additional step of performing a test upgrade on the planned production environment to identify and address environmental variables early. Plan out the production upgrade tasks, activities day by day, including all tasks, resources, and estimated time necessary for copying databases from production, estimate for performing database upgrade, and allocated time/resources for performing post-upgrade testing.

Most importantly, bring coffee.

Rod Stagg
SharePoint Practice Manager and Architect http://www.rstagg.com

Tagged with:
Posted in Sharepoint

SharePoint Intelligence Conference Bellevue KeyNote Take Aways

In Bellevue for the conference, key takeaways from keynote.

Self service BI tools are compelling in SharePoint 2010 in conjunction with SharePoint SQL Server 2008 R2 and upcoming SQL Server 2012.
Adoption of SharePoint is being driven by organizatizations seeking a unified Infrastructure reducing impact to IT freeing time for strategic initiatives

LINQ and integrated Voice Messaging worth looking into, shows presence in SharePoint 2010 and an interesting feature in Outlook that summarizes cm in text and search.

Unified Communications offer potential ROI opportunities.

 

Tagged with:
Posted in Business Intelligence, Sharepoint

Tips/Tricks: EndUserSharePoint.com moved on to NothingButSharePoint.com

Mark Miller announced  Dec 10, 2010 the closing of endusersharepoint.com but good news is the new NothingButSharePoint.com launch from Mark Miller, Jeremy Thake, and Joel Oleson with sections for End User, Developer, and IT Pro.

Posted in Sharepoint

This is wrong…so wrong.

Cool pic from http://jalopnik.com/5715603/this-is-why-you-park-your-ferrari-in-a-garage 

Posted in Cars General

Holiday Gift SharePoint to help others during the holidays

Using SharePoint to help others during the holidays

For the past several years, our employees have helped make the holidays very happy for many local children.  Because of thier thoughtfulness and generosity, these children woke up to presents and a wonderful Holiday Season.   Last year you helped a homeless family of six move into an apartment for the holidays – and if that wasn’t enough, fulfilled the kid’s wish lists! 

Again, this year we have a wonderful family who is going through some hard times.  A single mom with four children who works full time but struggles to make ends meet.  Last year, she was only able to get a few gifts for the youngest child.  We thought it be great if we could make this holiday a good one for all of them and knew this family would appreciate any help we can offer.  

This year we have a Holiday Gift SharePoint!

How SharePoint can help:
In previous years we sent out an email similiar to the above.  Thanks to the generousity of our employees many of the gifts came in time for the holidays, some even 2 or 3 times! 

Preventing duplicate gifts:
This year we wondered if we could provide the holidays wish list that could work much like a wedding registry preventing duplicated gifts.  When employees purhase a gift, they could go to the list and mark off that it is fulfilled. 
 
In SharePoint this turned out to be easy and fast to implement: 
  1. Create a custom list to store the holiday gift wish list items.
  2. Add fields for a picture of the gift, title, family member, and check-off field.
  3. Populate list with gift items.
  4. Create a new site page and add the gift list as a web-part to the page.
  5. Configure the list view to enable inline editing.
  6. Add content explaining how to view and select items from the list.
  7. Optional: Create a SharePoint Designer Workflow to automatically send out a thank you email.

Increasing Participation:

To increase participation we made the SharePoint accessible to more employees and also partners by enabling claims-based authentication and providing access through the firewall. 

Happy Holidays!

Posted in Sharepoint, Social Networking
Follow

Get every new post delivered to your Inbox.