Thursday, March 26, 2009

SharePoint Best Practices For Begginers

SPSiteDataQuery Class
Imagine a scenario in which you want to run a single query against every list in the current site collection that has been created from the Announcements list type and return all list items that were created today. The following code sample demonstrates how to do this by creating an SPSiteDataQuery object, initializing it with the necessary CAML statements, and then passing it to the current SPWeb object’s GetSiteData method.

SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";

string queryText = @" ";


query.Query = queryText;

DataTable table = site.GetSiteData(query);

foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}



Using SPQuery to query specific items in the list

To get back specific results within a list, you can use the SPQuery object. When you use an SPQuery object, you will create CAML statements to select specific data within the target list. To select announcements that have expired, you may want to use a query built with CAML statements, as shown in the following example:

SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"
";

SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}
You must specify the fields you want returned in the query by using the ViewFields property. Also note that you must specify the fields in terms of the field Name, and not DisplayName. If you attempt to access fields without specifying them in ViewFields, you will experience an exception of type ArgumentException

Enumerating thought the Fields excluding Hidden and read only fields
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
foreach (SPListItem item in list.Items) {
foreach (SPField field in list.Fields) {
if (!field.Hidden && !field.ReadOnlyField)
Console.WriteLine("{0} = {1}", field.Title, item[field.Id]);
}
}
Checking if the List Exists and Adding a new list if it does not Exists

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}

Check if list is of the type Document Library or Not

public bool CkechIfListisDocLib(SPList list) {
if (list is SPDocumentLibrary)
return true;
else
return false;
}

Running a Code with Elevated Permissions

Use this in ur code. if u want to run a portion of the code with elevated permissions


SPSecurity.RunWithElevatedPrivileges(delegate()
{
// do something
});

Download a file from Document Library and Save it locally

private static void DownloadAFile()
{
SPSite site = new SPSite("http://wwdevserver:3000/"); //site url

SPWeb web = site.OpenWeb(@"/Admin"); //web url

SPList list = web.Lists["PDF Form Templates"]; //list name



File.WriteAllBytes(@"c:\m.pdf", list.Items[0].File.OpenBinary()); //downloading first items file

}

SPWebConfigModification Class - Editing Sharepoint Web.Config

I have seen some of the code where in if a "SafeControl" entry is need to be done in the web.config, through code, then we use
"XMLDocument" class to load the web.config and make changes . there is trouble in doing so as you need to manually get the path of the web.config and all.

But Sharepoint object model provides a class called "SPWebConfigModification" which can be used to play around with the web.config of the site.

Sample Code where in --Safe Control Entry is Made for the Webparts in the feature activation



public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = (SPSite)properties.Feature.Parent;

if (site != null)
{
SPWebApplication webApp = site.WebApplication;

SPWebConfigModification ModDesc = new SPWebConfigModification();
ModDesc.Path = "configuration/SharePoint/SafeControls";
ModDesc.Name = "SafeControl[@Assembly='Description'][@Namespace='Description'][@TypeName='*'][@Safe='True'] [@AllowRemoteDesigner='True']";
ModDesc.Sequence = 0;
ModDesc.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
ModDesc.Value = "";


webApp.WebConfigModifications.Add(ModDesc);

webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
webApp.Update();

}

Introduction To K2 WorkFlow:

K2.com : K2 blackpoint Released
K2 have release their new product called blackpoint. This is a very well integrated solution with Microsoft SharePoint products and technologies (WSS 3 and MOSS).
Why might you look at K2 blackpoint over an above just the Workflow Foundation that you get with SharePoint?

• Fast creation and deployment of workflow processes using either the K2 Web Designer (built with Silverlight!) or K2 Studio. (No Code!)
• Amazing integration with SharePoint 2007 with numerous wizard based functions
• Rich options for forms (InfoPath, Form Server, ASP.Net, SharePoint)
• Great user experience for the business users (One task list for all tasks with rich functionality such as out of office, redirect, delegate, bulk actions)
• Data driven workflow (Use SmartObjects to wrap SharePoint data which can help drive your workflow)
• Integrated security model
• Delegated management of processes (Process portals for process managers to manage their processes)
• Reporting
• Enterprise grade server for process execution
Amazing price point! (In my opinion, the time saved building, deploying and managing processes will provide very fast ROI on the cost of K2)
K2.com : K2 blackpoint Overview

Enabling the K2 Features from Central Administration
After installing BlackPearl when I clicked any of the 'Feature' links from the K2 Administration tab in Central Admin, I was getting the following error;
"The site http://:/ could not be found in the Web application SPWebApplication Name=SharePoint - Parent=SPWebService."
I noticed that the reported site was my SSP Administration web application. Because I had this on a different port to MOSS, the only Site Collection is ssp/admin and there is no 'root' site collection. I tried deleting the SSP and web application, and the feature links then started working. I created a new SSP on a different port and it stopped working again. Then I tried adding a blank site collection at the root of the SSP Admin web application and they started working again.
I assume this means that there is an error when the BlackPearl link enumerates the site collections in all of the web applications and it expects there to be a site collection at the root of the web app.
So a work around is to create a blank site collection in the root of your SSP web application. (Or put your SSP in the same web application as your other sites)