Posts Tagged ‘SPS’
SP 2010: Web Application settings (web.config) modifications in SharePoint 2010 via code
September 7th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
I’ve been getting some questions lately about modifications to web.config files and SharePoint 2010 – is it possible to automate so that the administrator don’t have to manually edit those files on each WFE?
Yes, that’s the easy answer. This was possible in SharePoint 2007 as well.
In this article I’ll quickly demonstrate how you (using a Web Application feature) can make modifications to web.config automatically.
Please note that this is just a getting-started point which you’ll have to work deeper into to tweak it to your likings for updates and removals from the web.config file.
Automatic web.config changes using a SharePoint 2010 feature
Basically, if you want to get some type of change into the web.config, it oftentimes has to do with adding custom settings or values that you’ll later reference in your applications.
In this scenario, we’ll add the following key into web.config using a Feature Receiver, so we don’t have to do it manually after/before deploying our solutions:
<add key= "isAwesome " value= "1 " />
So, in order to achieve this programmatically without actually editing the web.config by hand – you could utilize the class called SPWebConfigModification something like this:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var value = 1; // We want to set the key isAwesome to the value "1"
var webApp = properties.Feature.Parent as SPWebApplication ;
var mySetting = new SPWebConfigModification
{
Path = "configuration/appSettings",
Name = string.Format("add [@key='isAwesome'] [@value='{0}']", value),
Sequence = 0,
Owner = "Zimmergren.SP2010.WebConfigModifications.Awesomeness",
Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode,
Value = string.Format("<add key='isAwesome' value='{0}' />", value)
};
webApp.WebConfigModifications.Add(mySetting);
webApp.Update();
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
By executing this cute snippet of code you will actually add the setting called isAwesome to the web.config of your web application. (This will be persisted to all the WFE’s of course).
Please note: You will need to tweak your code quite a lot to make the sweet SPWebConfigModification class behave the way you want on activation/deactivation of the feature. This should at least give you a starting point
Summary
In this short introductory article about web.config modifications I’ve talked a bit about how you can automate the process of altering your web.config files without actually opening them on the file system.
Nothing fancy, but a good starting point for those of you who requested some info on the topic.
Enjoy!
- Posted in Technical
- 12 Comments
- Tags: SharePoint, SharePoint 2010, SPF, SPS, Web Config Modification
SP 2010: Find error messages with a Correlation ID token in SharePoint 2010
September 3rd, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In SharePoint 2010, you’ve got some new capabilities for error reporting and logs. One of the most noted features for me as a developer is that whenever you bump into an error message – you’ll be presented with a correlation ID token.
In this article I will try to explain how you can fetch that token from SharePoint, and also provide a small snippet of code to be able to build your own “Log Searcher Web Part” for your administrators.
Correlation ID, what’s that?
In SharePoint 2010, you get a Correlation ID (which is a GUID) attached to your logs/error messages when something happens. This ID can then be used to lookup that specific error from the logs.
This Correlation ID is used per request-session in SharePoint 2010, and if you are in the process of requesting some information from SharePoint and bump into some problems along the way – your Correlation ID will be the best starting point for searching for what went wrong along that request!
You might get an error message like this in SharePoint 2010 (don’t worry, if you haven’t seen one like this one yet – just hang in there, sooner or later you will..
)
Search for the log messages based on the Correlation ID token
So if you’ve gotten such an error message and want to find out more information about the actual error and don’t have the time to go around poking in the logs and searching – there’s a few methods you can do this rather easily, as described below.
Using PowerShell to lookup a log message based on Correlation ID token
One of the quick-n-awesome ways to do this is to simply hook up a PowerShell console (SharePoint 2010 Management Shell) and then just write the following command (replace the <GUID> with the Correlation Id):
get-splogevent | ?{$_Correlation -eq "<GUID>" }
This will give you the details about your specific error like this in the console:
You might want to be more precise and get more specific details out of your query, then you can try something like this:
get-splogevent | ?{$_.Correlation -eq "<GUID>"} | select Area, Category, Level, EventID, Message | Format-List
This will give you the details about your specific error like this with some juicy details:
Finally if you would want these messages to be put into a text or log file instead, you could just add the classic “> C:Awesome.log” after the command like this:
get-splogevent | ?{$_.Correlation -eq "<GUID>"} | select Area, Category, Level, EventID, Message | Format-List > C:Awesome.log
On MSDN they have an overvoew of using SP-GetLogEvent which I would recommend!
Using SQL queries to find log message based on Correlation ID token
You can utilize the SQL logs database to fetch the specific error message based on Correlation id as well. In your logging DB (usually called WSS_Logging, but can be called something else if you’ve changed it) there is a view called ULSTraceLog which you can query with a simple SQL query and fetch the results.
I’ve created a query to fetch the items from the logging database like this:
select [RowCreatedTime], [ProcessName], [Area],
[Category], EventID, [Message]
from [WSS_UsageApplication].[dbo].[ULSTraceLog]
where CorrelationId=< pre>'B4BBAC41-27C7-4B3A-AE33-4192B6C1E2C5'
This will render your results in the SQL Query window like this:
This can of course be implemented in a Web Part for your convenience as well (I’ve created a bunch of diag. and logging web parts that I’ve got deployed to Central Admin) that could look like this (this way you don’t need physical access to the ULS logs all the time, but can do a quick lookup from the web part):
Get the current Correlation ID by using code
I got this piece of code from my good friend Wictor’s blog post. Thanks Wictor – this made my Logging-project more satisfying!
With the following code you can fetch the current Correlation Id of a request.
Create a method (in my case called GetCurrentCorrelationToken()) to wrap up the functionality of returning the current token like this:
public class CorrelationId
{
[DllImport ("advapi32.dll")]
public static extern uint EventActivityIdControl(uint controlCode,ref Guid activityId);
public const uint EVENT_ACTIVITY_CTRL_GET_ID = 1;
public static Guid GetCurrentCorrelationToken()
{
Guid g = Guid .Empty;
EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g);
return g;
}
}
Then from wherever in your code you can simply call it by using this approach:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = CorrelationId .GetCurrentCorrelationToken().ToString();
}
(Normally you might want this in a try/catch statement or something like that)
Summary
This article should give you (administrator and developer) an insight in how you easily can track the specific errors your users encounter in their/your application(s). If a user gets an error message in SharePoint 2010, they’ll also see the Correlation ID.
If you can train your users to write down that Correlation ID along with a few simple steps on how the error might have been occurring, you’re going to have a much easier way to find the details about that specific error than ever before.
Enjoy!
- Posted in Technical
- 9 Comments
- Tags: Correlation ID, Debugging, Logging, SharePoint, SharePoint 2010, SPF, SPS, ULS
SP 2010: Developing with the Word Automation Services in SharePoint Server 2010
August 30th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In SharePoint 2010, there is a new Service Application called Word Automation Services. This Service Application is used to convert documents from Word to different formats.
Word Automation Services can open about the same formats as Windows Word 2010 can:
-
Filetypes it can open include:
.docx, .docm, .dotx, .dotm, .doc, .dot, .rtf, .mht, .mhtml, .xml (Word xml) -
Filetypes it can save as include:
.docx, .docm, .dotx, .dotm, .doc, .dot, .rtf, .mht, .mhtml, .xml (Word xml), PDF, XPS
In this article you’ll see an example of how you can utilize the Word Automation Services in order to build a custom solution that takes care of converting documents (as listed above) into PDF documents.
Programmatically work with Word Automation Services in SP 2010
Note: You cannot deploy a solution working with the API’s in the Word Automation Services in the Sandbox. Rather you’ll need to target your application as a Farm Solution.
There’s not really a whole lot to it. Just follow along with these few steps and you’ll be fine!
In the API for Word Automation Services you’ll find a few different ways to convert documents including:
In the following example I’ll demonstrate how to use the AddLibrary() method in order to convert the contents of an entire document library into PDF documents! (Yes, that is way awesome)
1. Add the Word Automation Services API reference to your project
The following reference needs to be added to your project:![]()
It can be found here:
<path>14ISAPIMicrosoft.Office.Word.Server.dll
2. Add the proper using-statements
using Microsoft.Office.Word.Server.Service;
using Microsoft.Office.Word.Server.Conversions;
3. Create a job to convert an entire Document Library to PDF’s
First, fetch the WordServiceApplicationProxy object (so we don’t have to hard-code the service app name..). This first line requires the Word Automation Service Application to be added to the default proxy group.
Second, we instantiate a new ConversionJob class and shoots in your WordServiceApplicationProxy as a parameter:
var wordAutomationProxy =
(WordServiceApplicationProxy )
SPServiceContext .Current.GetDefaultProxy(typeof (WordServiceApplicationProxy ));
var conversionJob = new ConversionJob (wordAutomationProxy);
Next we need to specify a UserToken for the job to tell the job under what credentials to run.
We also need to specify a name for the job.
Finally you can add whatever Settings you want for your job, I’ve chosen that I want my files to be output as PDF’s.
conversionJob.UserToken = SPContext .Current.Web.CurrentUser.UserToken;
conversionJob.Name = "Zimmergren.SP2010.WordAutomationDemo Conversion Job" ;
conversionJob.Settings.OutputFormat = SaveFormat .PDF;
Next we will simply specify a library where the original .doc or .docx files reside and point out the destination library like this, and start the job by adding it to the timer job queue:
conversionJob.AddLibrary(origLib, destinationLib);
conversionJob.Start();
This is the sample code in one snippet
protected void btnConvert_Click(object sender, EventArgs e)
{
try
{
SPList origLib = SPContext .Current.Web.Lists[ddlLibraries.SelectedValue];
SPList destinationLib = SPContext .Current.Web.Lists["PDFLibrary" ];
var wordAutomationProxy =
(WordServiceApplicationProxy )
SPServiceContext .Current.GetDefaultProxy(typeof (WordServiceApplicationProxy ));
var conversionJob = new ConversionJob (wordAutomationProxy);
conversionJob.UserToken = SPContext .Current.Web.CurrentUser.UserToken;
conversionJob.Name = "Zimmergren.SP2010.WordAutomationDemo Conversion Job" ;
conversionJob.Settings.OutputFormat = SaveFormat .PDF;
conversionJob.AddLibrary(origLib, destinationLib);
conversionJob.Start();
Label1.Text = "Conversion job started!" ;
Label1.Visible = true ;
}
catch (Exception ex)
{
Label1.Visible = true ;
Label1.Text = "Error:<br/>" ;
Label1.Text += ex.Message;
}
}
So what’s the results?
When you’ve created a new ConversionJob, it’ll be added to the Timer Job schedule to be run by SharePoint. When the job has been run, it can look like this:
Original Document Library, filled with some Word documents:![]()
These files will then be converted to PDF’s and put into my PDFLibrary like this:![]()
Summary
To get started with the Word Automation Services, you don’t really need to do a lot of coding. Just specify the references, hook up a reference to your service app and create a new ConversionJob and you’re up and running.
This article demonstrated how to convert an entire library of documents to PDF’s with a single click.
Awesome. Enjoy!
- Posted in Technical
- 14 Comments
- Tags: SharePoint, SharePoint 2010, SPS, Word Automation Services
SP 2010: Introduction to programmatically working with Taxonomies in SharePoint Server 2010
August 28th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
One of the coolest new set of functionality for SharePoint 2010 is the Taxonomies (Term Store, Term Sets, Terms) that you can easily create using the amazing Managed Metadata Manager service application.
In this article I’ll talk briefly about how you can utilize the SharePoint API to programmatically work with Taxonomies and create terms and fetch the terms in your term store. This should give you some nice ideas on how to get going!
A simple example of a taxonomy
Let’s say we’ve got a taxonomy worked out and implemented in SharePoint. It could look something like this (I’m using some made up samples below):
So, if you’ve got a taxonomy configured in your Managed Metadata Service Application, you can work with those programmatically – and that’s what this little tip is about.
Work with the taxonomy API’s programmatically in SP 2010
In this article I will talk about some of the basics to get started with taxonomies in SharePoint 2010 programmatically. First, of course, we need to create a new project and add the references for the Taxonomy API.
Preparing for development
First of all, create a new project (In my case, I chose to create a Visual Web Part project).
You’ll need to add the following reference to your project:
You’ll find this reference here:
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.Taxonomy.dll
Namespaces
So, the first thing we would like to do is to learn how we can read the taxonomies we’ve got in our store. To do this, we utilize Microsoft.SharePoint.Taxonomy.
There’s a few good-to-know classes in this namespace that we’re going to work with:
- Microsoft.SharePoint.Taxonomy.TaxonomySession
- Microsoft.SharePoint.Taxonomy.TermStore
- Microsoft.SharePoint.Taxonomy.Group
- Microsoft.SharePoint.Taxonomy.TermSet
- Microsoft.SharePoint.Taxonomy.Term
The above classes are stated in their hierarchically correct order, meaning means that you start out with the TaxonomySession which contains the TermStore, which contains the Groups.. and so on.
Reading the Metadata store (Managed Metadata Service) programmatically
Sample code from my Visual Web Part’s user control (I have a control called tvMetadataTree in the user control):
public partial class TaxonomyWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SPSite thisSite = SPContext .Current.Site;
TaxonomySession session = new TaxonomySession (thisSite);
TreeNode treeNode = new TreeNode ();
treeNode.Text = "Metadata Awesomeness" ;
tvMetadataTree.Nodes.Add(treeNode);
foreach (TermStore termStore in session.TermStores)
{
var tsNode = new TreeNode (termStore.Name, null , null , "" , null );
treeNode.ChildNodes.Add(tsNode);
//treeNode = tsNode;
foreach (Group group in termStore.Groups)
{
var node = new TreeNode (group.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
//treeNode = node;
foreach (TermSet termSet in group.TermSets)
{
node = new TreeNode (termSet.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;
foreach (Term term in termSet.Terms)
{
AddTermSet(term, treeNode);
}
}
}
}
}
void AddTermSet(Term term, TreeNode treeNode)
{
var node = new TreeNode (term.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;
foreach (Term t in term.Terms)
{
AddTermSet(t, treeNode);
}
}
}
The end result will be a simple TreeView control filled with the Metadata structure from the store, looking something like this:
That’s about what you would need to get started with this!
Summary
Alright, so I wrote this small article up due to some students asked me for some taxonomy sample code a while back. I hope everyone enjoys this tip on how to programmatically work with the Taxonomies in SharePoint Server 2010!
As always, enjoy!
- Posted in Technical
- 1 Comment
- Tags: How-To, SharePoint, SharePoint 2010, SPS, Taxonomy
SP 2010: SharePoint Server 2010 – Creating a custom Document ID provider
April 13th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In this article I will talk about how you can create your custom Document ID provider for your SharePoint Server 2010 installation. Sometimes I’ve been getting the question weather or not it’s possible to change the behavior or change the way the Document ID’s are generated, and some people have a tendency to say no to that question, just because there’s no interface or out of the box functionality to do so.
I’ll give you a quick walkthrough of how you can extend your Site Collection by adding a custom Document ID provider, that will automatically generate custom ID’s based on your own algorithms entirely!
Recommended reading about Document ID’s before proceeding:
http://msdn.microsoft.com/en-us/library/ee559302(office.14).aspx
Document ID overview
This section will give you a very brief conceptual overview of Document ID’s in SharePoint Server 2010.
What is Document ID’s?
Document ID’s in SharePoint Server 2010 provide you with the ability to tag documents with a unique identification number. Something a lot of my clients have done manually or by implementing custom solutions to take care of in SharePoint 2007. With this new feature, you get all the required functionality to tag documents with unique identification numbers based on a specific pre-set formula with a custom prefix.
See this sample screenshot for an example:
Where do I enable Document ID’s for my Site Collection?
In order to enable Document ID’s in your Site Collection, you’ll need to activate the Site Collection Feature called Document ID Service.
See this screenshot for an example:
How do I change the way my Document ID’s are generated?
If you want to alter the way the Document ID’s are generated for your documents in your Site Collection, you can do that by navigating to:
Site Actions – Site Settings – Document ID Settings, like so:
From this new settings page, you’ll get the possibility to tell SharePoint how it should generate your unique ID’s. You can specify a prefix for all the generated ID’s:
I want to take it one step further!
If you’re not quite satisfied with the way SharePoint 2010 generates your Document ID’s for you, then you should most definitely follow along with the rest of this article as I will guide you through the steps to create your very own Document ID provider to generate exactly the kind of ID’s you want – based on your very own code/algorithms!
Bring it on!
Learning about a SharePoint 2010 Custom Document ID provider
This section will give you an overview of what you will need in order to create a custom Document ID provider for SharePoint Server 2010!
Note: As of this writing MSDN isn’t fully updated on these new SharePoint Server namespaces. Some details may or may not change when SharePoint Server 2010 is released into the wild (RTM)
Microsoft.Office.DocumentManagement
The namespace Microsoft.Office.DocumentManagement contains a class called DocumentIdProvider, which will be the base for our upcoming project!
Microsoft.Office.DocumentManagement.DocumentIdProvider
This is the class we will derive from when creating our custom provider. It contains three (3) abstract methods and one (1) abstract method that we need to implement:
- GenerateDocumentId (Method)
- GetDocumentUrlsById (Method)
- GetSampleDocumentIdText (Method)
- DoCustomSearchBeforeDefraultSearch (Property)
A description of each of these methods and the property will be made inline in my code in the samples!
Creating a SharePoint Server 2010 Custom Document ID provider
Let’s code this little piece of functionality, shall we. The final project (very basic) will look something like this:
So, let’s get coding.
1. Create a class and derive from DocumentIdProvider
public class CustomDocumentIdProvider :
Microsoft.Office.DocumentManagement.DocumentIdProvider
{
// Method to generate the actual document ID. Awesomeness lives here!
public override string GenerateDocumentId(SPListItem listItem)
{
// In this method we will tell SharePoint how it should generate
// the unique ID we want.
// In my case, I’ve just created a dummy-generator.
// Normally you would perhaps want to fetch this from another system or
// generate it properly instead of like this..// Points to a method I’ve created that generates foo-ID’s
return FooSampleIDGenerator.GetFooUniqueID();
}public override bool DoCustomSearchBeforeDefaultSearch
{
// If set to true: It will call the GetDocumentUrlsById method before search
// If set to false: It will use SharePoint Search before custom methods
get { return false; }
}public override string[] GetDocumentUrlsById(SPSite site, string documentId)
{
// Returns an array of URLs pointing to
// documents with a specified DocumentId
// An empty string array// This is where you will implement your logic to find
// documents based on a documentId if you don’t want to use
// the search-approach.
return new string[] { };
}public override string GetSampleDocumentIdText(SPSite site)
{
// Returns the default Document ID value that will be initially
// displayed in the Document ID search web part as a help when searching
// for documents based on ID’s.
// This should correspond with the way you’ve designed your ID pattern
return "AWESOME-12345-67890-SharePointRules";
}
}
2. Create a Feature Receiver to hook up your custom provider with your Site Collection
public class ProvisionCustomDocIdProviderEventReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
DocumentId.SetProvider(properties.Feature.Parent as SPSite,
new CustomDocumentIdProvider());
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
DocumentId.SetDefaultProvider(properties.Feature.Parent as SPSite);
}
}
Actually, you’re all done with the code for now.
3. Go to Document ID Settings page and see this message appear
This basically means that your custom provider has been successfully enabled (as per our Feature Receiver).
4. See that the Document ID’s on your documents now is using your custom provider
(Please allow for some time to pass so the Timer Jobs can do their magic, or manually go into Central Admin and run the timer jobs instantaneously)
Behold, awesome custom Document ID provider in action:
Summary and Download
What did we just do?
What we just did was to create a custom Document ID provider that generates our very own custom Document ID’s based on whatever algorithm or pattern we want. There’s no need to follow the built-in format for your generated IDs – which some people have presented in their seminars and blogs. So there you go, step by step!
This could be especially awesome if you’ve got an external system generating Document ID’s already, and you want SharePoint to use those ID’s alongside whatever other system is running. Use your own imagination as to what can be done. The code is in your hands, Obi Wan Coder!
Download project
Enjoy, and please don’t be afraid to leave comments!
- Posted in Technical
- 10 Comments
- Tags: Document ID, How-To, SharePoint, SharePoint 2010, SPS
SP 2010: Certification exam details for SharePoint 2010 published
March 28th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
Microsoft has published the two developer-oriented certifications for SharePoint 2010 on Microsoft Learning.
Personally, I think there is a huge improvement now as we’re not only getting the MCTS-credit but can now also become an MCPD (Microsoft Certified Professional Developer) on the SharePoint platform. Something I’ve been waiting for a long time
SharePoint 2010 exams
For us developers/solution architects there are two certifications of interest (of course you should do the IT-pro tracks as well, but let’s start here with the developer ones):
- 70-573: TS: Microsoft SharePoint 2010, Application Development
- 70-576: PRO: Designing and Developing Microsoft SharePoint 2010 Applications
SharePoint 2007 Exams
Way back in 2007 I wrote about passing all 4 certifications for SharePoint 2007 (link here). For SharePoint 2007 there is four certifications for the 2007 product-line:
- 70-541 – TS: Microsoft Windows SharePoint Services 3.0 – Application Development
- 70-542 – TS: Microsoft Office SharePoint Server 2007 – Application Development
- 70-630 – TS: Microsoft Office SharePoint Server 2007, Configuring
- 70-631 – TS: Microsoft Windows SharePoint Services 3.0, Configuring
Summary
So, keep an eye out on those two new certifications and be well prepared when they arrive – should be a fun ride
- Posted in Technical
- 3 Comments
- Tags: Certification, SharePoint, SharePoint 2010, SPF, SPS
SP 2010: Dynamically displaying messages to your users with the Notification and Status bar areas in SharePoint 2010
March 17th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
With the new version of SharePoint comes a full set of new and awesome features that you’ll have to indulge and learn. One of the small things that makes my day much more fun is to display messages to your users in the Status- and Notification areas.
Example of a message in the Status bar area:
Example of a message in the Notification area:
How do we make this magic happen?
In order to display these messages, you really (really) don’t need a lot of code. I’ll lay out the simple code I used to display the messages you saw in my screenshots.
It’s all JavaScript based, so get ready to dig out those old JS skills you know you’ve got lying around somewhere
Oh wait, you don’t need skills to do this, it’s just that easy!
Show me a Status bar!
JavaScript:
function ShowStatusBarMessage(title, message)
{
var statusId = SP.UI.Status.addStatus(title, message, true);
SP.UI.Status.setStatusPriColor(statusId, ‘yellow’); /* Set a status-color */
}HTML, call the JS method:
<a onclick="ShowStatusBarMessage(‘Title’!',’Awesome message!’)">
Display Status Bar message!
</a>
Show me a Notification popup!
JavaScript:
function ShowNotificationMessage(tooltip, message, sticky)
{
SP.UI.Notify.addNotification(message, sticky, tooltip, null);
}HTML, call the JS method:
<a onclick="ShowNotificationMessage(‘I am cool!’,'This is a cool message’,false)">
Display Notification!
</a>
Summary
Actually, there’s no need for a summary. It’s way too easy.
Enjoy!
- Posted in Technical
- 6 Comments
- Tags: SharePoint, SharePoint 2010, SPF, SPS, UI
SP 2010: LINQ to SharePoint – What CAML lies behind my query?
February 19th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
The two following questions are quite popular in my SharePoint 2010 developer training classes, so I ought to answer them right here.
- "What does LINQ to SharePoint really do?"
- "Can I see the CAML query generated by the LINQ to SharePoint query?"
The answer is simple: Yes, you can see the results of your generated LINQ query by using the Log property of your DataContext object.
What CAML lied behind my LINQ to SharePoint query?
In order to fetch the CAML query that lies behind your LINQ query, all you need is to work with the .Log object of your DataContext.
See this simple example, which simply outputs the CAML query to an XML-file for easy reading:
This will essentially generate the following content in the file C:MyEntitiesDataContextQuery.xml:
As you can see, the LINQ to SharePoint query is automatically turned into a CAML Query.
Summary
Yep, all you need is the .Log property to fetch the CAML query from your LINQ statement. In my sample I’m outputting it to a file called C:MyEntitiesDataContextQuery.xml.
You could of course output it in any other way you want – not just a physical file on the file system. The Log property is of the type TextWriter.
Enjoy!
- Posted in Technical
- No Comments
- Tags: CAML, LINQ, Queries, SharePoint, SharePoint 2010, SPF, SPQuery, SPS
SP 2010: Getting started with LINQ to SharePoint in SharePoint 2010
February 19th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In SharePoint 2010 you now have the ability to use LINQ syntax to fetch items from your lists instead of using the "traditional" approach of CAML queries. (Including SPSiteDataQuery and SPQuery objects)
In this article I will give you a brief introduction to how you can get started using LINQ queries in SharePoint, also known as LINQ to SharePoint.
Basics of LINQ?
As a prerequisite to this article, I’m going to imply that you know what LINQ is and how to write basic LINQ queries in any .NET application already. I’m not going to dive into the details about LINQ or the syntax itself here – please see MSDN for that!
LINQ to SharePoint!
In order to work with LINQ in SharePoint 2010, we need use a tool called SPMetal.exe which resides in the 14bin folder. This tool is used to generate some entity classes which Visual Studio 2010 can use to get IntelliSense, and allows for LINQ-based queries to be performed on your lists.
Noteworthy:
- LINQ to SharePoint queries are translated to proper CAML queries
- CAML queries are in turn later translated to SQL queries
SPMetal.exe
Using the tool called SPMetal, we generate our entity-classes that are needed to perform these object oriented queries toward our SharePoint server.
These are the required steps to get hooked up:
- Launch a cmd-window and navigate to C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14bin
- Run the following command to utilize the SPMetal.exe tool with the following syntax:
- Now navigate to C: (or wherever you chose to output your file) and make sure the file has been generated:
- Open up the file and take a look at the content that SPMetal now have provided us with:
Note that the class name is now MyEntitiesDataContext. It’s based on the name you specify as your code file in the SPMetal.exe command line tool.If you were to use /code:C:Awesome.cs instead, it would generate a class called AwesomeDataContext.
With that done – all we need to do is import it to one of our projects and use it!
Visual Studio 2010 – Let’s create a sample Web Part that utilizes LINQ to SharePoint
In this sample I will create a simple Web Part that will use LINQ to SharePoint syntax to fetch some information from the Announcements list. A basic sample I use in my training classes as well, and should be fairly easy to grasp!
- Create a new project (I’m going to create a new Visual Web Part project)
- Import your DataContext-file by choosing your Project -> Add -> Existing Item:
- Specify your file (mine is called MyEntities.cs):
- Make sure it’s properly placed in your project structure – then we’re good to go:
Alright – that’s easy enough. Thus far we have created an entity file using SPMetal.exe and now we have successfully imported it into our project.
Add proper references
Now in order to use LINQ to SharePoint, you also need to reference the Microsoft.SharePoint.Linq assembly. Point to references, right-click and choose "Add Reference" and select the Microsoft.SharePoint.Linq.dll file:
In your code, reference the assemblies:
Ready to code?
What you should’ve done up until now is this:
- Generate your entities using the SPMetal.exe tool
- Reference the newly created file from your SharePoint project
- Make sure you’re using the proper references for System.Linq and Microsoft.SharePoint.Linq
- Be ready to code
Code!
In my example I will have a Visual Web Part that will use LINQ to SharePoint to fetch all Announcements from my Announcement-list and work with those results. If you want to see the entire project, look at the bottom of this article where you can download it.
IntelliSense!
While you code your queries using LINQ to SharePoint, you will now have access to IntelliSense, which you did not have with CAML queries:
I’m going to leave it at that – very (very) easy to get started with LINQ to SharePoint, and all you really need to know is to start using the SPMetal tool to generate your entity classes and hook’em up with Visual Studio to start coding.
Summary & Download
As you can see, there’s not a lot of things you need to do in order to work with LINQ in your SharePoint applications with your SharePoint-data.
I’ve been pinged plenty of times on how you can get started with this, and there you have it. More in-depth articles to come later – this is just to get your wagon rolling!
To download the sample project, click here: [Download]
Enjoy!
- Posted in Technical
- 36 Comments
- Tags: How-To, LINQ, SharePoint, SharePoint 2010, SPF, SPS
SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model
January 21st, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
Article 3 in the small BCS-series:
1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model
In my previous article in the series, I talked about how easy it is to fetch information using the standard SharePoint server API-approach. In this article I will talk about how you can access data in your BCS data source, by utilizing the Client Object Model.
Client Object Model code to read from the external list
Just like I described in my previous article, you now have the awesome ability to work with data in your External Lists (connected to a data source using BCS) – namely, you can use the standard SharePoint APIs.
Since I’ve shown you how you can do this using the Server Object Model, I thought I could take another spin at it and show you the code for doing basically the same with the Client Object Model.
The underlying data
As with my previous article, I’m still using the same data source as I set up in my first article – the "ProductList" table in my SQL Server database called "Zimmergren_DB"
As seen in the SQL Server Management Studio: ![]()
Let’s fetch the data using a Windows Forms application that utilizes the Client Object Model!
I’ve designed a Windows Forms application to utilize the .NET Client Object model (in contrary to using the Silverlight client object model or JavaScript client object model).
When you click the fancy button called "Get External Data", it will use the Client Object Model to fetch the records from the external list (from the SQL server) and display them in a DataGridView. Nothing fancy.
The code!
With no further delays or chit-chat, here’s the simple code!
// Define the Client Context (as defined in your textbox)
SP.ClientContext context = new SP.ClientContext(tbSite.Text);
SP.Web site = context.Web;var ProductList = site.Lists.GetByTitle(tbList.Text);
SP.CamlQuery camlQueryAwesomeness = new SP.CamlQuery();
IQueryable<SP.ListItem> productItems =
ProductList.GetItems(camlQueryAwesomeness);IEnumerable<SP.ListItem> externalList =
context.LoadQuery(productItems);// This is where we actually execute the request against the server!
context.ExecuteQuery();// Retrieve the products from the product list using some fancy LINQ
var productListData = from product in externalList
select new
{
// We’re never pointing to the field at the 0-index
// because it’s used by the BDC Identity itself. Hence our elements start at 1.
ProductID = product.FieldValues.ElementAt(1).Value.ToString(),
ProductName = product.FieldValues.ElementAt(2).Value.ToString(),
ProductDescription = product.FieldValues.ElementAt(3).Value.ToString()
};// Simply clear the rows and columns of the GridView
gvProducts.Rows.Clear();
gvProducts.Columns.Clear();// Add the columns we need (ProductID, Name, Description)
gvProducts.Columns.Add("ProductID", "ProductID");
gvProducts.Columns.Add("Name", "Product Name");
gvProducts.Columns.Add("Description", "Product Description");
foreach (var product in productListData)
{
// For each product in the list, add a new row to the GridView
gvProducts.Rows.Add(
product.ProductID,
product.ProductName,
product.ProductDescription
);
}
References and recommended reading
- Getting Started with the Client Object Model in SharePoint 2010
- Getting Started with Business Connectivity Services in SharePoint 2010
Summary & Download
At this point, I’ve showed you three short articles in which I describe how you can set up a Business Connectivity Services data source – then utilize the Server OM or Client OM to fetch information from that external data storage.
Worth to note is that this is still a Beta product, which of course means that it may differ in functionality and performance in comparison with the final (RTM) version of SharePoint 2010.
Download the complete Visual Studio 2010 project here: [ Zimmergren.SP2010.ClientOM.BCS.zip ]
- Posted in Technical
- 6 Comments
- Tags: BCS, Client Object Model, SharePoint, SharePoint 2010, SPF, SPS

