Tag Archives: SharePoint 2013

WebAPI OData – 10 min video introduction (Visual Studio 2013)

I’ve been learning about OData and wanted to record a quick getting started video with how to create a new WebAPI project, add OData Controller, and send HTTP CRUD operations.  Below is an example using Adventure Works Departments with sample code, screenshots, and a 10 minute video introduction.   Please leave a comment if you found this helpful.  Thanks!  shades_smile

Video Content

  • Create MVC 4 web application
  • SQL Express – Adventure Works Departments
  • Add “AdventureWorks.edmx
    • Wizard driven
    • F4 set namespace
  • Add “DepartmentsController.cs
    • Create from EDMX class
    • Implements ODataController
    • Replace ID with KEY
  • Edit “WebApiConfig.cs
    • Comment out default route
    • Add OData route builder
  • Test with HTTP manually
  • Test with Chrome REST Postman
  • SQL Express – see changed data

Watch Video

WebAPI OData – 10 min video introduction (Visual Studio 2013) from Jeff Jones on Vimeo.

Sample Code

[WebApiConfig.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
namespace MvcApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
            ODataConventionModelBuilder build = new ODataConventionModelBuilder();
            build.EntitySet("Departments");
            config.Routes.MapODataRoute("odata", "odata", build.GetEdmModel());
            config.EnableQuerySupport(new QueryableAttribute()); 
            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();
            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}

 

[DepartmentsController.cs]

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.OData;
namespace MvcApplication1.Controllers
{
    public class DepartmentsController : ODataController
    {
        private AdventureWorks2012Entities db = new AdventureWorks2012Entities();
        // GET api/Default1
        public IEnumerable GetDepartments()
        {
            return db.Departments.AsEnumerable();
        }
        // GET api/Default1/5
        public Department GetDepartment(short key)
        {
            Department department = db.Departments.Find(key);
            if (department == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return department;
        }
        // PUT api/Default1/5
        public HttpResponseMessage PutDepartment(short key, Department department)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (key != department.DepartmentID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            db.Entry(department).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        // POST api/Default1
        public HttpResponseMessage PostDepartment(Department department)
        {
            if (ModelState.IsValid)
            {
                db.Departments.Add(department);
                db.SaveChanges();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, department);
                response.Headers.Location = new Uri(Url.Link("odata", new { key = department.DepartmentID }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
        // DELETE api/Default1/5
        public HttpResponseMessage DeleteDepartment(short key)
        {
            Department department = db.Departments.Find(key);
            if (department == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            db.Departments.Remove(department);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK, department);
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Downloads

Screenshots

image

image

image

image

image

PowerMap – 6 min video introduction (Excel 2013)

I heard a lot about PowerMap and wanted to record a quick getting started video with how to download, screenshots, and play a sample XLSX workbook.  

Background

The “Power” family of Business Intelligence features is getting a lot of attention at conferences, SharePoint Saturday, Channel 9, and social media.   Personally I hadn’t worked hands-on with the features before.   The idea is simple and practical – everyone uses Excel for data, so why not leverage that as the BI design surface?

Video Content

  • PowerMap screenshots
  • Download PowerMap EXE for Excel 2013
  • Download sample XLS PowerMap workbooks
  • How to play the Chicago sample XLSX

If you found it helpful please leave a comment below.  Enjoy!  shades_smile

Downloads

 

Watch Video

PowerMap – 6 min video introduction (Excel 2013) from Jeff Jones on Vimeo.

Screenshots

image

image

image

image

image

image

image

image

How to Follow a site URL with PowerShell in SharePoint 2013

Background

While migrating from SharePoint 2010 to 2013 we needed to take MyLinks and replace with new Social Site Following.   Given a CSV with user names and site URLs I researched PowerShell options for programmatically making users follow sites.   Now we can pre-populate Follow Sites before launch.   The below code did the trick.  shades_smile

 

Code

Function AddSiteToUserFollow ($siteUrl, $userName) {
	# Load site and user profile service
	$site = Get-SPSite $siteUrl
	$serviceContext = Get-SPServiceContext($site)
	$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext)
	if ($profileManager.UserExists($userName)) {
		# Load user profile
		$userProfile = $profileManager.GetUserProfile($userName)
		
		# Load social following manager
		$followingManager = New-Object Microsoft.Office.Server.Social.SPSocialFollowingManager($userProfile, $serviceContext)
		
		# Prepare following object
		$actorInfo = New-Object Microsoft.Office.Server.Social.SPSocialActorInfo
		$actorInfo.ContentUri = $site.Url
		$actorInfo.AccountName = $userProfile.AccountName
		$actorInfo.ActorType = "Site"
		
		# Add to followed sites
		$followingManager.Follow($actorInfo)
	}
}
AddSiteToUserFollow "http://sp15" "demo\sptest1"

 

Screenshots

image

image

References

Support

If the target user does not yet have a MySite created you could see the below error.  The fix is simply to have them visit MySite – or – to upgrade their site collection from 2010 to 2013.

Exception calling “Follow” with “1” argument(s): “No personal site exists for the current user, and no further information is available. Internal type name: Microsoft.Office.Server.UserProfiles.SocialDataStoreException. Internal error code: 1.”

InfoPath tip – detect Security Group with List Item permissions

Yes, everyone says InfoPath is dead … but we’re all still supporting it for a while so I wanted to share one of my favorite tips.  Forms often need role based security at the field level.  Table below with example security matrix.

How can InfoPath detect that?   Don’t some people query SOAP ASMX?   Or even a custom WSP with a custom ASMX?   There is a simpler way with List Item permission.  

image

  1. Create a new Custom List named “SecurityLevel” with only the default “Title” column.  
  2. Go create the needed SharePoint Groups under Site Permissions.  
  3. Back in “SecurityLevel” add one new item for each SharePoint Group with an identical name.   Hover that item, pull down the menu, and set Item Level Permissions for that group ONLY to have “Read” on that item only.  
  4. With InfoPath Designer edit the XSN Form Template and create a new Data Connection to the list “SecurityLevel” with auto refresh.  
  5. Under Form Load create a rule … if count(SecurityLevel [“Analyst”]) > 0 then set field “SecurityLevel=Analyst”.   
  6. With that in place you are ready to apply formatting rules anywhere needed that use “SecurityLevel” to determine hide/show or read/write.

 

Voila!

Now when a user open the InfoPath form, the data connection “SecurityLevel” will only show the items they have access to (which is the same as the SharePoint Group membership!).    Works on MOSS 2007, SharePoint 2010, SharePoint 2013, and Office 365.

Hope this helps.  Please leave a comment if it did.  shades_smile

 

DOWNLOAD  InfoPath Form – SecurityLevel.xsn >>

 

 

image

image

image

image

image

 

image

image

image

FIXED – UPS missing Edit Connection LDAP filter menu

Recently while working on SharePoint 2013 I wasn’t able to edit the LDAP filters of the User Profile Service connection.   The hover menu wasn’t even visible.

 

Enabling Compatibility View for the Central Admin URL fixed it.   This page has older HTML which doesn’t work well in the IE 11 modern render engine.   Once Compatibility View was enabled everything worked as expected.     shades_smile

 

image

 

image

 

image

VSIX for SharePoint 2013

Recently while configuring a new developer lab VM I searched http://visualstudiogallery.msdn.microsoft.com/ for plug-ins to help speed up coding.   I found a few good ones and wanted to share links here in case you might find these helpful too.   Cheers!   shades_smile

 


 

  1. CKS – Dev for Visual Studio 2013  is a collection of Visual Studio templates, Server Explorer extensions and tools providing accelerated SharePoint 2010/2013 development based on Microsoft’s SharePoint 2010/2013 development tools.

    image

     

  2. SPCop CE (Community Edition) Essential tool to ensure SharePoint code quality. SPCop analyses SharePoint code from .wsp and .app files and checks all contained code incl. XML, ASPX, JS, CSS for correctness, best practices, memory disposal etc. SPCop is the free component of SPCAF.

    image

     

  3. SharePoint 2013 Ribbon API provides you to use Ribbon UI elements such as Button, DropDown, SplitButton, Gallery, Tab, Group and others for building your own Ribbon and/or modification standart one.

    Screenshot

  4. Mavention SharePoint Assets Minifier for Visual Studio 2013  automates the process of minifying CSS and JavaScript files. Upon installation it introduces three custom tools that you can use for minifying CSS and JavaScript files.

    Mavention

  5. Office 365 API Tools – Preview  your app can access email, calendar, contacts, files, and profile information on behalf of the user. This extension will help register your app to consume Office 365 APIs, and will add the necessary NuGet libraries and sample code to get you up and running.

    Screenshot

  6. SPRemoteAPIExplorer provides the ability to explore, discover and generate SharePoint 2013 remote API code in REST and CSOM(Javascript, .Net and Silverlight). Useful when developing SharePoint REST applications

      Screenshot

       

    1. Ribbon Designer for SharePoint and Office 365 – true RAD tool for customizing the Server Ribbon UI of your SharePoint and Office 365 solutions. Specialized components allow you to quickly build custom ribbons and add a new ribbon to your existing projects without learning the Ribbon XML schema.

        Use the in-place visual designer to customize your SharePoint Ribbon components

      SQL 2014 and SSRS Integrated “Hello States.rdl”

      Recently I create a new lab virtual machine with SharePoint 2013 and SQL 2014 to test SSRS Integrated mode.  

       

      I found the screenshot based instructions at http://rajeshagadi.blogspot.com/2013/07/installing-reporting-services-in.html even more helpful than TechNet official documentation http://msdn.microsoft.com/en-us/library/jj219068.aspx.     Both are good and make configuration easier.   Also I needed to follow the C2WTS configuration steps http://msdn.microsoft.com/en-us/library/hh231678.aspx and Kerberos steps http://technet.microsoft.com/en-us/library/gg502594.aspx to enable single sign on for Claims authentication and SSRS Integrated mode.   To enable SMTP and IMAP email routing I followed https://www.spjeff.com/2011/02/05/how-to-free-internal-sharepoint-email-imappopsmtp-inbound-and-outbound/ to configure both IIS 6.0 inbound to SharePoint and HMailServer SMTP/IMAP for end user mailboxes.

       

      With SSRS online the next task was to build a sample report.  Below are the steps I followed.  

      In the end we have a nice graphical USA map with data points coming from SPList.  Enjoy the screenshots!    shades_smile

       

      1. Open SP2013 Team Site
      2. Create new list named “States” with columns “Title” and “Number”
      3. QuickEdit to add a few sample rows
      4. Activate “PowerView” site collection feature
      5. Add SSRS Content Types to a library
      6. Launch Report Builder 3.0
      7. Create a map with wizard
      8. View in IE to test
      9. Schedule daily job to run report and email PDF
      10. View PDF

       

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      image

      FIXED BDC – Database is in compatibility range and upgrade is recommended

      I noticed the message “BdcServiceDatabase – Database is in compatibility range and upgrade is recommended” in Central Admin.   This often seems to come up after applying a CU patch.

      The fix was just to run a quick PowerShell line to upgrade the database.  Here it is for reference.  Cheers!  shades_smile

       

      (Get-SPDatabase | ?{$_.type -eq "Microsoft.SharePoint.BusinessData.SharedService.BdcServiceDatabase"}).Provision()

       

      image

       

      image

      FSUTIL – create any #MB sized file for testing SharePoint upload

      Recently I came across an old DOS command that can help verify SharePoint maximum upload file size.   FSUTIL enables us to create a file of any given size.   For example,  if your SharePoint farm has a maximum file upload of 200MB you can create a 195 MB and 205MB test file.   Uploading both would validate when 195MB is successful and 205MB fails.

      Enjoy!  shades_smile

       

      PowerShell

      $x = 195MB
      fsutil file createnew 195.txt $x
      $x = 205MB
      fsutil file createnew 205.txt $x

       

      image

      Quick Edit supports JS Link and Client Side Rendering

      Today I attended #SPSChicagoBurbs and the session by Wes Preston (@idubbs)  on Client Side Rendering.   A question was asked by someone in the audience if Quick Edit (new Data Sheet) would support CSR rendering.   The consensus was probably not because of the advanced rendering, event handlers, and cell editing.

       

      I gave it a quick test and surprisingly it worked!   Smile 

       

      When I renamed a file to become “test.txt” it turns the background green, text white, and even shows a custom icon <IMG> tag.   This could be leveraged to give end users real-time feedback on the values entered.   Unlike a JQuery page load event which only triggers once, this triggers per row as values are changed.

       

      Video

      csr-quick

       

      Screenshot

      5-17-2014 12-35-08 PM

       

      Code

      //override
      (function () {
          var overrideCtx = {};
          overrideCtx.Templates = {};
          overrideCtx.Templates.Fields = {
              'LinkFilename': { 'View': ConditionalStatus }
          };
          SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
      })();
      function ConditionalStatus(ctx) {
          var ret;
          console.log(ctx.CurrentItem.FileLeafRef);
          if (ctx.CurrentItem.FileLeafRef== "test.txt") {
              ret = "
      " + " " + ctx.CurrentItem.FileLeafRef + "
      "; } else { ret = ctx.CurrentItem.FileLeafRef; } return ret; }
      Return to Top ▲Return to Top ▲