Starting a Service Application Proxy via PowerShell

If you need to start an application proxy thats crashed or for some other reason then the following will get it up quickly for you.

Change the Usage* to a partial name or full name of the target proxy.

$app = Get-SPServiceApplicationProxy | where {$_.TypeName -like "Usage*"}
$UP = Get-SPServiceApplicationProxy | Where {$_.ID -eq $app.Id.Guid}
$UP.Provision()

Problem with updating code run from Async Events? No worries

Exactly no worries just make the following script bat or ps1:

net stop SPTimerV4
net start SPTimerV4
iisreset /noforce
net start W3SVC

Save the script into the root of the project and set it the file to “Do not copy”. Then add the script to your “Post deployment command line”

Like so:

%windir%\sysnative\windowspowershell\v1.0\powershell -file “$(ProjectDir)PSDeploy.ps1″

The $(ProjectDir) will automatically pick up in visual studio for you.

Job done, the timers and iis will reset and ensure they are fully restarted after every deployment.

Note this works in a local development environment only, to do this remotely you can do the same by enabling remote powershell and changing the command to suite.

Faster way of passing a param to call functions.

This pattern of functions as objects runs significantly faster than a switch statement doing the same thing on IE (40%) and marginally faster on Chrome (15%) and Firefox (3%) however safari actually comes in faster with optimisations on switch statements by 1.8%.

For SharePoint at least this is worth considering as a pattern for any large switch statement you may use.

var opt = "example";

var funcCalls = {
"Add":addToFunction = function(options) {
alert("Zero " + options);
},
"Add1":addToFunction1 = function(options) {
alert("One " + options);
},
"Add2":addToFunction2 = function(options) {
alert("Two " + options);
},
"Add3":addToFunction3 = function(options) {
alert("Three " + options);
}
};

myCall = "Add1";
funcCalls[myCall].call(this, opt);

SandBox Solutions, a Necessary evil

[Examples near the bottom]

Okay, Sandbox solutions aren’t going to go away any time soon (No matter how much I wish they would) BUT there is good news, with the right development methods Sandbox solutions can have almost as much functionality as a full Farm solution.

Code behind files can be replaced by a webpart, and where needed with the CSOM (SPServices finishes this off from CodePlex)

Custom JS and CSS, Master pages and layouts get deployed as modules, which are activated in the feature. They are all set as ghostable and their URL property mapped to where you want it.

For elevation, you have to use a app hosted externally, which authenticates your user then runs the elevated task.

etc etc…

Sandbox Solution are used by most large organisations as the ONLY deployment type allowed, if you don’t become used to writing them, you will cost a lot of extra development time.

Farm solutions are “dirty” but a required evil, Sandbox are difficult but a required evil. Basically both are evil in their own way.

Write a Farm solution wrong and you will risk breaking your box, breaking security or something else just as risky if you are just starting out.

Sandbox solutions are limited, but organisations use them as protection against bad code, or bugs in code, they can’t break the server and they can’t cause the server to slow down.

On top of this, anything that has processing involved should run under a monitored scope. This will mean if anything you write does go wrong, the cause can be pinned down and your code disabled awaiting a fix.

Sandbox solutions are depreciated in 2013, but I know for a fact that since they are still there, certain large organisations are sticking by Sandbox solutions and will not back down.

There isn’t a limitation of a Sandbox solution that cannot be overcome, this is the fact of the situation, and they heavily help create a more stable server.

Examples of what you think cannot be done and how to get around them:

  • Logging, you cannot use the ULS to custom log events, you can however use monitored scopes to output verbosely to the ULS everything within, and you can create a hidden list and log what you would manually log to it.
  • Taxonomy, with the taxonomy namespace restricted you have to turn to a client side solution with SPServices to do everything you are blocked for
  • Elevated permissions, to achieve this you need to have an externally hosted app which can authenticate your user with SharePoint and run the required process using WEB Services / RPC for you
  • Custom Master page (Similar for js, css, layouts etc) you add the file into a module in your solution, and in the elements file set the URL to the location you wish it to appear and then set it as Ghostable or GhostableInLibrary depending on what you want to do
  • You can’t get external site collections, again go to JavsScript for this and use the CSOM
  • Visual WebParts aren’t supported, but you can use CKS Dev/Power tools to give you this functionality back.
  • You cannot call external databases, again you can dive into the JavaScript, or use a BCS connected list to surface the information for you
  • Only designer workflows allowed, not a big deal, you can either use a product like K2 Workflows or just create it with event receivers (Which are usually faster anyway in my book)
  • You can’t use system IO, again just go through JavaScript here and use the author.dll RPC the same as Office/Designer do
  • Hide custom action/custom action group are not allowed, this isn’t a problem if your custom actions are made correctly, but you can still use security trimming and use JavaScript/css after disabling with security trimming!!
  • No feature stapling support, this is a hard one to overcome, but using events like SiteProvisioned etc can overcome this
  • Can’t write to the registry but you can read, WHY WOULD YOU WANT TO!!!
  • Can’t set cookies in sandbox, but you can use JavaScript to do this again!
  • No call to external Services, but again JavaScript (See where I am going CSOM is your friend)
  • Can’t use sharepoint mapped folders such as layouts, RUBBISH as I said just ghost the file from a module into the folder, even works on public facing 365
  • Can’t export a sandboxed webpart, technically this is the hard one, but really good standards and practices you should have this in code anyway!
  • Microsoft WebPart controls and Pages aren’t available. There are SharePoint controls for almost all ASP.net and if not CKS dev also helps. Further you can create JavaScript modifications
  • No ADO.net support, going back to BCS connect to a list that uses it instead of doing it in your webpart
  • No support for sendemail, so write a proxy service to send emails! Or use an external app and JavaScript
  • No Cacheing support, you can create custom cacheing for complex HTML using a HTML field in a custom hidden list to prevent re generation
  • No site definition, this can be done using modules instead
  • No localisation support, you would be using international, but if it is a hosted SharePoint you would set this up regardless
  • Microsoft.Sharepoint.Administration is disabled, use SPServices to get around this
  • No document converters, this is just training, they would save as the trained file, converting externally sent files on save to SharePoint in Office
  • No access to scriptmanager, this doesn’t stop you from doing anything at worst you can use a webpart or javascript
  • No GAC deployment, no loss here, just make a custom deployment method for complex deployments
  • No redirects server side, use JavaScript redirects or nice Modal boxes to display data/messages
  • Can’t directly access some enterprise services, like UPM or Search, but you can just use one of the other models to access this information
  • Can’t access DLLs from BIN and resource files. This doesn’t hit you with any issues, in fact I see doing this as an almost bad practice, this could be abused by a hacker anyway. You can do anything you need in other ways
  • Can’t access code that is marked as partially trusted callers, this is again fine, if it is to hard to do then just make a COSM version of what you need to do or make a trusted version
  • Only SPLimitedWebPartManager is available, there is nothing you should need to do that you need to do. Anything to heavy can be moved to a CSOM ran page through JavaScript

I am going to write this up and extend it for every blocked namespace for sandbox solutions. Random guides for each work around are about but I will aim to put in one place.

So once more with feeling, large organisations will love you if you can develop freely, securely and quickly in a Sandbox solution.

Creating a blank ASPX page for SharePoint 2010 using visual studio 2010

Okay so there are a lot of guides on this and most are completely right.

But what I want to show is slightly different, I want to give you the the BARE minimum page you can make with a ASPX page in SharePoint 2010.

1) Create a new blank SharePoint 2010 project targeting .net 3.5 framework and any processor and target your test SP2010 site
2) Add new reference to the SharePoint built in folder _Layouts
3) I recommend you create a sub folder in here to keep your custom files in nice and neatly, so make an External folder for this example
4) Add a new Application Page to the External folder and call it blanktest
5) Delete the designer page (not needed)
6) In the aspx page delete EVERYTHING but the following two lines:

<%@ Assembly Name=”$SharePoint.Project.AssemblyFullName$” %>
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”blanktest.aspx.cs” Inherits=”Your.Namespace.Here” %>

7) Deploy
8) Browse to your site http://%5Bsite%5D/_layouts/External/blanktest.aspx

There you have it, a 100% blank aspx page that you can do ANYTHING with.

This method is almost identical to making a ashx HTTP Handler, except instead of inheriting Page you Inherit HTTPHandler with your default function being:
public void ProcessRequest(HttpContext context).

SharePoint – Site owner access denied

The theory always stays the same no matter how this has happened, basically we changed the access to someone else, then back to the site owner, this will reset all the permissions for the user.

stsadm provides us with what we need for this, so simply run the following two commands to reset the permissions.

stsadm -o siteowner -url SiteUrl -ownerlogin Domain\AnyUser
stsadm -o siteowner -url SiteUrl -ownerlogin Domain\SiteOwner

Easy.

Local debugging in SharePoint

Sometimes you don’t want to use the ULS because you are working locally and you want to work quickly without having to add debugging code to your web parts/pages.

Sometimes it isn’t your code that is breaking and you still want to work locally.

Here is how:

  • Open up IIS and browse to your local SharePoint installation (Usually SharePoint – 80)
  • Right click it and click explore.
  • Locate the web.config and edit in your favorite editor
  • Locate the following three parts and change false to true and On to Off where appropriate:
    1. CallStack=”false” > CallStack=”true”
    2. debug=”false” > debug=”true”
    3. customErrors mode=”On” > customErrors mode=”Off”
    4. AllowPageLevelTrace=”false” > AllowPageLevelTrace=”true” (this will show headers cookies etc BIG HELP)
  • Once this is done go back to IIS right click the _layouts folder and locate the second web.config in there
  • In this file there is only a debug=”false” line change this to debug=”true”

Then you have two options for a page trace:

Either add it per page:

Or add it in the system.web node of your web.config for the entire site
<trace pageOutput=”true” enabled=”true” />

You have now enabled full debugging on SharePoint for your local installation.

Enjoy!

Node.nodeType – Don’t use for backwards compatability!

Just a note the following, Node.nodeType isn’t in IE8 or below so if you are targeting those browsers make sure to use the number instead of the textual format.

The node type values:
Node.ELEMENT_NODE == 1
Node.ATTRIBUTE_NODE == 2
Node.TEXT_NODE == 3
Node.CDATA_SECTION_NODE == 4
Node.ENTITY_REFERENCE_NODE == 5
Node.ENTITY_NODE == 6
Node.PROCESSING_INSTRUCTION_NODE == 7
Node.COMMENT_NODE == 8
Node.DOCUMENT_NODE == 9
Node.DOCUMENT_TYPE_NODE == 10
Node.DOCUMENT_FRAGMENT_NODE == 11
Node.NOTATION_NODE == 12

example:
this.nodeType == 3
not
this.nodeType == Node.TEXT_NODE
Will check the node type you have loaded to see if it is one that holds text.

example 2:
this.nodeType == 11
not
this.nodeType == DOCUMENT_FRAGMENT_NODE
This will check to see if the node holds other nodes, ie is a DOM fragment.

Good hunting dom manipulators!

[code snippet] Populate a table from an array (JQuery)

Ever returned a massive array from json? Want to pre render the table to reduce dom manipulation and just populate the data?

Well this can be used for tables and with a modification a table made from DIVs (If you really don’t want to use tables for what they are used for!)

Basically I got asked how do you do this using JQuery, it really makes it simple doesn’t it.

A simple nested loop, if you can beat it for performance please post I want to know!

var newarray = [["One","Two","Three"],
                ["One 2nd","Two 2nd","Three 2nd"],
                ["One 3rd","Two 3rd","Three 3rd"]];
$('#foo tr').each(
    function(i) {$(this).find('td').each(
        function(j) {
            $(this).html(newarray[i][j]);
        });
    });