Thursday, 28 January 2010

Creating Custom Controls - Back to basics

Sometimes you just need to stop and go back to the basics.

Yesterday I had some problems with nested controls in a custom control that was added to a Web part. The nested controls were losing their post back information, in the end it came down to a forgotten Interface, the INamingContainer. The INamingContainer is that small piece of magic that gives your composite control a new ID Namespace which uniquely identifies your control and all of its sub controls.
It is also worth noting that you need to add the child controls to the collection before setting their values for the TrackViewState() to be called, though you can do this manually.

Now I am going back to my old reference books to see what else I have let slip.

Wednesday, 22 July 2009

Anonymous Access SharePoint WCM Site prompting for login in IE only.

Watch out for those SharePoint anonymous access demons, while a new site that I have been working on was going through testing on its way to UAT we encountered an odd bug where only IE 6-8 would request a login box when loading some pages, we traced this down to one Custom control that was pulling an item from a SharePoint list and displaying some images with their description.

As this was not an issue in other browsers we concluded that it was not the control or a case that the images were not published (though we checked to be sure), after a long night and a few tufts of hair lost to frustration I had a look at the html output, there plain as day was the culprit, an image tag with no alt or source, I have come across this before and could kick myself for it but what happened was the developer simply fetched the value of the image field and rendered the html supplied by SharePoint. When no image Url is supplied SharePoint outputs a blank image tag like this <img src=”” alt=””></img>, this tag causes IE to try and authenticate the user(don’t know why never botherd to look any deeper).

So the lesson learnt Don’t trust SharePoint’s Html it can be a Demond in disguise.

Tuesday, 21 July 2009

SharePoint 2010 and the NDA

I have been lucky enough to be working with the next release of SharePoint 2010 through the TAP program and have wondered what I can and can’t say about it, Joel Oleson has recreantly posted a helpful blog in regards to what we can and can’t say(What’s Up? NDA or NOT? Office 2010 Technical Preview vs. SharePoint 2010 Technical Beta), Till the NDA is lifted I won’t be saying much other than so far I have found 2010 to be looking really good and I can’t wait for it to move on to RTM.

For those that are interested.
My SharePoint 2010 environment is all beta/rc at the moment
Windows Server 2k8 R2 RC hyper-v Host with Windows Server 2k8 R2 RC VMs
With SQL 2008 running as the backend database on one.

So far so good, look forward to sharing what I have found in the future.

Friday, 8 May 2009

Finding the language packs installed on a SharePoint Server

I spent a hour or sow looking for a way to find all the installed languages on a server so I could update one of the XML files via a feature (I will post later about Installing a Theme across multiple front end servers targeting multiple languages).

The file I want to modify was SPTHEMES that is located at TEMPLATE\LAYOUTS\{LCID}\SPTHEMES.XML, There is a unique file for each language.
I thought that there must be a class in the OM that would allow me to get the installed languages. After diving in to the SPFarm object, digging in the NewSitePage class and a number of web searches while still getting no where I stumbled on the most simple class. (YaY for Reflector)

SPRegionalSettings and its GlobalInstalledLanguages property.

SPRegionalSettings.GlobalInstalledLanguages is a collection of SPLanguage objects.
each SPLanguage object is a simple data object that contains DisplayName and a LCID propriety.

so with this simple for loop I managed to avoid messing around with searching through the File system.

foreach (SPLanguage language in SPRegionalSettings.GlobalInstalledLanguages)
{
DoSomthingWith(language);
}

Sometimes the simple solution takes the longest to find.
Hope this helps someone.

Tuesday, 5 May 2009

A New SharePoint blogger

One of my bosses has started blogging about his experiences skinning SharePoint sites and the work he has done to create a simple CSS frame work that can be used Making SharePoint Beautiful

More than worth a look at some of the secreats behind the magic he has created.

Wednesday, 18 March 2009

SharePoint Best practices conference - UK

Looking forward to the SharePoint Best Practices Conference in London comming up this April

for more info see

Thursday, 5 March 2009

Twitter And Me

Well i have made the jump in to the Twitter pond you can find me at http://twitter.com/jcvivian not that there will be mutch looking at my blogging history :P

I am trying out the Blu Client though TweetDeck and the like seem to be better clients i just cant bring my self to install yet another platform, I dont have java installed for the same resion.

John

FBA Login Page - Images not showing when user is Anonymous

I have been doing a lot of work with FBA and custom membership providers and here is something that is so simple but nearly caught me out.
The Client was happy with the way the login worked but complained that the styling was different from the rest of the site. So one of our designers put together a Simple.Master based on the main master pages styling and a custom CSS.
So we added this to our solution and deployed it to our staging environment.
The login page loaded fine but neither the CSS file nor the images were being pulled through leaving the login page looking worse than before. At first thought I was a little confused as the CSS and the images were stored in a Layouts/{Project Name}/CSS and Images folder and worked fine once a user was logged in. Then I realised exactly where I had gone wrong, The Layouts folder is only accessible to authenticated users, this is not only expected but wanted. So as WSS is based on ASP.Net we can open a path to our CSS and Images folders to allow Anonymous users to see the files and only these files.
We added the following to the Web.Config

<location path="_layouts/{Project}/images">
<system.web>
<authorization>
<allow users="*">
</allow>
</authorization>
</system.web>
<location path="_layouts/{Project}/CSS">
<system.web>
<authorization>
<allow users="*">
</allow>
</authorization>
</system.web>

It would have been possible to place the Images in the Images folder but I prefer to keep all Custom files in the layouts/{Project Name} format as it makes it easier for admins to track the changes our solution has made to their servers.
Also to note there is nothing in these folders that would be need to be protected however there are some files in the layouts/{Project Name} that should only be available to authenticated so we could not just open up the entire Folder.

Any way just something small that helped.

Sunday, 25 January 2009

Moving On

It has been a while since my last post.

Thing have been really busy for me as I changed jobs in October.

I am now working for Brightstarr leading their SharePoint development team.

BrightStarr concentrates more on the usability and look and feel customisations as opposed to the backend integration and Business layer side. Their aim is the make the users want to use SharePoint because it is fun and looks good.
So the last few months I have had to brush up on my UI layer, Web 2.0 and what makes a website usable. All in all it has been a great few months and some of the projects that I have been working on really need a second look to see that it is really running on SharePoint with all its out of the box goodness.

Well I hope I will get some time to post some of the Web 2.0 SharePoint things I have been up to with My Sites and some of the interesting front end web parts.

Friday, 5 September 2008

Creating Custom Meeting Workspaces Site Definitions

My college was working on a project that needed to create a custom Meeting Workspace site definition.

The simple answer would be to create a copy of the site definition and work from there
However as quite often SharePoint is not quite so simple.

The problem comes in the form of 3 web parts embedded in the MasterPage. These web parts check to see that the webTemplateId of the current SPWeb object is equal to 2 (which is the ID of the MPS templates In the webtemp.xml). These web parts then fail to render breaking the site.

He had located the problem but was unable to find a acceptable workaround.
1) He could modify the OotB MPS Site Definition (This is NOT acceptable practice)
2) He could use a feature stapler to modify the Site Definition on creation(This would apply to all new Meeting Workspace across the Farm and not really practical given the project)
3) he could remove the Web Parts and replace them with custom ones (the classic developer answer but never a practical one)

None of these option were really viable for his project.

So I asked him if he had thought of using a SPWebProvisioningProvider class.
With a little testing we found that the SPWebProvisioningProvider does not change the WebTemplateID as the Site Definition used during the provisioning of the site is still the OotB MPS Definition and the Provisioner runs code After the site had been created.

He can now create a Customised Meeting Workspace site definition.
the SPWebProvisioningProvider class he is using is quite small as all it does is activate and deactivate a few features, this allows for easy modification of the features rather than having to recompile the provisioner should the client wish to change anything.

Just something that popped up today :)

Creating and attaching Information Management Policies

I haven't posted anything for a while and here is something I meant to post
Sorry for the formatting issues with the code Hope this Overview helps.

Background information about information Policies
Polices are defined in xml markup
A skeleton Policy described in xml.

<p:Policy xmlns:p="office.server.policy" id="" local="true">
<p:Name></p:Name>
<p:Description></p:Description>
<p:Statement></p:Statement>
<p:PolicyItems>
<p:PolicyItem featureId="">
<p:Name></p:Name>
<p:Description></p:Description>
<p:CustomData>
<data>
</data>
</p:CustomData>
</p:PolicyItem>
</p:PolicyItems>
</p:Policy>

Note the Policy id attribute takes a string that uniquely identifies this policy
Example “Microsoft.Office.RecordsManagement.Policy”

Each policy contains a number of Policy Items
A Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration Policy Item defined in xml.

<p:PolicyItem featureId="Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration">
<p:Name>Expiration</p:Name>
<p:Description>
Automatic scheduling of content for processing, and expiry of content
that has reached its due date.
</p:Description>
<p:CustomData>
<data>
<formula id="Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn">
<number>0</number>
<property>Created</property>
<period>days</period>
</formula>
<action type="workflow" id="" />
</data>
</p:CustomData>
</p:PolicyItem>

These Policy items are used to configure the Policy Features for this Policy.
See Stegeman Blog for more information on how to create your own custom Policy Features.

Managing Information Management Policies via Code
Creating a Information Management Policy
The Policy needs to be defined in xml markup. This definition can then be passed to the
Policy.ValidateManifest () method that will validate the XML against the Policy Xml schema.
Once the policy has been validated it can be added to the policy collection using the PolicyCollection.Add () method

Example

string xmlManifest = generatePolicyXML(policyId,
Name,
string.Empty,
string.Empty,
FieldName,
WorkflowAssociationId);

Policy.ValidateManifest(xmlManifest);

PolicyCollection.Add(site, xmlManifest);

In this example I am generating the XML Manifest using a method and passing it various parameters once we have the xmlManifest string populated I pass it for validation to the Policy.ValidateManifest (string) method (Note this will through an exception that explains why it is unable to validate the XML) and then I add it to the Site via the PolicyCollection.Add (SPSite, string)

Retrieving a Information management Policy for a Site
To retrieve an Information Management Policy for a site we need to first get the Policy Catalog for that site and then retrieve the Policy from the catalog. We retrieve the Policy Catalog by creating a new PolicyCatalog object passing the SPSite object to the Constructor. We can then access the PolicyList collection of the new PolicyCatalog object to retrieve the Policy.

Example

using (SPSite site = new SPSite(siteId))
{
PolicyCatalog policyCatalog = new PolicyCatalog(site);
Policy returnPolicy = policyCatalog.PolicyList[policyId];

if (returnPolicy != null)
{
//Code to run aganst the new Policy Object …
}
}

In this example I am creating the SPSite object from a Guid that is the Id for the site. Once I have the site object I pass it to the PolicyCatalog Constructor to create a new PolicyCatalog object that relates to the site. Once I have the PolicyCatalog for the site I can use its PolicyList Collection to retrieve a Policy using the Policy’s Id. Note that if a Policy does not exist with the supplied Policy ID then the Collection returns null so I check the returned Policy is not null before running code against it.

Attaching a Information Management Policy to a Content Type
To attach a Site Information Management Policy to a Content Type, we first need to fetch the site policy and then attach it to the Content Type using the Policy.CreatePolicy () passing it the Policy and Content Type.

Example

using (SPWeb web = site.OpenWeb())
{
SPContentType contentType = web.ContentTypes[contentTypeId];
if (contentType != null)
{
Policy.CreatePolicy(contentType, policy);
}
}

In this example I fetch the SPWeb Object and use it to fetch the Content Type with the supplied Content Type ID. Once I have the Content Type I check that that the returned value is not null and then I pass it to the Policy.CreatePolicy (SPContentType, Policy). Note a content type can only have one policy attached at any time and it may be best to check that the content type does not have a policy attached by testing that the Policy.GetPolicy (SPContentType) method returns null and not a Policy object else the Policy.CreatePolicy () method will through an exception.

Configuring the Expiration PolicyFeature

Creating an Expiration PolicyFeature Formula
The Expiration PolicyFeature has a custom data node that defines the when the item will expire. This is stored in the formula node.

Example

<formula id="Microsoft.Office.RecordsManagement.PolicyFeatures.
Expiration.Formula.BuiltIn">
<number>0</number>
<property>ERMExpiryDate</property>
<period>days</period>
</formula>


The Formula id Points the out of the box, built in formula
Number refers to the number of units to append to the date
Property refers to the Field in the item to retrieve the date from
Period refers to the unit that the number represents.
There are 3 period options: days, months, years.

Creating an Expiration PolicyFeature Action that calls a Workflow
The Expiration PolicyFeature has a custom data node that defines what action should be taken once the Item has expired. We want to start off a workflow so our XML looks like this

Example

<action type="workflow" id="feebb1e3-68f0-40ce-8dc0-e297814680ab" />


I define the type of action to be workflow and set the id to point the ParentAssociationId of the Content Types Workflow Association.
Setting this ID is one of the resigns that have not been able to get around in CAML.
This Guid is neither the Workflow Associations Id nor the Workflow Template ID but the Parent Association Id of the Workflow association.

Resources
MSDN
Introduction to Information Management Policy
Policy Schema Overview
Private Blogs
MOSS Custom policies part 1 - Creating a custom information management policy

Wednesday, 16 January 2008

SPFieldCollection indexer (Field[string]) Vs SPFieldCollection. GetField(string)

The Question can be asked don’t they do the same thing and reading the SDK doesn’t clear that up (see http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.aspx )
So a bit of work with Reflector and the difference becomes apparent

The Indexer calls the internal method GetFieldByDisplayName(strDisplayName, true)
Which in turn accesses the Display Name Hashtable using the parameter as the key value DisplayNameDict[strDisplayName];
(Note the second Pramater of GetFieldByDisplayName is a bool which sets if the method will throw any exceptions)
GetField(string) calls GetField(strName, true) which in turn will call GetFieldByInternalName(strName, false) which accesses the Internal Name Hashtable using the parameter as the key value InternalNameDict[strName] if this fails to return a value it accesses the InternalNameWithPrefixDict Hashtable. If GetFieldByInternalName fails to return a value GetField will make a call to GetFieldByDisplayName(strName, false)

In practice how does this help
The Indexer only works with Display Names while the GetField() will look for the internal name first but if it can’t find a field it will then try the parameter as the display name. This matches up nicely with the ContainsField(string) method as this method will return true if the string is found as ether a display name or a internal name. Using this we have a nice way of avoiding unnecessary exception handling when accessing List data

Eg
if (item.Fields.ContainsField(_fieldName))
{
holderstring = item[_fieldName].ToString();
}

Not checking to see if the field exists can cause a System.NullReferenceException - Object reference not set to an instance of an object on the ToString() method

Note there is also a GetFieldByInternalName(string) which will only call GetFieldByInternalName(strName, false)

Been a while

It has been a while (6 months) since my last post and in that time I have acquired ownership of some rather messy projects (Please I am begging people don’t modify out of the box files even if you think you know what you are doing because most likely YOU DONT …. ok maybe Application.master and the like but then again only if absolutely necessary and you and your client understand what Microsoft has to say http://blogs.msdn.com/sharepoint/archive/2007/10/30/kb-944105-how-to-customize-application-pages-in-the-layouts-folder-in-wss-3-0-and-moss-2007.aspx ) and passed my MCTS - WSS 3.0 Application Development gotten engaged and learnt a lot about WSS and MOSS and to be honest ASP.NET

I will try and Blog all of what I have discovered and where I went badly wrong over the next few months and return what I can to the SharePoint community.
Hope to post more as time goes on :)

PS I would like to see more internet facing WSS 3/Moss sites on the web they are easy to develop and even easier to maintain for the non technical minded.

Tuesday, 17 July 2007

Creating a New My Sites or adding My Sites to a Moss Portal
The other day I had to add My Sites to a client Moss Site

Firstly create a My Sites Web Application
Central Administration > Application Management > SharePoint Web Application Management:
Create or extend Web application

Then create a My Site Host Site Collection
Central Administration > Application Management > SharePoint Site Management:
Create site collection
Remember to set the site template as Enterprise>My Site Host

Now add a managed path if you don’t plan to use Sites as your location
Central Administration > Application Management > SharePoint Web Application Management:
Define managed paths
Add your Location as a wildcard path.
Next go in to your SSP
User Profiles and My Sites: My Site settings
Change the
Personal Site Services: to your new Web Application
And change
Personal Site Location: to your new location you defined earlier

And there you have it a new My Sites.

Monday, 9 July 2007

Adding Google as a search scope

Well the title is prehaps miss leading but you can trick MOSS in to using Google as a search scope.

Firstly how do we get google working with in a Moss site
As Google is droping thier Web service api (which was limated to 1000 quires a day) and are promoting thier Ajax API i will describe how to use the Ajax API.
We will use a CWEP (Content Editor Web Part) and drop some custom code in to the Source section.


<link href="http://www.google.com/uds/css/gsearch.css" type="text/css" rel="stylesheet">
    <script src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0&key=REPLACE_ME" type="text/javascript"></script>
    <script language="Javascript" type="text/javascript">
    //<![CDATA[     function OnLoad() {       // Create a search control       var searchControl = new GSearchControl();       // Add in a full set of searchers       searchControl.addSearcher(new GwebSearch());       searchControl.addSearcher(new GvideoSearch());       searchControl.addSearcher(new GblogSearch());       searchControl.addSearcher(new GnewsSearch());       searchControl.addSearcher(new GbookSearch());              // draw in tabbed layout mode       var drawOptions = new GdrawOptions();       drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);       searchControl.draw(document.getElementById("search_control_tabbed"), drawOptions);       // Execute an inital search       searchControl.execute(cleanup(getQval("k")));     }     GSearch.setOnLoadCallback(OnLoad);     //]]>
    function cleanup(str)
    {
      str = str.replace(/%22/ig, "\"");
      str = str.replace(/\+/ig, " ");
      str = str.replace(/%20/ig, " ");
      str = str.replace(/%2B/ig, "+");
      return str;
    }
function getQval(name)
{
var m, Q = window.location.search.substring(1);
if ('' != Q)
{
var re = new RegExp(escape(name) + '=([^&$]+)');
if (m = Q.match(re))
return m[1];
else return '';
}
return '';
}


    </script>
<div class="search-control" id="search_control_tabbed">Loading</div>
<div id="error"></div>




Replace the REPLACE_ME with your google API key which you can get here
http://code.google.com/apis/ajaxsearch/signup.html
NOTE espaly for corprate clients they must read and approve of the tearms and conditions in relation to Google's API key

The Google part of the code is in the OnLoad()
and you should be able to easly modfy it to your own needs just explor the API

the rest of the fuctions are there to tokenise the URL string so make the search work from a search scope
the cleanup(str) fuction is used to reformat the URL token in to plain text.

the getQval(name) Gets the url tokens for the search string. Since i am just lazy and not much of a javascript programer this is just a cut and past from this Forum all credit goes to RobB and Michael Winter.
http://www.thescripts.com/forum/thread149745.html

now you have a google search webpart
go to the Search colection in your portal
Add two pages one for Google Search and one for Google Search Results.
Add these pages to the relative tabs.
Drop a Cwep whith the above code.
you now have a search page and a results page that contain a Google search web part

now how to get Moss search scopes to point the results here

go to search scopes ehter in the SSP or at the toplvl of the site colection(recomended for this method)
Create a display groop and call it Google Search Group (or your own name)
Creat a search scope called Google Search that is atached to Search Dropdown and Google Search Group that uses a custon search results page. Point to your newly created Google search results Page were you added the Cwep.

add a rule that will not search anywere (point it to the google search page you created for a minimal search)

now you will have a google search in your defauld search dropdown and any search placed in there will open your Google Search Results page which will display the search results in the Cwep.

one last thing to fix

go edit page on your Google search page and go Modfy sheard webpart on the Search box
Hide the search dropdown and under Mics change the results page to your new Google Search Results and change the Scope (txt box just below) to Google Search Group.
repeat these steps on your Google Search Resluts page

sorry i was in a hurry with this post :P

Monday, 18 June 2007

Adding a document to a Document library

Here is one that stumped me for a while

One of my fellow developers had a web part that needed to convert a xml file to a pdf and then add the pdf to a document library . Well the conversion worked and everything was fine except he couldn’t workout how to get the pdf in to a document library.
There are no overrides on the .Add() method of the SPListItemCollection Class that take File in to account, the .File propriety is only a get and we didn’t know what Field to use. Evan the SPDocumentLibrary class was of no use.

After a bit of head scratching we found that we needed to use the list.Rootfolder.Files.add

This is in the SDK on one line in one of the related classes but I can’t find it again

Hopefully this post will help anyone else that gets snagged on this simple process

A useful tip

The Add method of the SPFilecolection returned a SPFile object
So you can use this code to add your relevant meta data

SPFile newFile = list.Rootfolder.Files.add( fileURL, fileStream);
SPListItem fileItem = newFile.Item;



Hope that help

Tuesday, 12 June 2007

Noooo SharePoint Blogs is down

SharePoint Blogs is down...
One of the best resorces bor a bumbling MOSS newbee developers like my self
But there is light at the end of the tunnel as it is all is not lost
Thanks to Andrew Connell posting info on the problem
SharePointBlogs.com public service announcement

Heres to hoping you will be back up and running soon

Monday, 11 June 2007

Stsadm export / import comand Errors to catch us

Migrating a sub site from one location to another within a single Site Collection.

After a short search you will find that most places point you towards Stsadm.exe -export / import and most of these tuts and How to’s are complete so no need to Blog it again (besides I could not do half as good a job) But what I want to highlight is errors that I have come across when using the commands that I can’t find answers to

Firstly the size of the sub site
When using stsadm.exe export the exported data is not written to destination disk till after the export is complete so if the sub site is larger than the free space on the system disk the export will fail.
Not much can be done around this one you can try reduce the amount of information exported by using the –versions command or create your own migration tool using the API’s
If you know any good way around this please add a comment.

Next Lists with e-mail address
If a list has an attached incoming email address and the Portal incoming email settings Directory Management Service is set to yes. The import fails as it can’t create the email address as it all ready exists short of removing all e-mail support from these lists and redoing the export and import then add email association to the newly imported lists
Best way I have found is to drop all list email association and then do the export and import then add the associations to the new lists.
If you know any good way around this please add a comment.

Lets start exposing my lack of anything

Well i read somewere that app developers should have a blog (evan if they have nothing usefull to say) so here are my ramblings.
This blog is about MOSS 2007. I have only started on MOSS and have a measly 1 month of it behind me.