Posts Tagged ‘MOSS’

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

If you are a SharePoint developer, you often need to dig into the logs in the 12-hive in order to find out why things are behaving the way they are.

You and me both know that this can be a pain in the buttocks if you don’t have an appropriate tool to read the logs with.
I’ve been trying out around 10 different log viewers, including SharePoint-specific log viewers, in order to save some time reading the logs.

What I found out, was that the tool called SPTraceView that you an find on www.codeplex.com, is the by far most complete SharePoint logs parsing tool I’ve tried.

Bear in mind though, that there’s plenty of good tools out there – and this is the one that I find to be most suitable for my needs. Your requirements may differ.

Why SPTraceView for me?

The reasons as to why I chose SPTraceView are as follows:

  • Balloon notifications when new events occur (e.g. an exception is thrown and shown in the logs)
  • Filtering
    • Filter based on Monitoring Level
      • Critical Event
      • Unexpected
      • Exception
      • Warning Event
      • Assert
      • Unassigned
      • High
      • Medium
      • Information Event
      • Monitorable
      • Verbose
    • Filter based on Process
    • Filter based on Message
    • Filter based on Product
    • Filter based on Category
  • Big "View Events" button to quickly parse and view the logs, applying all the filters you’ve configured
  • Farm event logging / Cross-server logging
    • You have the option to use SPTraceView across multiple servers in your farm (!)

An example

The plain-text logfiles in SharePoint looks something like this

image

Viewing the SharePoint ULS logs with SPTraceView

If I make a simple configuration like this:

image

And if I now click the big "View Events" button (you really can’t miss it!) – it’ll look something like this:

image

Summary and Download

I urge you to check out this tool if you’re (like me) diving into the logs every now and then, but find it unbearable to read plain-text and don’t find that any of the other tools really fit the blueprint of what you need.

With that said, go to www.codeplex.com/sptraceview and get it now!

SharePoint BDC Part 2: Creating your first BDC Web Part

July 25th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In my previous article (SharePoint BDC Part 1: Getting started with the Business Data Catalog) I talked about what you’ll need to do in order to begin to work with the BCD in SharePoint (MOSS 2007 specifically, as it’s an Enterprise feature).

In this article I will briefly guide you through the process of creating your first BDC Web Part that will communicate with the BDC.

Note: You can download the source code for this sample project here [Download]

Prerequisites

You need to have your BDC set up and ready to use before you can start creating your own BDC Web Parts to communicate with the BDC. (See my previous article for a walkthrough)

We will also use Microsoft Visual Studio (2005/2008) to create the Web Part.

Enjoy!

What we had -> where we’re going

In the previous article I talked about using the built-in Web Parts for your BDC needs. Although they fill a lot of requirements, sometimes you just might want to write your custom Web parts instead.

This is what the standard BDC list looks like:

image

This is what the final result will look like: (Note, this is a custom Web Part which you’ll develop in the following steps)
image

Step 1 – Create a new Web Part project

I will expect that you already know how to create a new Web Part project (either using the VSeWSS or using WSPBuilder, or any other tool of preference).

See this article for a WSPBuilder complete walkthrough: WSPBuilder – Walkthrough of the Visual Studio Add-in

Step 2 – Add the BDC references to your project

Once you’ve got a Web Part project up and running, you should add some references that are needed for the BDC Object Model.

You should add the "Microsoft® Office SharePoint® Server component" reference to your project:
image

Once you’ve added this reference to your project, you have a GO for using the BDC namespaces.

Add the following using-statements to the top of your Web Part:

using Microsoft.Office.Server.ApplicationRegistry.MetadataModel;
using Microsoft.Office.Server.ApplicationRegistry.SystemSpecific.Db;
using Microsoft.Office.Server.ApplicationRegistry.Runtime; (if you need it..)

This is what my Visual Studio project looks like when using the WSPBuilder to create my Web Parts (notice the reference to microsoft.sharepoint.portal which comes from the reference we added):
image

Now we’re good to go! Let’s start coding then!

Step 3 – Utilize the BDC object model to access data

Note, you can download the complete Visual Studio Project at the end of this article with the source code.

Fetches all the LOB instances from the metadata repo:

var myInstances = ApplicationRegistry.GetLobSystemInstances();

 

Fetch the HR instance for Human Resources:

var humanRecourcesInstance = myInstances["HR"];

 

Pick out the Department entity from the HR instance:

var departmentEntity = humanRecourcesInstance.GetEntities()["Department"];

 

Fetches the method GetDepartments which is specified in our ADF file (Application Definition File) for our BDC connection:

var getDepartmentMethod = departmentEntity.GetMethods()["GetDepartments"];

 

Fetches the MethodInstance DepartmentFinderInstance:

var deptFinderInstance =
      getDepartmentMethod.GetMethodInstances()["DepartmentFinderInstance"];

 

We call the departmentEntity.Execute() method to fetch DbEntityInstance’s:

var foundEntities = 
     (DbEntityInstanceEnumerator)departmentEntity.Execute(
                                                                          deptFinderInstance, 
                                                                          humanRecourcesInstance);

 

Simply loop the DbInstances and then shoot out their name in a bunch of literal controls.
In a real scenario, we would most likely add those intances to an SPGridView instead of printing Literals to enable Views, Sorting, Paging and a whole set of awesome features that comes with the Grid View.:

while (foundEntities.MoveNext())
{
    var currentDepartment = (DbEntityInstance)foundEntities.Current;
    Controls.Add(new Literal{Text =
              "<div style=’border-bottom:1px dashed #c0c0c0; width:100%;’>"});

    Controls.Add(new Literal {Text =
              currentDepartment.GetFormatted("Name")+ "<br/>"}); 

    Controls.Add(new Literal { Text=
currentDepartment.GetFormatted("DepartmentID").ToString() }); 

    Controls.Add(new Literal{ Text = "</div>" });
}

When you’ve written the aforementioned code, you will have the base set up for retreiving data from your BDC connection. You will (of course) have to dig a whole lot deeper if you want to master the arts of BDC and the object model that comes with that. But at least it’s a start for you to get to know the namespace, and learn what namespaces to use – and see that it actually works!

Step 4 – Finalize and deploy your Web Part

Once you’ve created the project, build it and deploy to your SharePoint development machine and add your Web part to see the action:

image
(Yes, the Web Part is called SharePointRules BDC Web Part – and for a good reason too!)

Step 5 – May your creation shine upon SharePoint! (aka. Final result)

This is what the creation looks like (wow..), which basically only utilize the most basic aspects of the BDC Object Model to get started – but here you have it in action, fetching data immediately from your back-end SQL server (Adventure Works database in this case) using the BDC:

image

Summary

That’s a wrap for this article. I have walked you through the few simple steps needed to create your own first BDC Web Part.

In my next BDC article I will talk about what alternative tools I find suitable to use for generating your ADF (Application Definition File).

 

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com 

Introduction

In this article I will guide you through the very basics of getting started with Business Data Catalog, BDC:

  1. Install the AdventureWorks 2008 Sample Databases
    1. We will use this database as our example for retrieving data using the BDC.
  2. I will step you through the simple process of creating your ADF (Application Definition File)
    1. We will use this file as our import connection
  3. I will guide you through how we can import this ADF file and create our BDC Application
  4. Lastly, I will guide you through the process of creating a basic site and use some of the basic BDC Web Parts

Install the AdventureWorks sample database

  • You’ll need to go and download the AdventureWorks sample databases
    image
  • Just finish the installation by clicking next a couple of times and let the installer do it’s normal Microsoft-installer magic.
  • You should now see a couple of new databases in your SQL Server Management Studio:
    image
    AdventureWorks, AdventureWorks2008, AdventureWorksDW, AdventureWorksDW2008, AdventureWorksLT, AdventureWorksLT2008

Alright – We’ve got our databases, now we need to start thinking about how we will get data from our SQL server into SharePoint. This is done by creating/generating an Application Definition File (ADF) as you will see in the next section.

Creating the ADF (Application Definition File)

Alright, there’s a few different options to create your ADF (Application Definition File). I will show you how to get started with using the free tool called "Application Definition Editor" that comes with the latest SharePoint Server SDK.

Note: See the bottom section in this article for a summary of links to all resources mentioned in the article.

After you have installed the latest SDK, you can choose to install the "Microsoft BDCTool" located here by default: "C:Program Files2007 Office System Developer ResourcesToolsBDC Definition Editor". Which will give you the following item in your Start Menu:
image

Launch the BDC Application Definition Designer

Click the application and launch the editor. You will see an interface like this:
image

Create or import your ADF file

There’s basically two alternatives when it comes to editing an ADF (Application Definition File).
One is to create a new one (which I will guide you through first), and the other is to import an existing one (which I will show you after the first alternative).

Alt 1) Creating our own ADF file
Now we’re going to connect to our newly created sample-databases and create an ADF file for use with those databases.
  • Click on ADD LOB System
  • Choose Connect To Database
  • You will see a nice popup-dialog where you will be able to enter the connection details to your desired database
    • Enter your connection details, example:
       image
  • You are presented with the "Designer Surface" that looks something like this:
    image
  • In our case, we’re going to use the table called "vEmployee" which exist in the AdventureWorks database in order to pull out some information about our employees.
    • Search for the table called vEmployee and drag it out to the Design Surface
    • Search for the table called vEmployeeDepartments and drag it out to the Design Surface
    • It should look something like this:
      image
    • Make any necessary changes, then click OK
    • You’ll see a view similar to this one after some tweaking:
      image 
    • After you’ve done the necessary changes to your configuration, making sure it’s a valid ADF with proper filters, enumerators and methods or whatever you need in your application then smile, because we’re done with that part!
Alt 2) Importing an existing ADF file

If you don’t want to do everything from scratch or you’ve already got an ADF file that you wish to modify, you can do so by importing an existing ADF file into the Definition Editor. Here’s how:

  • Open the BDC Definition Editor tool, then click the "Import" button in the menu:
    image
  • Browse to your existing ADF file and choose to import it. Simple as that.
    (I am importing a file called BDCAWDW.xml, which contains definitions for Product, Reseller, ProductSubcategory, ProductCategory as shown below)
  • You’ll see the imported ADF file’s structure immediately in the designer, under the prerequisite that your SQL connection string in the ADF file is valid:
    image 

Note: I will not detail how you create filters, finders, methods etc. in this article. You can read more about that here:
http://msdn.microsoft.com/en-us/library/ms145931(SQL.90).aspx

I may cover the topic of ADF-functionality in another article later on.

Generate the ADF file from the designer

I really don’t need to tell you this, but there’s a button called "Export" which you use to export the definition you’ve created using the definition editor to an xml file:
image

Import the ADF file

If we have gotten this far, we might as well get the last few bits in place.
What we now need to do is to import our ADF file into SharePoint, since that’s where it should reside. Follow along with these few simple steps to make sure you’re properly importing your file into SharePoint.

  • Navigate to your Shared Services Provider Administration site (You can access your SSP through Central Administration)
  • You are presented with a section called "Business Data Catalog" where you’ll find a bunch of different alternatives.
  • Make sure you have the permissions to modify the BDC (See the link Business Data Catalog permissions)
  • Click "Import application definition"
    image  
  • Browse for your .xml file and click "OK":
    image
  • You’ll see a progress bar (You don’t see that a lot in SharePoint. I love it!), telling your how the import process is going:
    image
  • When it’s done, you’ll click "OK" and be presented with an overview of your imported BDC Application:
    image
Configure permissions on the BDC Application Definition

In order for all users to be able to select/read data from your BDC Application, you’ll need to make sure they’ve got the appropriate permissions to actually do so.

Usually I do this setting on each of the imported entities, in case you want specific permissions on different entities – instead of on the entire application.

  • Select the DropDown list on your first entity and choose "Manage Permissions":
    image 
  • Choose "Add Users/Group":
    image
  • Enter "NT AUTHORITYAUTHENTICATED USERS" and choose "Select in Clients":
    image
  • Repeat these steps for the other entity as well.
  • You’re done.

Now we have created or imported an ADF file with the Business Data Catalog Definition Editor tool, exported it to an .xml file, imported it into SharePoint, set basic permissions on the entities.

Next, we should make sure that the application works in SharePoint by adding a Business Data Catalog-WebPart to a page.

Use the basic built-in BDC Web Parts

Awesome. Now that we have gotten this far by importing an ADF file into SharePoint and set appropriate permissions on the entities – We’re ready to actually use the ADF connection to view stuff in our database.

Note: I have created a new blank site where I can easily show the built-in BDC Web Parts – so that’s where I am adding my Web Parts.

 

  • Add two Web Parts to your page called "Business Data List" and "Business Data Item":
    (Note that when you’ve configured a BDC application, you’ll see the Business Data web parts)
    image
  • Choose to edit the properties of the Business Data List Web Part:
    image
  • Click the Browse-icon to the right to pop up the BDC entity chooser:
    image
  • It will present you with the following interface (note, BDC applications will of course vary depending on what you have imported..):
    image 
  • Double click the "Employee" type, and then click "OK" in your Web Part property window.
  • Repeat this process for the "Business Data Item" Web Part, and select "Employee" in the BDC Type Picker as well.

Now we’ve got one BDC List Web Part which will list all employees, and one BDC Item Web Part that will display details about the employee we select.

In order for this to work we must connect the two Web Parts.

  • Edit menu of your Web Part -> Connections -> Send Selected item To -> Employee
    image

Test our BDC Application out, and make sure it works!

  • Choose "LastName" then "contains" and enter "smith":
    image
  • Select one of the results by clicking the radiobutton to the left, and see that the result (details) about the Employee shows up in the connected Web Part:
    image 

Resources and links

Summary

This article is a basic step-by-step guide to getting started with BDC in MOSS 2007. I’ve shown you every step from creating the databases required (in our case some sample databases) to creating the ADF file and to finally utilize the BDC connection from a site, using the BDC Web Parts.

In an upcoming post I will talk about how you can create your own BDC Web Parts! Keep your eyes open!

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

Often when developing solutions that has anonymous users enabled, it can be hard to debug them from your local machine – because when you reach a point in your code where permissions higher than anonymous is required, SharePoint automatically tries to identify the user.

This means that if you’re running local development, and is browsing as an anonymous user – everything can be fine until you hit a line of code in your application that requires authentication, you are then automatically logged in.

This makes it rather hard for anyone to truly debug their solutions in anonymous mode.

With this article I’m laying out the tips that I’m using to debug application requiring anonymous users, and making sure that I don’t step up my privileges if the application needs to – I will now get an access denied instead.

Featured Solution that I am using

  • Enable Anonymous access for your web application
  • Enable anonymous access for your site and lists
  • Enable Remote Desktop on your development machine
    • If it is a virtual machine, you’ll also need to give it access to the internet or at least the local network so you can RDP to it using Remote Desktop.
  • Hook up your Visual Studio debugger to the IIS worker process so your breakpoints can hit
  • Use the web browser on your LOCAL machine (not the development machine) to browse your site (remember, it has to be an IP reachable from the local machine – make sure your network settings are valid)
    • This ensures that whenever you hit a point in your code that doesn’t allow anonymous users, it can not impersonate the account of the logged in user, which will result in an access denied exception. (Yes, this is where your breakpoints and debugging skills come in)
  • Now, when the breakpoint has hit – simply remote to your development machine (or use the lagged-out funked-up VPC console.. (no, use RDP!!)) and step through the code, as the breakpoint has hit!

Summary

Debugging anonymously accessible code can be a bit of a pain, but following my mentioned recommendations should make it a bit easier.

I tend to use this technique whenever I’m playing around with anonymous access, least-privilege code and things like that.

Hope it can help someone.

Recover/fetch the Application Pool password

May 18th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

Alright, so we’ve had a few discussions lately regarding securing your SharePoint environments. Not only did I have a discussion about this when I were conducting SharePoint training last week, but we also covered the aspect which is a base for this article: The Application Pool Password is stored in Clear Text.

If you read this article and the code associated, you’ll see how unsafe it can be to run your Application Pool accounts with too much permissions – which leads us in to the discussion about running a least-privileged installation of SharePoint, at all times!

Note: This can also be seen as a way of "recovering your application pool password".

Where can I get/retrieve my Application Pool Password?

Well, there’s plenty of ways to fetch your Application Pool password, but I’m going to give you two possible ways which is fairly easy. One of which you need to be an administrator on the local server, and one where you can be an anonymous user running a web part under elevated privileges <yikes!>.

  • Use the SharePoint Manager to get your Application Pool password
    • Find your Application Pool:
      image

Note: You’ll see that the password for your Application Pool is indicated in clear text, along with the name, ID, User Name etc.

  • Use the following SharePoint object model code to get your Application Pool password:

    image

  • Copy/Paste friendly code:

SPWebService webService =
                SPContext.Current.Site.WebApplication.WebService;

string appPoolName =
                SPContext.Current.Site.WebApplication.ApplicationPool.Name; 
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    var app = new SPApplicationPool(appPoolName, webService);
    var lit = new Literal();
    lit.Text += "Application Pool Name: " + app.Name;
    lit.Text += "<br/>";
    lit.Text += "Application Pool Password: " + app.Password;
    lit.Text += "<br/>";
    lit.Text += "Application Pool User Name: " + app.Username;
    Controls.Add(lit);
});

  • This is what the Web Part would look like, even to anonymous users

    image
     

What can we do to secure our environments then?

First off, you should think about security before you install SharePoint. That’s for sure. Second, you should always perform a least-privileged installation of your SharePoint environment, meaning that e.g. the Application Pool account doesn’t get more permissions than needed.

To see some related articles on how you can correctly install your SharePoint environments, please have a read-through on the following articles:

Summary

This post was merely meant to be a follow-up to the discussions going on, and to enlighten you that there are some things we DO NEED TO CONSIDER with our SharePoint environments, even if they’ve been running fine for quite some time.

Just a heads up.

Z out.

WSS 3.0 & MOSS 2007 Software Development Kit (SDK) 1.5

May 3rd, 2009 by Tobias Zimmergren

On the 24th of April, Microsoft released a new version of their SDK for WSS and MOSS, and we’re now talking about version 1.5.

I suggest that you update your virtual machines (or whatever tech you’re using for your playgrounds) and install the new SDK.

Download

Download WSS 3.0 SDK 1.5
Download MOSS 2007 SDK 1.5

WSS and MOSS: Service Pack 2 Released Today!

April 28th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

Previous major updates for SharePoint related technologies has been:

Today – as promised – Microsoft released the next set of updates called Service Pack 2.

For an overview of major updates and rollups/cumulative updates post SP1, check out my mate Spence’s awesome blog here: http://www.harbar.net/articles/postsp1.aspx

The new WSS 3.0 SP2 brings this to the table:

Quoted from the Microsoft sites in the links section below!

Some big areas of the improvements that the Windows SharePoint Services team wanted to highlight:

  • Faster, more reliable content migration and data backup and restore
  • Reduced memory consumption
  • Smoother upgrade experience
  • Significant database performance adjustments
  • Updated integration for forms authentication
  • Advanced permission management
  • Helpful administrative tools
  • Expanded browser compatibility

The new MOSS 2007 SP2 brings this to the table:

Quoted from the Microsoft sites in the links section below!

Microsoft Enterprise Content Management (ECM)

  • Improves the performance and stability of the content deployment feature and of the Variations feature.
  • Adds a new command to the Stsadm.exe tool. This tool provides the following functionality:
    • Lets a SharePoint administrator use the Variations feature to scan a site for errors, report the errors, and fix certain problems.
    • Finds and repairs missing peer relationships and corrupted entries in the internal variations relationships list.
    • Handles the propagation of large volumes of variations content in a more manageable way.

Microsoft Office Excel and Microsoft Office Access services

  • Fixes Open Snapshot so that snapshots open more reliably, even if there is no SharePoint root site.
  • Fixes display issues that cause calculations to appear incorrect in some cases.
  • Improves connections to cubes by using .odc files in non-English cases.
  • Improves the performance of programmatic scenarios.
  • Fixes conditional formatting in Mozilla Firefox browsers.
  • Improves support for generating Excel Web Access Web parts on new sites.

Microsoft Office Groove Server (64-bit version only)

  • Office Groove Server 2007 Data Bridge now limits the number of file-sharing workspaces to 64 to make sure that all workspaces can be synchronized. This limit applies only to newly added file-sharing workspaces. If you already have more than 64 file-sharing workspaces, you can continue to use them.
  • Improves synchronization reliability.
  • Groove Server 2007 Manager can be installed and run with SQL Server 2008.
  • Improves the Groove Lightweight Directory Access Protocol (LDAP) connectivity and auto-activation functionality.
  • Improves error reporting in the Groove Relay Server.
  • Improves the robustness of Groove Relay Server.

Microsoft Office Forms Server

  • Improves performance of large browser forms on InfoPath Form Services, both for memory usage and for page load time.
  • Improves reliability of Forms Server and of Microsoft Office SharePoint Server by addressing the previous behavior in which an upgrade of an administrator-approved form template triggers an IIS reset.
  • Improves the Digital Signature functionality for InfoPath Forms Services.

Microsoft Office Project Server

  • Modifies the queue service to prevent it from using large volumes of memory over long periods.
  • Improves the performance of certain database table indexes.
  • Improves cost resource functionality. For example, the server now correctly handles tasks that have material or work resources assigned to the same task.
  • Improves certain areas such as resource plans, build team, and the server scheduling engine.

Microsoft Office Search Server

  • Improves the reliability and stability of WSS crawl, of SharePoint crawl, of crawling through a very large corpus, and of backup restore.
  • Introduces a new command to the Stsadm.exe tool that lets a SharePoint administrator tune the Query processor multiplier parameter. For example, the Query processor multiplier can be used to tune the query performance for SSP indexing content sources that have highly restrictive permissions and many duplicates.
  • Improves the accuracy of searches that involve numbers. For example, there is additional support for large numbers in which a comma is used to separate every three digits (for example, 1,000,000), for numbers that are between 9 and 40 characters, and for numbers that are separated by spaces.

Platform support

  • Provides full support for Windows Internet Explorer 8.
  • Provides level 2 browser support for Mozilla Firefox (versions 2 and 3).
  • Provides support for Windows Server 2008

Summary, Links & Downloads

MOSS 2007
Download: MOSS 2007 SP2 Download
KB: MOSS 2007 SP2 Knowledge Base Article

WSS 3.0
Download: WSS 3.0 SP2 Download
KB: WSS 3.0 SP2 Knowledge Base Article

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

This is yet another very simple example of a question I’ve been getting over and over the past couple of months through comments and emails – instead of answering it each time in the mail, I’m simply shooting it out here.

Deleting a Field from a View programmatically

Alright, here’s a good starting point for you to check out if you simply want to remove a field from the view. Simple as that.

SPList list = SPContext.Current.Web.Lists["MyAwesomeList"];
SPView view = list.Views["MyView"]; 

if(view.ViewFields.Exists("MyField"))
{
    bool allowUnsafe = SPContext.Current.Web.AllowUnsafeUpdates; 

    SPContext.Current.Web.AllowUnsafeUpdates = true;
    view.ViewFields.Delete("MyField");
    view.Update(); 

    SPContext.Current.Web.AllowUnsafeUpdates = allowUnsafe;
}

Summary

The aforementioned code is all there’s to it in order for you to get started.
Simple, quick, effective!

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

I’ve been getting a couple of requests to provide details on how you can upload a file or document using the SharePoint Object Model, instead of using the UI.

With this simple article, I’m walking you through the process of uploading any file to your Document Library.

Note; Since this is done through the local API, you need to have this code running on the server. That means that it’s ideal to use in for example a FeatureReceiver or EventReceiver. You cannot run this code on the client in e.g. a Windows Form, then you’ll need to utilize the SharePoint WebServices instead.

Code to upload a file/document to a SharePoint Document Library

Use the following code to get you started in uploading a file using the object model. It really isn’t that hard :-)

// Getting a reference to the document library
var sp = new SPSite("http://localhost");
var site = sp.OpenWeb();
var folder = site.GetFolder("Documents");
var files = folder.Files;

// Opening a filestream
var fStream = File.OpenRead("C:MyDocument.docx");
var contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

// Adding any metadata needed
var documentMetadata = new Hashtable {{"Comments", "Hello World"}};

// Adding the file to the SPFileCollection
var currentFile =
    files.Add("Documents/MyDocument.docx", contents, documentMetadata, true);

site.Dispose();
sp.Dispose();

As you can see in the image below, the metadata "Comments" has been filled in as per the metadata I specified in the code above.

File uploaded using the Object Model

Simple as that. Over and out!

WSPBuilder – Walkthrough of the Visual Studio Add-in

April 8th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net

Introduction

Alright. People have approached me lately and asked me if I could give them a brief introduction to the WSPBuilder extensions available for Visual Studio. Instead of taking all those discussions on one by one, I’ve decided to document some of the main features here. If I’m missing out on something, please let me know and I’ll fill it up.

Bil Simser did a survey with the SharePoint MVP’s and summarized the foremost favorite CodePlex projects in this article. 

In this article I will cover one of my favorite tools – WSPBuilder.

WSPBuilder background

A SharePoint Solution Package (WSP) creation tool for WSS 3.0 & MOSS 2007
No more manually creating the manifest.xml file
No more manually specifying the DDF file
No more using the makecab.exe application

Carsten Keutmann, an MVP and friend in Copenhagen is the brilliant mind behind this awesome application.

The idea behind the WSPBuilder add-in for Visual Studio is that it’s based on any normal "Class library" template – which means that you can easily copy your entire WSPBuilder project to a machine that doesn’t have WSPBuilder and still be able to open the project. – This is something you can’t do with a lot of other extension tools (say, the VSeWSS for example)

WSPBuilder Installation

Just download the latest release of the "WSPBuilder Extensions – Visual Studio Addin" and let the installation guide take you through the most simple process ever – clickety click.

Creating a WSPBuilder project

When you have installed the add-in to Visual Studio, you should now be able to create a new project based on the "WSPBuilder" template.

To kick this off, let’s create our WSPBuilder project:
image

Note: You don’t have to create a WSPBuilder template, you can create a normal Class Library as well. The only thing about a WSPBuilder template is that it will automatically create the "12" folder along with a temporary strong-key so you don’t have to do that right now.

When you’ve created the project, you’ll see a structure like this one in your solution explorer:
 image

The WSPBuilder will create the 12-folder, since it’s good practice to start your projects from the 12-root. It will also add the file "solutionid.txt" which contains a GUID to be used on the .wsp package, for easy reference. You will also get a strong-key generated for you so you don’t have to worry about signing your project right now.

Alright, now that we’re up and running with a blank WSPBuilder project – we should start by adding something to the solution.

WSPBuilder Templates – Overview

In an ordinary fashion, right click on the project and choose Add – New item.
image

Choose the "WSPBuilder" node and you will see an overview over the available templates like this:
image

Let’s walk through each and every one of them! The joy! :-)

Blank Feature Template Overview

A blank feature does exactly what the name implies, it creates a blank feature for you!

I’m creating a blank feature, and naming it to "BlankFeature1" so we easily can distinguish it from the other folders created later on.

With WSPBuilder, when you create a new item based on a template, you’ll get a dialog asking you for some variables – and since this is a feature, it’s going to need a Title, Description and of course a Scope:
image

Your solution tree will be populated with a few new things, in this case the BlankFeature1 that we chose to create:
image

As you will see, you get not only the perfectly correct 12-hive structure – you will also get the feature.xml and elements.xml files created for you, and the feature.xml file can look like this:

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="8e039720-d7df-460a-8d65-c52e47417fdf"
          Title="BlankFeature1"
          Description="Awesome description for BlankFeature1"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>   
  </ElementManifests>
</Feature>

Event Handler Template Overview

With the Event Handler item template, you will not only get the correct 12-structure in your solution – you will also get the reference to "Microsoft.SharePoint.dll" added automatically, since an event handler requires some talking to the SharePoint Object Model.

We will get our feature.xml and elements.xml as normal – but this time the elements.xml is pre-populated with some tags to hook up our event handler:

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="100">
    <Receiver>
      <Name>AddingEventHandler</Name>
      <Type>ItemAdding</Type>
      <SequenceNumber>10000</SequenceNumber>
      <Assembly>Zimmergren.SharePoint.Demo.WSPBuilder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b7201b5590fd1fc0</Assembly>
      <Class>Zimmergren.SharePoint.Demo.WSPBuilder.EventHandler1</Class>
      <Data></Data>
      <Filter></Filter>
    </Receiver>
  </Receivers>
</Elements>

As you can see, the elements.xml file is referring to the assembly called Zimmergren.SharePoint.Demo.WSPBuilder and a class called EventHandler1.

With the magic of WSPBuilder, this class has of course also been created for us and will look something similar to this:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace Zimmergren.SharePoint.Demo.WSPBuilder
{
    class EventHandler1 : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
        } 

        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
        } 

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
        } 

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
        } 
    }
}

Solution Installer Configuration

If you’ve ever used the SharePoint Installer from CodePlex, you know that when you want to use it with your own .wsp file you need to do some adjustments to the configuration xml.

With the Solution Installer Configuration template you will get this configuration automatically created and hooked up with your project. The Setup.exe.config file might look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="BannerImage" value="Default"/>
    <add key="LogoImage" value="None"/>
    <add key="EULA" value="EULA.rtf"/>
    <add key="SolutionId" value="6e23b11d-8460-49a0-b2f1-b8aa78d7c58d"/>
    <add key="FarmFeatureId" value="bb1586eb-3427-483b-baa5-ae5498c47d69"/>
    <add key="SolutionFile" value="Zimmergren.SharePoint.Demo.WSPBuilder.wsp"/>
    <add key="SolutionTitle" value="Zimmergren.SharePoint.Demo.WSPBuilder"/>
    <add key="SolutionVersion" value="1.0.0.0"/>
    <add key="UpgradeDescription" value="Upgrades {SolutionTitle} on all frontend web servers in the SharePoint farm."/>
    <add key="RequireDeploymentToCentralAdminWebApplication" value="true"/>
    <add key="RequireDeploymentToAllContentWebApplications" value="false"/>   
  </appSettings>
</configuration>

Web Part Feature

This is by far one of the most popular templates, as it crates a generic template for your web part and also creates the feature for provisioning the Web Part to the Web Part Gallery.

You will get the elements.xml file configured something like this:

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE">
    <File Url="WebPartFeature1.webpart" Type="GhostableInLibrary">
      <Property Name="Group" Value="MyGroup"></Property>
      <Property Name="QuickAddGroups" Value="MyGroup" />
    </File>
  </Module>
</Elements>

and you’ll get the required .webpart file configured something like this:

<?xml version="1.0" encoding="utf-8" ?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type
        name="Zimmergren.SharePoint.Demo.WSPBuilder.WebPartFeature1,
        Zimmergren.SharePoint.Demo.WSPBuilder,
        Version=1.0.0.0,
        Culture=neutral,
        PublicKeyToken=b7201b5590fd1fc0" />
      <importErrorMessage>
            Cannot import WebPartFeature1 Web Part.
      </importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">WebPartFeature1</property>
        <property name="Description" type="string">
            Description for WebPartFeature1
        </property>
      </properties>
    </data>
  </webPart>
</webParts>

and you will get the WebPartFeature1.cs file created automatically (or whatever you choose to name it) and it usually look like this:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace Zimmergren.SharePoint.Demo.WSPBuilder
{
    [Guid("a043d73d-7418-4918-baed-828a2bc77019")]
    public class WebPartFeature1 : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        private string _myProperty = null; 

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        {
            get
            {
                if (_myProperty == null)
                {
                    _myProperty = "Hello SharePoint";
                }
                return _myProperty;
            }
            set { _myProperty = value; }
        } 

        public WebPartFeature1()
        {
            this.ExportMode = WebPartExportMode.All;
        } 

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                { 

                    base.CreateChildControls(); 

                    // Your code here…
                    this.Controls.Add(new LiteralControl(this.MyProperty));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        } 

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls(); 

                    // Your code here…
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        } 

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}

Web Service Template

The following files will be automatically created for you:

  • 12LAYOUTSWebService1.asmx
  • WebServiceCodeWebService1.cs

WebService1.asmx may look like this:

<%@ WebService Language="C#"
Class="Zimmergren.SharePoint.Demo.WSPBuilder.WebService1,
Zimmergren.SharePoint.Demo.WSPBuilder,
Version=1.0.0.0,
Culture=neutral,
PublicKeyToken=b7201b5590fd1fc0"  %>

WebService1.cs may look like this:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace Zimmergren.SharePoint.Demo.WSPBuilder
{
    [WebService(Namespace = "http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
  </ElementManifests>
</Feature>

FeatureWithReceiver1.cs might look like this:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace Zimmergren.SharePoint.Demo.WSPBuilder
{
    class FeatureWithReceiver1 : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            throw new Exception("The method or operation is not implemented.");
        } 

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            throw new Exception("The method or operation is not implemented.");
        } 

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            throw new Exception("The method or operation is not implemented.");
        } 

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}

Sequential Workflow Feature and State Machine Workflow Feature Templates

Creates the necessary files to get started with your Sequential Workflow code.

  • 12TEMPLATESequentialWorkflowFeature1elements.xml
  • 12TEMPLATESequentialWorkflowFeature1feature.xml
  • WorkflowCodeSequentialWorkflowFeature1.cs
  • WorkflowCodeSequentialWorkflowFeature1.designer.cs

The same routine applies to the State Machine Workflow Feature template.

 

Web Part Without Feature

Finally, you can create a Web Part without the feature – basically just creating the .webpart file and the .cs file.

  • 80wpcatalogWebPart1.webpart
  • WebPartCodeWebPart1.cs

Solution tree overview

Since I’ve been bashing all kinds of templates in here, you’ll see that there’s a huge tree of files – all automatically created in less than 1 minute.

image

Template Overview Summary

Alright, the templates I’ve been mentioning before are great to get rolling with a new SharePoint project. But what about deployment of this solution? How do we create our .wsp file, and how do we choose where the files should land (Global Assembly Cache – GAC – or the /bin folder?)

That’s what the next section is all about – bringing some clarification to how the WSPBuilder creates your packages.

WSP Creation and Deployment with WSPBuilder

So, when we’re satisfied with our awesome project and want to build a .wsp package from it – we can simply choose to right click the project -> WSPBuilder -> Build WSP and it will automatically create the .wsp for us:
image

This will create a .wsp file in your project folder like so:
image

Now, if you want to check the contents of the .wsp package, you simply rename the .wsp file to .cab and open it, like so:
image

Manifest.xml

In the cabinet (.wsp package) you will find the file called Manifest.xml - this is the file that tells SharePoint where to actually deploy the solution – GAC or BIN.

If you don’t do any changes at all, this file will look something like this:
image

As you can see, the DeploymentTarget is set to "GlobalAssemblyCache"  and your dll will go into the GAC.

Now, in this particular case we can not deploy to the /bin folder anyway – as we have types in our assembly that MUST go into the GAC (Workflows and EventReceivers are two of those types).

But if we were to have a Web Part project or what not – and we want to deploy it only to the /bin folder, follow along with the next few steps.

Scoping the assembly for BIN instead of GAC (including Code Access Security generation)

Okay. So you don’t want it in the GAC, but in your BIN folder instead. That’s okay, just follow along with these few simple steps:

  • Remove your /bin/debug folder entirely from your solution (make sure the .dll gets wiped)
  • If the 80-folder in your project root isn’t created – create it
    • Create a folder called "bin" folder in the 80 folder
    • Your solution tree should look something similar to this:
      image
    • Right click your project and choose "Properties"
    • Choose the "Build" tab
    • Change the Output path from "binDebug" to "80bin":
      image

When you build your project now, your .dll should pop into the "80bin" folder in your solution tree like this:
image

Ready to Rock – Scoping the assembly for the /bin folder

If we go about building our .WSP package again (right click project – WSPBuilder – Build WSP) and rename the .wsp to .cab and check the manifest.xml file – we should see two things done different:

  • DeploymentTarget is set to WebApplication (any chosen WebApp, e.g. /bin)
    image
  • Some general CAS (Code Access Security) permissions has been automatically added to make your assembly run:
    image

Deployment with WSPBuilder

Okay. So we’ve created our project, scoped it either for GAC (do nothing) or for /bin (make the changes in the previous section) – and we want to deploy it. What do we do?

  • Right Click the Project -> WSPBuilder -> Deploy
    Your output window will show something like this:
    image

Check your Solution Management in Central Administration under the tab "Operations" and make sure it’s successfully deployed:
image

Conclusion and Summary

This post simply walks through some of the more popular features of the WSPBuilder created by my pal Carsten Keutmann in Copenhagen.

If there’s any questions or comments – please add them in the comments section below.

Thanks

Microsoft SharePoint Designer 2007 is now officially FREE

April 2nd, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Download SharePoint Designer for Free!

For a few weeks there has been a numerous people spreading the rumor that SharePoint Designer is going to be a free download.

Today Microsoft made it official, and we can gladly share the word: Microsoft SharePoint Designer 2007 is now a FREE download for anyone.

If you register the product, you’ll even get free customized support!

More details on the product here:
http://office.microsoft.com/en-us/sharepointdesigner/FX100487631033.aspx?ofcresset=1

Link to download section here:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=baa3ad86-bfc1-4bd4-9812-d9e710d44f42

Quote from the Microsoft Download site

SHAREPOINT DESIGNER 2007 IS NOW FREE! Be sure to watch the video in the "Related Sections" below to learn more about details and future direction. Office SharePoint Designer 2007 provides the powerful tools you need to deliver compelling and attractive SharePoint sites and quickly build workflow-enabled applications and reporting tools on the SharePoint platform, all in an IT-managed environment.

Ten (10) Free SharePoint Themes – Visual Overview

March 23rd, 2009 by Tobias Zimmergren

As many of you already have seen, there’s a set of free themes out there for use with your SharePoint sites. They can be downloaded here:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=0a87658f-20b8-4dcc-ad7a-09ad22641f3a

These themes are to be used with the Visual Studio 2008 Extensions for SharePoint (VSeWSS)

Article Overview

I got myself together and summarized all the themes below, where you will find a screenshot of each of the ten themes in action and you can decide for yourself if this is something you’re interested in exploring further.

My tip is: Check them out!

Preview: Corporate Site Theme

image

Preview: Team Site Theme

image

Preview: Publishing Site Theme

image 

Preview: Sports Site Theme

image

Preview: Construction Site Theme

image 

Preview: Contoso Site Theme

image 

Preview: Events Site Theme

image

Preview: Owner Approver Reviewer Participant Site Theme

image

Preview: Procurement Site Theme

image

Preview: Startup Site Theme

image 

Summary

Alright, that was the 10 new SharePoint themes available for free here

SharePoint Online – Customization – Part 2

March 11th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net

Introduction

I previously wrote an Introduction to SharePoint Online which was highly appreciated, so now I’m doing a quick follow-up on how you can easily customize the appearance of your SharePoint Online site.

Since we today can’t really do any customizations using .wsp packages or deploying custom code on the standard services, we’ll have to use the SharePoint Designer to do our customizations.

I will show you a quick-intro on how you can get started with customization of your sites in SharePoint Online.

Pre-requisites

If you want to be able to follow along with this article yourself, please make sure that you’ve fulfilled the requirements below:

  • SharePoint Online Site Collection
    • This will work with any OOB installation you’ve got as well though
  • Microsoft Office SharePoint Designer
  • You’ve got some custom Master Page lying around
    • If not, grab the WSS 3.0 Example Master Pages from Microsoft here
  • Single Sign-in application installed
    • You can download the Single Sign-in application from your Microsoft Online Services Admin portal

Preparing for customization with SharePoint Designer

You should install the Single Sign-in application, and log in to your account, before proceeding past this point. The application looks like this, and you should see something like the following once logged in:
 image

Once logged in, you should have the icon down in your system tray, and don’t need to worry about it anymore – you’re always logged in (the blue square-ish icon, compare to the image’s titlebar-icon above):
image

This is what your site basically looks like from scratch

Out of the box, our default.master looks like this (I’ve made it squeeze into the frame here):
image

SharePoint Designer – here we come

Now that we’re always logged in, and don’t need to worry about providing credentials all the time, let’s proceed with SharePoint Designer.

Open SharePoint Designer, open your Site to edit, get a move on
  • In an ordinary fashion, open SharePoint Designer and open your site:
    • File – Open Site
    • URL of the Site Collection
    • Let’s roll!

This is what it might look like when you open your SPOL site using SPD

Customize the Site Collection

There’s a few options you’ve got when you want to customize the Site Collection from here.
One option is of course to create new and/or modify existing Master Pages in the Site Collection – which is our task for the day. We are going to modify the default.master so it will match our corporate branding, and in order to do that you can follow along with the following steps.

Note: I’m not digging down into the css/master pages right now, if you want more information on how that works – I urge you to check out www.heathersolomon.com/blog for great resources on branding.

Note 2: I’m using the WSS 3.0 Example Master pages for this.

Step 1 – Import all the required resources

  • File – Import
  • Choose the "File" option
  • Click "Add Folder"
    • Select the folder where your _catalogs files reside
    • Repeat this for all resources you need (styles, images, what-not)
  • Repeat the aforementioned step for every new set of resources you want to import.

As a result, you may now have a bunch of .master files, a bunch of new images and a set of styles hooked up with your Site Collection. No beef there:

Example of importing folders into your Site Collection using SharePoint Designer

Step 2 – Validate the resources

Make sure the new files are in the right place in your Site Collection structure

  • _catalogs
    • masterpage
      • awesome1.master
      • awesome2.master
      • awesome3.master
  • images
    • CompanyNamedFolder
      • zimmergrenHeader.png
      • zimmergrenLikesSharePointOnline.png
    • imageFile1.gif
    • imageFile2.png
  • styles
    • CorporateNamedFolder
      • zimmerCustomCSS.css
      • tozitAwesomeCSS.css
    • styleFile1.css
    • styleFile2.css

Step 3 – Modify the default.master and apply our corporate branding

To make this quick’n'easy, we’re going to use the completely ready master pages from the example package I mentioned earlier.

  • Open any of the new .master pages
    • Copy the entire content
  • Open the default.master page
    • Replace the entire content with the one in your clipboard
  • Save
  • Smile and cross your fingers (not really needed, but it’s more fun this way..)

The default.master has now been customized, and the all-too-familiar information icon appears right next to the file, telling us that it’s customized from the definition. From there, we can of course always right click and choose "Reset to Site Definition" in order to revert any and all changes we’ve done.
image

Step 3 – Alternative approach (Recommended if you don’t want to mess with the original)

If you don’t want to replace the contents of the default.master, you can of course simply cut to the chase by clicking one of your other .master pages and choose "Set as Default Master Page" in order for it to be set as the default master without replacing the actual default.master:
image

Final results

If all goes well, we should now see our "branded" master page with some new images, some custom css and a bit of a new look to it, like this:
image

Summary

So, in this article I showed you how you easily can alter the look and feel of your SharePoint Online site by using the Example master Pages provided from Microsoft.

I’ve been getting a lot of questions regarding weather or not it is possible to actually DO ANYTHING with your SharePoint Online installation.
The answer is: Yes. But it’s quite limited. We will discuss the limitations and more fine-grained possibilities with the Standard vs. Dedicated options another time.

SharePoint Ramp Up – Part 2

March 1st, 2009 by Tobias Zimmergren

For those of you who have tried the online-training program called MyRampUp, and went through all the exercises for SharePoint developers part 1 – Part 2 is here.

Check this out: http://msdn.microsoft.com/en-us/rampup/dd320759.aspx

I wrote a bit about the Ramp Up program in this previous article where I outlined the Part 1 of the program.

Part 2 adds the following levels:

  1. Level 1: Page Navigation
  2. Level 2: Page Branding
  3. Level 3: Web Services
  4. Level 4: Custom Content Types
  5. Level 5: User Management

Now I’m off to shoot some fellow SharePoint MVP’s at the summit paintball.

Cheers.

Microsoft Online Services Release Notes

February 16th, 2009 by Tobias Zimmergren

A new set of Release Notes for Microsoft Online Services were released yesterday. For those of you interested in the Microsoft Online Services, you should check it out.

Below are some good links touching the Microsoft Online Services.

Microsoft Online Release Notes
Download here

Microsoft Online Services Single Sign-on application
Download here

Microsoft SharePoint Online Standard Developer Guide
Download here

Microsoft SharePoint Online Standard Service Description (Dec08)
Download here

/Z out.