Thursday, 6 March 2014

Custom error page for a public facing publishing portal

In the previous Post we created a web application and extended it to have a Anonymous Public Facing Door, that is an entry point that is Read only and Anonymous. At the end of that post we saw a lovely blank 401 unauthorized error page.

Not exactly user friendly, especially when you work in government and you have some crazy conspiracy theorist claiming he's found the web page about selling organs on the black market, when it's really just a bus route some coop student forgot to check back in.

So lets start by creating a new SharePoint Project

Hit Ok,


Make sure to select Farm solution and hit finish.

Now you Have your SharePoint Project, next what your going to do is create a class library, right click on your solution->add->New Project.

Select Windows Templates, pick Class Library, give your project a name and hit OK.

In the above I accidentally have framework 4.5 selected, for SharePoint 2010 you have to have 3.5 so make the change here or right click on your project and change it there.

Next your going to have to add a reference to the System.Web.dll. In your solution explorer right click on references and hit add References.

with that added go to your class, by default the file and class should be called class1.cs change that to something more appropriate, it's common to suffix whatever you call it with the word module.

next implement the IHttpModule interface,

using System;
using System.Web;

namespace ErrorRedirect
{
    public class ErrorSwapModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


right click on IHttpModule and implement it implicitly, that'll get you the init and dispose functions. I wrap them in a region this is just for decoration and makes it easer to manage large classes. how you organize your code is really up to you and your team, you just have to pick what works for you and stick to it.

next we add a new event handler to our context to handle The PreSendRequestContent event.

using System;
using System.Web;

namespace ErrorRedirect
{
    public class ErrorSwapModule : IHttpModule
    {
        private HttpApplication _webApp;

        #region IHttpModule Members
        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            _webApp = context;
            _webApp.PreSendRequestContent +=
                new EventHandler(WebApp_PreSendRequestContent);
        }

        #endregion

        private void WebApp_PreSendRequestContent(object sender, EventArgs e)
        {
            HttpResponse response = _webApp.Response;

            string message = string.Empty;

            switch (response.StatusCode)
            {
                case 401:
                    this._webApp.Response.Clear();
                    this._webApp.Response.Write(
                        @"<html>
                            <head />
                            <body>
                                This is a Custom 401
                            </body>
                        </html>");
                    break;
            }
        }
    }
}


this is where we check the status code of our response and then redirect our user to where ever we feel is appropriate.

Now we've done a lot of work, but we're not done yet, we still have to register this module in our GAC, and to do this your project has to be signed, what this means is a bit out of the scope of this post but think of it as giving it a unique secure-ish identifier.

To sign your project, right click on it and go to properties, on the left select the signing tab

now from the drop down select browse, next navigate to the SharePoint Project we created earlier at the start of this post and select that key.snk file

with that selected our solution is now signed, now we are going to need our modules public Token, the public token is an abstraction of the public key, if you don't know what that is don't worry about it too much it has to do with asynchronous Encryption and a privet-public key pair again outside of the scope of this, but you know enough to look it up yourself.

Now when it comes to getting our public Token, the best way is in this post, don't worry it works in VS 2012 too.


when you run your tool, you should get something like the above, but with a different public key and token. make note of this Public Key Token for later. In my case it's 06ae58ed1b6fa751 in your case it'll be something different.

Now we have enough to register our Module in our Web Config, now you should never modify your web config by hand, but to keep this post shorter we are going to break that rule. open up the web config for the extension of your site. In the previous post we created a web app with port 3333, then we extended it on port 4444. Make sure you make your modification for port 4444.

Your web config will be "C:\inetpub\wwwroot\wss\VirtualDirectories\4444"


now open that up in your favourite editor, personally I like notepad++, but that's me.
look for the line
<modules runAllManagedModulesForAllRequests="true">
it should be around line 450 in the webconfig, now directly after it your going to append something along the lines of
<add name="ErrorRedirect"

    type="ErrorRedirect.ErrorSwapModule,
ErrorRedirect
,
Version=1.0.0.0,
Culture=neutral,
PublicKeyToken=06ae58ed1b6fa751"
/>

Just match the above with the below

using System;
using System.Web;

namespace ErrorRedirect
{
    public class ErrorSwapModule: IHttpModule
    {
        ...
    }

}

As for the Version number and Culture, you set that in the project properties
and we talked above how to get the Public key token.

with that change made in your webconfig, deploy your project and try to navigate to your settings folder of your extended web app that's the one with 4444 as a port number.


still not the greatest but you can at least customize it, now you could deploy a much more robust html page, read it in using some sort of string reader, and write that to your response, just make sure all of your assets, such as css and images are in a publicly available library, ie not your layouts folder.

Sunday, 2 March 2014

Create Anonymous Publishing Site

Lets Start with a regular Publishing Web app


notice the following:

  • Authentication: leave as default set to Classic
  • Name: Whatever you want it to be
  • Port: something easy to remember
  • Anonymous: Enabled.

and hit OK, wait a while and create your publishing site collection


notice the following
  • Name: whatever you like
  • Template Category: Publishing
  • Template type: Publishing Portal
  • primary admin: yourself
  • secondary admin: Local administrator 
hit OK, let it spin a while and you have your Web Application created.

next we're going to extend our web application, select our web application form central admin and hit the extend button.

next you'll get the Extend web application to another iis website screen


put in your info
  • Name
  • Port
  • Enable Anonymous 
  • Zone to internet
Scroll down and hit OK.

now click the authentication providers button

this will list the authentication providers, click on the internet one


with that selected change the authentication by unchecking the integrated windows authentication option


This will ensure that through this second door only anonymous unauthorized user ie the public can hit your publishing portal.

Finally navigate to the Site Permissions of the original web app set up  in this case it was the one with port 3333. Site Actions->Site Permissions

with that clicked the Anonymous Access Pane will pop up and select Entire Web Site

and hit OK, now navigate to your public facing extension in this case it had port 4444


and there you go your extended site. if you click sign in you'll get a 401 Unauthorized


this is because on your extension you enabled anonymous and disabled integrated windows authentication, meaning you couldn't log into your web application through this "Door" if you wanted to, ideal for a public facing portal.

Wednesday, 26 February 2014

Debug Sandbox Solutions

Sandbox Solutions do not run on the w3wp.exe process they actual run on SPUCWorkerProcess.exe, so that's what you have to attach to in visual studio.

Saturday, 22 February 2014

List property bag content

function LoadSharePointPowerShellEnviroment
{
 write-host
 write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Magenta
 Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
 Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green
}
Clear-Host
LoadSharePointPowerShellEnviroment
write-host


$url= 'https://collaboration-dev5.ioc-lab.local/sites/ApprovalsPortal'
$site = New-Object Microsoft.SharePoint.SPSite($url)
$rootWeb = $site.RootWeb

Write-Host -foregroundcolor Green "The current Site"$rootWeb

$properties = $rootWeb.AllProperties

$properties.Keys | % {write-host $_":" $properties[$_]}

if ($rootWeb -ne $null)
{
    $rootWeb.Dispose()

}
If ($site -ne $null)
{
    $site.Dispose();
}

Write-Host -foregroundcolor Green "Script has finished executing "

Thursday, 13 February 2014

Sandbox add To Property Bag

You can't add to the property bag in a sandbox solution as you would in a farm solution; In a farm solution you would access the AllProperties or Properties collections, but in a sandbox solution you have to use the functions exposed on the SPWeb class.

// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;

    AddValueToPropertyBag(web, "language_en_location", "/sites/ApprovalsPortal/SiteAssets/Navigation_en.xml");
}

private void AddValueToPropertyBag(SPWeb web, string key, string value)
{
    if (web != null)
    {
        web.SetProperty(key, value);

        web.AllowUnsafeUpdates = true;
        web.Update();

        web.AllowUnsafeUpdates = false;
    }
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    var web = properties.Feature.Parent as SPWeb;

    RemoveValueFromPropertyBag(web, "language_en_location");
}

private void RemoveValueFromPropertyBag(SPWeb web, object key)
{
    if (web != null && web.AllProperties.ContainsKey(key))
    {
        web.AllowUnsafeUpdates = true;

        web.DeleteProperty(key);
        web.Update();

        web.AllowUnsafeUpdates = false;
    }
}

Saturday, 8 February 2014

Replicator

This is a continuation of my previous post Multiple Tasks. The video by Scot Hillier is probably more then enough to complete this part, so I'm just going to skim over it.

Open up the workflow you created in the previous post, add a replicator and inside of it add your taskGenerator, if you do not see your task generator in your tool box, make sure to deploy your project.

now that you've added your task generator your workflow should look like


right click on your replicator and select generate handlers. this is what you should see

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace SPM_WorkFlow.Workflow
{
    public sealed partial class Workflow : SequentialWorkflowActivity
    {
        public Workflow()
        {
            InitializeComponent();
        }

        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        private void replicatorActivity1_ChildInitialized(object sender, ReplicatorChildEventArgs e)
        {

        }

        private void replicatorActivity1_ChildCompleted(object sender, ReplicatorChildEventArgs e)
        {

        }

        private void replicatorActivity1_Completed(object sender, EventArgs e)
        {

        }

        private void replicatorActivity1_Initialized(object sender, EventArgs e)
        {

        }
    }
}


we are really only going to focus on two of the functions:

  • replicatorActivity1_Initialized
  • replicatorActivity1_ChildInitialized

so you can delete the other two if you'd like, one other thing that you're going to have to do is create an iList, this what you should end up with
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace SPM_WorkFlow.Workflow
{
    public sealed partial class Workflow : SequentialWorkflowActivity
    {
        public Workflow()
        {
            InitializeComponent();
        }

        public IList TaskList = default(System.Collections.IList);
        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        private void replicatorActivity1_ChildInitialized(object sender, ReplicatorChildEventArgs e)
        {

        }

        private void replicatorActivity1_Initialized(object sender, EventArgs e)
        {

        }
    }
}


Notice the highlighted IList, lets go back to our replicatorActivity properties

  • bind the InitialChildData to our IList TaskList. 
  • set the execution type to Parallel

also if you removed the two completed fucntions your'e going to have to remove them from the properties to end up with.


Now go back into the code and lets focus on the replicatorActivity1_Initialized function.

private void replicatorActivity1_Initialized(object sender, EventArgs e)
{
    //set up the array list, which is going to be distributed amoungst each instance
    //the task gernator activity
    TaskList = new ArrayList();
    TaskList.Add(@"Domain\User1");
    TaskList.Add(@"Domain\User2");
    TaskList.Add(@"Domain\User3");
    TaskList.Add(@"Domain\User4");

    //initiate the first task
    taskGenerator1.Task_Title = "My Task";
    taskGenerator1.Task_Description = "<ul><li>One</li><li>Two</li></ul>";
    taskGenerator1.Task_AssignedTo = TaskList[0].ToString();

    taskGenerator1.Site_GUID = workflowProperties.SiteId;

}

next lets look at the replicatorActivity1_ChildInitialized function

private void replicatorActivity1_ChildInitialized(object sender, ReplicatorChildEventArgs e)
{
    taskGenerator1.Task_Title = "My Task";
    taskGenerator1.Task_Description = "<ul><li>One</li><li>Two</li></ul>";
    taskGenerator1.Task_AssignedTo = e.InstanceData.ToString();

    taskGenerator1.Site_GUID = workflowProperties.SiteId;

}

now deploy your project and test out your workflow