Thursday, 5 November 2009

MVC Cheat Sheets

Sharepoint Unknown error

To find out what the exact .net error is you need to alter the following in the web.config

Locate the CustomError element and change the attribute value:

From: mode="on"
To: mode="off"

Locate the SafeMode element:

Change the attribute on the Safemode element from

CallStack="false" to CallStack="true"

Friday, 14 August 2009

Modifying Web config entries using code

A good place to start would be to look at the SPWebConfigModification class.

 

The documentation around how to use this is hard to come by, but there is an excellent article here.

 

 

 

Thursday, 13 August 2009

Sharepoint Setting Cookies

To Set Cookies you must do the following:

 

cookie = new HttpCookie(“MyCookie”);

cookie.Values["textSize"] = value;

cookie.Expires = DateTime.Now.AddDays(30);

 

HttpContext.Current.Response.Cookies.Add(cookie);

 

It’s the HttpContext bit which makes it persist!

 

Friday, 31 July 2009

Hosting InfoPath forms inside XmlFormView

First add:

 

<SafeControl Assembly="Microsoft.Office.InfoPath.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.Office.InfoPath.Server.Controls" TypeName="*" Safe="True" />

 

To the safe controls of the web.config.

 

 

Then go to the sites Gallery, appending the link : _layouts/NewDwp.aspx

 

Find “Microsoft.Office.InfoPath.Server.Controls.XmlFormView”

 

And add it to the gallery.

 

Thursday, 2 July 2009

SPEventReceiver Events

Remember that the ItemUpdating , ItemAdding events are the Synchronous ones which mean you can actually cancel them in your code and flag this up to the user, these events should be used as appose to the ItemUpdated , ItemAdded events which fire asynchrously.

 

Wednesday, 1 July 2009

Friday, 26 June 2009

Sharepoint Tool Basket

Download it here:

 

http://sptoolbasket.codeplex.com/

 

Exporting an SDO from MCMS

If you load up Site Manager:

 

 

Start -> All Programs -> Microsoft Content Management Server -> Site Manager

 

 

From the Menu of the Site Manager program:

 

File -> Package -> Export

 

In the All Containers window :

 

Click on Channels , and select “Include”

Click on Resources, and select “Resources”

Click on Templates, and select “Templates”

 

 

At the bottom of the screen it says Export to file (.sdo ) if you put path and filename there, then click  Export.

 

cid:image002.png@01C9F673.425D6A20

 

Above is a example of what it should look like.

 

Wednesday, 24 June 2009

Biztalk training

Sharepoint Using Infopath forms with Workflow

How to setup an Infopath form and use this data inside a Windows Workflow hosted inside sharepoint.

 

http://www.lcbridge.nl/vision/2008/infopath-vs.htm

Sharepoint Workflow & Delay Activity

Once you deploy a Workflow which uses a Delay activity , you should perform an IISRESET and Reset the Sharepoint Timer Service, since both of these may load your dll from the GAC.

 

 

Use the following :

 

net stop sptimerv3

iisreset

net start sptimerv3

 

Friday, 19 June 2009

MOSS SDK very useful

Contains various samples to get you started with Workflow amongst other things.

 

 

http://www.microsoft.com/downloads/details.aspx?FamilyId=6D94E307-67D9-41AC-B2D6-0074D6286FA9&displaylang=en

 

Secure Views In Sharepoint

Good Article on implanting secure views.

 

http://www.infoq.com/articles/Dressel-Gogolowicz-wss-security

Tuesday, 16 June 2009

Big set of Useful Sharepoint Links

Useful Sharepoint Links

Useful Links

 

·         MOSS Video Demos (Total 14 Modules)

·         Before You Begin with SharePoint Server 2007

·         MOSS Tools for performance and capacity planning

·         Downloadable book: Planning and architecture for Office SharePoint Server 2007

·         MOSS 2007 - Planning and Architecture for Office SharePoint Server 2007

·         MOSS 2007 - Administrator Guide

·         Complete reference of all STSADM operations

·         Using the 2007 Microsoft Office system for disaster planning and response

·         Planning and Designing SharePoint Products and Technology Solutions for Geographically Dispersed Sites

·         Complete reference of all STSADM operations

·         Complete reference of all PSCONFIG operations

 

Best Practices

 

·         Before You Begin with SharePoint Server 2007

·         Best Practices Analyzer for WSS 3.0 and MOSS2007

·         Writing SQL Syntax Queries for Relevant Results in MOSS2007

·         Backing Up and Restoring Web Sites with Stsadm

·         Downloadable book: Planning and architecture for Office SharePoint Server 2007

·         MOSS Hardware and Software Requirements

·         SharePoint 2007 products comparison download

·         Which SharePoint technology is right for you?

·         White Paper: Working with large lists in Office SharePoint Server 2007

·         MOSS Tools for performance and capacity planning

 

How to Deploy updates for SharePoint 2007

 

·         Deploy software updates for Windows SharePoint Services 3.0

·         Deploy software updates for Office SharePoint Server 2007

·         How to troubleshoot common errors that occur when you run the SharePoint Products and Technologies Configuration Wizard

 

How to configure Alternate Access Mappings (AAM) successfully

·         http://sharepoint.microsoft.com/blogs/fromthefield/Lists/Posts/Post.aspx?ID=8

 

What every SharePoint administrator needs to know about Alternate Access Mappings

 

·         http://blogs.msdn.com/sharepoint/archive/2007/03/06/what-every-sharepoint-administrator-needs-to-know-about-alternate-access-mappings-part-1.aspx

·         http://blogs.msdn.com/sharepoint/archive/2007/03/19/what-every-sharepoint-administrator-needs-to-know-about-alternate-access-mappings-part-2-of-3.aspx

·         http://blogs.msdn.com/sharepoint/archive/2007/04/18/what-every-sharepoint-administrator-needs-to-know-about-alternate-access-mappings-part-3-of-3.aspx

 

STSADM COMMANDS

 

·         Jose Barreto's Blog Complete reference of all STSADM operations (with parameters) in MOSS 2007 SP1

·         Jose Barreto's Blog Complete reference of all STSADM operations (with parameters) in MOSS 2007

 

SharePoint Administration Toolkit

·         SharePoint Administration Toolkit (Office SharePoint Server)

 

TCP Chimney should be disabled

 

·         http://support.microsoft.com/kb/942861

·         The Microsoft Windows Server 2003 Scalable Networking Pack release

 

http://blogs.msdn.com/aggbug.aspx?PostID=9762455

MSDN Blogs / Tue, 16 Jun 2009 14:43:00 GMT

Sent from FeedDemon

Monday, 15 June 2009

Sharepoint Search Exception from HRESULT: 0x80040D1B

If you get this error while trying to access Search Settings  it might be worth re-booting all servers in your farm.
 
This error usually occurs because a password has been changed, and a full -reboot of the farm is required in order for this to sort it's self out.
 

Helpful class to get Display and Internal Field names for a SPList

namespace ConsoleApplication1

{

public class FieldList

{

/// <summary>

/// Shows the Display field and internal field name for a list.

/// </summary>

/// <param name="litem"></param>

public static void ShowFields(SPListItem litem)

{

for (int i = 0; i < litem.Fields.Count; i++)

{

SPField field = litem.Fields[i];

Console.WriteLine(field.Title + "(" + field.InternalName + ")");

}

}

 

 

}

}

 

Event Handlers By Design

Interesting article about ItemAdding, and ItemUpdating.
Apparently you cannot get access to the properties.ListItem with the new values to be written , as Microsoft say it's by design.
You must use:


properties.AfterProperties["_INTERNALFIELDNAME_"]
Read more at:

Sharepoint URLs Becareful!

Sharepoint URL's can contain the ' character, which can break your code, for example a custom sitemap provider.

Friday, 12 June 2009

Replace CreatePage.aspx to run your own Code

On the SiteActions menu it is possible to replace or delete the existing options or even add more.

By editing the CustomAction.xml file in the _catalogs/masterpage/Editing Menu/

The xml below shows you how to replace the Create Page option and use your own custom page instead.

Code will be uploaded soon.

CreatePage.aspx

I had a require the other day from a user, they wanted to remove certain page layouts from the CreatePage depending on a certain user.

We found that this couldn't be achieved with user permissions so instead I copied the CreatePage.aspx, inherited the class, and manually filtered the avaiable page layout.

If logic behind it goes, if the user belongs to a certain group then hide certain layouts from them.

The usergroup and layouts to hide come from the Web.config.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace Leelodharry.Sharepoint
{
public class CreateIntranetPage : Microsoft.SharePoint.Publishing.Internal.CodeBehind.CreatePagePage
{

protected override void OnLoad(EventArgs e)
{
Microsoft.SharePoint.Publishing.Internal.WebControls.DropDownListWithDetails dd = this.pageTemplatePicker;


base.OnLoad(e);

if (!IsPostBack)
{
Microsoft.SharePoint.Publishing.Internal.WebControls.DropDownListWithDetails.ItemInfo[] ItemInfoArray = dd.DataList;

string id = dd.DropDownListId;
DropDownList drop = (DropDownList)dd.Controls[0].Controls[1];


System.Collections.IDictionary stsh = (System.Collections.IDictionary)System.Configuration.ConfigurationSettings.GetConfig("PageLayoutRestriction");
string FindGroup = (string)stsh["UserGroup"];


SPUser user = SPContext.Current.Web.CurrentUser;

bool IsAMember = UserIsMemberOf(user, FindGroup);

if (!IsAMember)
{
string LayoutAttributeValue = (string)stsh["CanSeeLayouts"];
string[] RestrictedLayouts = LayoutAttributeValue.Split(',');

for (int idx = 0; idx < RestrictedLayouts.Length; idx++)
{
string RemoveLayout = RestrictedLayouts[idx].Trim();

FindAndRemove(drop, RemoveLayout);
}

}



}

}


///
/// Checks to see if a user is part of a group
///

///
///
///
private bool UserIsMemberOf(SPUser user, string FindGroupName)
{
FindGroupName = FindGroupName.ToUpper();
int idx = 0;
bool Found = false;

while (!Found && idx < user.Groups.Count)
{
SPGroup group = user.Groups[idx];
if (group.Name.ToUpper() == FindGroupName)
{
Found = true;
}

idx++;
}

return Found;
}


///
/// Find and remove a string in a dropdown.
///

///
///
private void FindAndRemove(DropDownList dropdown, string FindText)
{
FindText = FindText.ToUpper();
bool Found = false;
int idx = 0;
while (!Found && idx < dropdown.Items.Count)
{
ListItem Item = dropdown.Items[idx];

string ItemText = Item.Text.ToUpper();

if (ItemText.Contains(FindText))
{
dropdown.Items.Remove(Item);
Found = true;
}

idx++;
}
}


}
}

Sharepoint and Body Onload

If you want some custom javascript code to run onbodyload event in a page layout, then you must use the following javascript syntax:


_spBodyOnLoadFunctionNames.push("");

i.e.:


RichHtmlField Gaining Focus on Edit Issue

On a custom page layout, I have a few controls on the page, a few of these being RichHtmlField.

If I Edit page, focus is automatically set to the first RichHtmlField control on the page, IE will also scroll to the position where it's located and the cursor will blink in the contents of the field, the user can then start typing, however the changes when saved do not persist for the field.

We found however if you Edit Page, then click on the 'Edit Content' or click into the RichHtmlField, this will activate the editor, then any changes we made then get saved. This however is not ideal, as the control shouldn't automatically gain focus in the first place.

I have compared the OTB page layouts, and they do not have the same behavouir, When you click Edit Page, no control gains focus, you have to manually click into the RichHtmlField to edit content.

The question is why is it automatically gaining focus and how do we stop the RichHtmlField from gaining focus when the page is loaded in Edit mode?

Well I didn't find the answer, but I did come up with a work around, and that was to set focus to the 2nd text control in the page.

Why the 2nd I hear you ask?, well becuase the first control is the search input field.

Below is the javascript code that will achieve this:

function SetFocus()
{
var theForm = document.forms['aspnetForm'];
var elementCount = theForm.elements.length;

var controlcount=0;

for(var idx=0; idx {
var ele = theForm.elements[idx];

if ( ele.type == 'text' )
{
controlcount++;
if ( controlcount==2 )
{
ele.focus();
break;
}

}

}

}

Common tasks in Sharepoint

I have written a simple class which allows you to do many sharepoint things, such as create a web instantate a page based on a certain layout.

This class can be used from a console app, inside a feature , a web part or an aspx page.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Publishing;
using System.Collections.Specialized;
using System.Collections;


namespace Leelodharry.Sharepoint
{
public class Utils
{


///
/// Sets a webs welcome page.
///

///
///
public static bool SetWelcomePage(SPWeb web, string welcomepage)
{
try
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);


PublishingPageCollection pagecollection = pubWeb.GetPublishingPages();
PublishingPage page = pagecollection[welcomepage];


pubWeb.DefaultPage = page.ListItem.File;
pubWeb.Update();
}
catch
{


return false;

}

return true;
}


///
/// Deletes a page given it's web and it's page i.e. pages/default.aspx
///

///
///
public static bool DeletePage(SPWeb web, string pagename)
{
try
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

PublishingPageCollection pagecollection = pubWeb.GetPublishingPages();

PublishingPage page = pagecollection[pagename];


page.ListItem.Delete();
}
catch
{
return false;
}

return true;

}

///
/// Create a page publish and approve it.
///

///
///
///
public static bool CreatePage(SPWeb web, string pagename, string pagelayout)
{

try
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

//find layout from list.
PageLayout[] layouts = pubWeb.GetAvailablePageLayouts();

PageLayout layout = null;


for (int idx = 0; idx < layouts.Length; idx++)
{

layout = layouts[idx];

if (layout.Name.ToUpper() == pagelayout.ToUpper())
{
break;
}
}

if (pagelayout == null)
{
return false;

}



PublishingPageCollection pagecollection = pubWeb.GetPublishingPages();

PublishingPage page = pagecollection.Add(pagename, layout);

//include in navigation can be set.

page.CheckIn("EIG Homepage");

SPListItem litem = page.ListItem;
litem.File.Approve("Approved");
}
catch
{
return false;
}


return true;
}



///
/// Cleans slashes from a URL.
///

///
///
public static string CleanURL(string url)
{

return url.Replace("//", "/");

}

///
/// Sets the web to allow all templates and all page layouts.
///

///
public static void SetAllPagesAndTemplate(SPWeb web)
{
PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);

pubweb.AllowAllPageLayouts(false);
pubweb.AllowAllWebTemplates(false);

pubweb.Update();
}


///
/// Sets the welcome page in a sharepoint web.
///

///
///
public static void SetDefaultPage(SPWeb web, string fileurl)
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
try
{
SPFile newDefaultPageFile = pubWeb.Web.GetFile(fileurl);

pubWeb.DefaultPage = newDefaultPageFile;
pubWeb.Update();
}
catch { }


}


///
/// Sets a sites logo
///

///
///
///
public static void SetSiteLogo(SPWeb web, string Url, string Description)
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);

web.SiteLogoUrl = Url;
web.SiteLogoDescription = Description;
web.Update();
}



///
/// Changes a web's available page layouts.
///

///
///
///
public static void SetPageLayouts(SPWeb web, string commaseplist)
{
SPWeb RootWeb = web.Site.RootWeb;
SPSite site = web.Site;

PublishingSite pubSite = new PublishingSite(site);
PageLayoutCollection rootPageLayouts = pubSite.GetPageLayouts(true);


string siteurl = Utils.CleanURL(site.ServerRelativeUrl + "/_catalogs/masterpage/");
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);



string[] pagelayoutnames = commaseplist.Split(',');


PageLayout[] pagelayouts = new PageLayout[pagelayoutnames.Length];


for (int idx = 0; idx < pagelayoutnames.Length; idx++)
{

string findPage = siteurl + pagelayoutnames[idx].Trim();

PageLayout layout = (PageLayout)rootPageLayouts[findPage];

pagelayouts[idx] = layout;
}

pubWeb.SetAvailablePageLayouts(pagelayouts, false);
pubWeb.Update();

}

///
/// Given a comma delimited list of available templates this procedure will then set the available sites in sharepoint.
///

///
///
///
public static void SetAvailableTemplates(SPWeb web, string commaseplist)
{
uint LCID = 1033;
SPWeb RootWeb = web.Site.RootWeb;

SPWebTemplateCollection sitetemplates = RootWeb.GetAvailableWebTemplates(LCID);
Hashtable HtSiteTemplates = new Hashtable();


for (int idx = 0; idx < sitetemplates.Count; idx++)
{
SPWebTemplate sitetmp = sitetemplates[idx];
HtSiteTemplates.Add(sitetmp.Name, sitetmp);
}


string[] SiteTemplateNames = commaseplist.Split(',');
System.Collections.ObjectModel.Collection useTemplates = new System.Collections.ObjectModel.Collection();

for (int idx = 0; idx < SiteTemplateNames.Length; idx++)
{
string findTemplate = SiteTemplateNames[idx];
SPWebTemplate template = (SPWebTemplate)HtSiteTemplates[findTemplate];

if (template != null)
{
useTemplates.Add(template);
}

}

web.SetAvailableWebTemplates(useTemplates, LCID);
web.Update();
}


///
/// Configures the "Parallel Approval" WorkFlow
///

///
public static void ConfigureWorkFlow(SPWeb web)
{
SPList pagesLib = web.Lists["Pages"];
SPWorkflowAssociation wf = pagesLib.WorkflowAssociations.GetAssociationByName("Parallel Approval", System.Globalization.CultureInfo.CurrentCulture);

if (wf != null)
{
wf.AssociationData = AssociationData.AssocData;
wf.Name = "Ecclesiastical Approval";
string assocData = wf.AssociationData;

//Update workflow.
pagesLib.UpdateWorkflowAssociation(wf);
}
}

///
/// Gets the nested level in the tree.
///

///
///
public static int GetWebDepth(SPWeb web)
{
int depth = 0;

while (!web.IsRootWeb)
{
web = web.ParentWeb;
depth++;

}

return depth;
}

///
/// Sets the master page for a web.
///

///
///
///
public static bool SetMasterPage(SPWeb web, string masterpage, string custommaster)
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);



try
{
//pubWeb.MasterUrl = masterpage;
//pubWeb.CustomMasterUrl = custommaster;
//pubWeb.Update();

web.MasterUrl = masterpage;
web.CustomMasterUrl = custommaster;
web.Update();

pubWeb.Update();
}
catch
{

return false;
}

return true;
}


///
/// Sets the site's CSS.
///

///
///
public static bool SetCss(SPWeb web, string cssUrl)
{
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
try
{
//pubWeb.AlternateCssUrl = cssUrl;

web.AlternateCssUrl = cssUrl;
web.Update();
pubWeb.Update();
}
catch
{
return false;
}

return true;
}


public static bool CreateSubSite(SPWeb web, string sitedefinition, string title, string description, string url)
{
try
{
web.Webs.Add(url, title, description, 1033, sitedefinition, false, false);
web.Update();
}
catch
{

return false;
}

return true;
}


}
}

Visual Studio 2005 & Sharepoint development

When creating projects that contain dlls which need deploying to the GAC.

use the following Post Build Event on your Visual Studio project:

xcopy $(TargetPath) $(ProjectDir)\GAC\ /I /R /Y

This will copy your dll output from the bin directory into a folder in your project called GAC, the great thing about this is if you switch the Configuration of your project between Debug/Release builds it will update the GAC folder making it easier to deploy.

Thursday, 11 June 2009

Good Tutorial on SPDataSource.

Haven't got round to trying this yet, but it seems pretty good.

http://www.sharepointnutsandbolts.com/2008/06/spdatasource-every-sharepoint-developer.html

Debugging Sharepoint

Try the event viewer to see if Sharepoint as left any tell tale signs.

and also

12 Hive:


C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

In the web.config for the application:

Normally found in the C:\Inetpub\wwwroot\wss\Virutal Directories\

Where is equal to the port number your sharepoint site is using.

In the web.config you can enable the debug settings, like you can for asp.net applications, this is a great help as normally sharepoint will only output the message "Unknown Error" hiding the .net exception, leaving you guessing!

Deploying Sharepoint WSP's

Deploying a solution is a two step process:

First you must upload your WSP into Farm.

Then the solution must be deployed to the servers in your farm , also known as Web Front Ends.

You cannot upload the wsp into the farm using "Central Administration" instead you must use the stsadm tool.

The stsadm tool is located in :

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\



From Cmd line:

SET PATH=%PATH%;C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\


Syntax:


stsadm -o addsolution -filename SharepointDesignerWebPartDemo.wsp


Important!

In order to add a solution into the farm, you will need to ensure that the user you are using to execute the command is a local administrator and also has access to the sharepoint admin database.

If you attempt to run the command without being a local administrator you will receive an
"Access Denied" message., if you are using Windows Server 2008 or Vista you will receieve this error if UAC is enabled, to get round this run the command prompt as an Administrator.



If you receieve "Object not set to a reference" then the account you are using does not have access to the Admin Database.

It's usually not worth setting up an account with these priviledges although good practice says you should set one up so thats it's exact mirror of the Moss Farm Account.

The Moss Farm account can be found by going into IIS, and looking at Identity of the Application pool for the Sharepoint site in question.

Once you have uploaded the WSP into Sharepoint you can either use the stsadm or go to Central Administration and deploy the solution.

I would recommend that you use the GUI, not only becuase it's easier, but it also shows you the progress and failures as it deploys, unfortnately it's not in real time, but if you hit refresh you can see any issues.

Shrinking Virtual PC Images / VMs

To Shrink VM:

Open and Boot the guest OS.

Inside the Guest OS:

Go to disc clean up, remove temp files etc.

Defrag hard drive

Using VPCon the Host, mount "Virtual Disk Precompactor.iso"
which is found in :

C:\Program Files\Microsoft Virtual PC\Virtual Machine Additions

of your Host machine.


Start Iso, this will prepare your virtual hard disk ( go for a coffee )

When done, shutdown the VM.

In VPC choose "Settings" for your image in question, and go to the "Hard Disk 1" section and on the right side you can use the "Virtual Hard Disk Wizard" button.

Choose to edit an image and find your target image and choose to "Compact" it. ( Go away for a week )

When you come back you should have a smaller VM, and a larger electricity bill.

Inconsistencies When running Sharepoint CAML Queries

Something I noticed today:

When using SPQuery if the CAML syntax is invalid you will receive all the results for that list,regardless of any condition you have applied in your CAML.

However if you were to do the same query using SPSiteDataQuery, you would receive no results.

Nice!

CAML Query Schema

Useful links for constructing CAML Queries

http://msdn.microsoft.com/en-us/library/ms467521.aspx

Useful link for ViewFields:

http://msdn.microsoft.com/en-us/library/ms442073.aspx


When quering on datetime values, by default CAML will only query on the Date portion, to include the time use the following :

<value includetimevalue="TRUE" type="DateTime"> <today> </value>

Tuesday, 17 March 2009

Welcome!!!

Hi and welcome to my Blogg.