Sharepoint 2013: Get Me Out Of Here (Part I): Full Trust Proxy   2 comments

  • A Note About Our Development Environment: We’re all Bozos on This Bus

You can find Part II here.

After several frustrating attempts to construct a working Sharepoint 2013 RTM development environment locally on both physical and Hper-V hardware we finally got out our (corporate) credit cards are purchased virtual cloud environments from CloudShare.   For a very reasonable fee, I have a three server reference implementation of Sharepoint 2013 RTM  (Sharepoint Server, Windows 2012 server SQL Server and Windows 2012 Active Directory Server).  All of which is fully re-configurable.  Plus all the Microsoft products you can shake a stick at (Visual Studio 2012, Office 2013 and more at no extra cost.  Make the pain go away.  If you are developing now and are waiting for corporate to configure Sharepoint or struggling to configure Sharepoint on your own STOP – Go cloud based.  Easy, fast, and fun.

  • SPProxyOperation Class How to Call into a Full Trust Assembly (Farm Solution) From a Sandbox Solution
 
 

The MSDN official documentation of the Full Trust Proxy Class is the rather terse:

 
public abstract class SPProxyOperation
public abstract Object Execute(
	SPProxyOperationArgs args
)
public abstract class SPProxyOperationArgs()

public static Object ExecuteRegisteredProxyOperation(
	string assemblyName,
	string typeName,
	SPProxyOperationArgs args
)

What more could you want? Start by reading base reference articles from MSDN:

You should review these papers before proceeding with this blog. I am attempting here to

  • correct some errors in those papers;
  • clarify some ambiguous points; and
  • provided some simplifications to development procedures.

You should refer to these papers for additional details and hand holding for sections of code development I am not going to discuss herein.

  • Step One Create a Full Trust Proxy.

Create a new Project as a Sharepoint 2013 – Empty Project and set the Sharepoint Server and select Farm Solution in the setup dialog box.  Once the project is created open the property pages for the project.  On the Application Tab:

Set Default Namespace: (for example) Contoso.SharePoint.UserCode

Set Assembly Name as Namespace.AssemblyName (for example) Contoso.SharePoint.UserCode.myProxyOp

On the Sharepoint Tab in the post-deployment step add this code:

net stop SPUsercodeV4

net start SPUsercodeV4

which will stop and restart the User Code module after deployment. Save The project and close the Property pages. 

Open the AssemblyInfo.cs file in your project and add this line to the bottom of the file:

[assembly: AllowPartiallyTrustedCallers]

This will enable Sandbox solution web parts to call the assembly.

Now create a new item for your project:  a class file.  Here is a simple shell of the code you will need to write.

//using statements

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

using Microsoft.SharePoint.UserCode;

namespace Contoso.SharePoint.UserCode

{

public class myProxyOp : SPProxyOperation

{

      public override object Execute(SPProxyOperationArgs args)

{

               if (args != null)

{

                  //Decode the arguments to your specific needs:

                  //See the two Serializable Classes below

MyProxyArguments myArgs = args as MyProxyArguments;

                                  MyProxyReturnDataStructure myData=new MyProxyDataStructure(myArgs.Thing1, myArgs.Thing2, myArgs.Thing3);

                

                  //Your FULL trust Code Goes Here

                  // …

                  // return your results

                  List<MyProxyReturnDataStructure> myReturnList=new List<MyProxyReturnDataStructure>();

                  myReturnList.Add(myData);

return myReturnList;

               } else{

                  //do nothing if the SPProxyOperationArgs is null

                  return null;

               }

       }

}

//Helper to Define the return object, optional

[Serializable]

public class MyProxyReturnDataStructure

{

public String Thing1 { get; set; }

public String Thing2 { get; set; }

public String Thing3 { get; set; }

       public MyProxyReturnDataStructure(string thing1, string thing2, string thing3)

       {

     Thing1 = thing1;

     Thing2 = thing2;

     Thing3 = thing3;

       }

}

//Define the parameter class (Argument Class) to pass arguments into the proxy class

[Serializable]

public class MyProxyArgumentsClass : SPProxyOperationArgs

{

       //Define Arguments

       public string Thing1 { get; set; }

       public string Thing2 { get; set; }

       public string Thing3 { get; set; }

       //Initialize Arguments (Optional)

public MyProxyArguments(string thing1, string thing2, string thing3)

{

Thing1 = thing1;

            Thing2 = thing2;

            Thing3 = thing3;

        }

    }

}

  • Add Registration Feature For your Full Trust Proxy

We must add an event receiver For Feature Activation and Deactivation. Why? Who Knows, just do it, its purely boiler plate code and we are only supplying the Class name of our class derived from SPProxyOperation.  Please remember to set the Scope to FARM.  See the Reference articles for details.

using System;

using System.Runtime.InteropServices;

using System.Security.Permissions;

using Microsoft.SharePoint;

using Microsoft.SharePoint.UserCode;

using Microsoft.SharePoint.Administration;

namespace Contoso.SharePoint.UserCode.Features.Registration

{

/// The GUID attached to this class may be used during packaging and should not be modified.

[Guid(“a2a9ac81-7338-4f76-8f29-6a55f5aed186”)]

public class RegistrationEventReceiver : SPFeatureReceiver

{

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

Type type = typeof(myProxyOp);

SPProxyOperationType proxyOperationType = new SPProxyOperationType(type.Assembly.FullName, type.FullName);

SPUserCodeService userCodeService = SPUserCodeService.Local;

userCodeService.ProxyOperationTypes.Add(proxyOperationType);

userCodeService.Update();

}

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

Type type = typeof(myProxyOp);

SPProxyOperationType proxyOperationType = new SPProxyOperationType(type.Assembly.FullName, type.FullName);

SPUserCodeService userCodeService = SPUserCodeService.Local;

userCodeService.ProxyOperationTypes.Remove(proxyOperationType);

userCodeService.Update();

}

}

Note that I have removed the attribute adornment of both the SPProxyOperation class and the SPProxyOperationArgs class of

[Microsoft.SharePoint.Security.SharePointPermission(System.Security.Permissions.SecurityAction.LinkDemand, ObjectModel=true)]

This adornment is both obscure and lead to errors when the proxy class was called by the Farm solution. We note that the abstract class definition as documented in MSDN has these attributes already so there loss from the user code seems to not be a problem.

One final code addition, open the feature xml file, it will look something like:

<!–?xml version=”1.0″ encoding=”utf-8″ ?>

<Feature AlwaysForceInstall=”TRUE” xmlns=”http://schemas.microsoft.com/sharepoint/”>

</Feature>

We have added the attribute and value given in RED above. This will allow you to retract and deploy this package multiple times without manually removing the registration feature each time.

Build and Deploy your project to your Sharepoint server.  Ok, now we are ready to write a Farm solution to call the proxy.

  • Create A Sandbox solution to use the Full Trust Proxy Class

Get the public key of the Assembly which contains the Full Trust Proxy Class

Visual Studio command line utility called sn.exe.  It can be used to extract the public key from a strongly named assembly.

Get the physical address of the assembly you created.  You do not need to manually access the assembly in GAC.  In my example above this path is

C:\Users\Administrator.AD2012\Documents\Visual Studio 2012\Projects\WebAdminInfoOp\myProxyOp\bin\Debug

use this and the SN utility to get the public key:

{path}\SN –T {projectpath}\Contoso.SharePoint.UserCode.myProxyOp

Create a new Visual Studio Project Sharepoint 2013 Empty Project and make it a SANDBOX solution.  See the reference article for details.

Add a reference to your full trust assembly you developed above.  You do not need to use the assembly in the GAC, use the physical project path you obtained above.

The guts of the Sandbox solution is the call to the Full Trust Proxy. Use a non-visual Web Part to implement the call.   This critical code will look like this:

using Microsoft.SharePoint.Utilities;

using Contoso.SharePoint.UserCode;

//get the Assembly name,  the class name and the assembly’s Public key into strings into strings

String publicKey=”0c2fc14b21374a34”;

String assemblyName=”Contoso.SharePoint.UserCode.myProxyOp”;

String proxyOperationClassName = “Contoso.SharePoint.UserCodemyProxyOp”;

String fourPartProxyAssemblyName =String.Format(“{0},Version=1.0.0.0,Culture=neutral,{1}”, assemblyName,publicKey);

//Get the arguments ready

MyProxyArgumentsClass args = new MyProxyArgumentsClass(“a”,”B”,”c”);

//Make the call

Object returnObject = SPUtility.ExecuteRegisteredProxyOperation(fourPartProxyAssemblyName,proxyOperationClassName, args);

//translate the results back from type object

List myList = returnObject as List;

Ok that’s the code: see the reference articles for details on creating Farm solutions.  Deploy and add the Web part any Sharepoint page and off you go.

2 responses to “Sharepoint 2013: Get Me Out Of Here (Part I): Full Trust Proxy

Subscribe to comments with RSS.

  1. Pingback: Sharepoint 2013: Get Me Out Of Here (Part 2): Cross Domain AJAX Calls in Sharepoint Apps « Cloud2013 Or Bust

  2. Activation fails after I added the feature (not calling the proxy yet). Just wanted to see if it would load without calling the proxy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: