Sunday, November 16, 2008

Programatically Reading a list and binding to SPGridView (Code)

This post would depict the simple usage of SPGridView and reading from a list and binding it to the SPGridView programatically.


SPGridView oSPGridView = new SPGridView();
string sTaskListName = "News"; // News List in this example

SPWeb site = SPControl.GetContextWeb(Context);
SPList spList = site.Lists[sTaskListName];

SPDataSource mySPDS = new SPDataSource();
mySPDS.List = spList;

oSPGridView.DataSource = mySPDS;
oSPGridView.DataBind();

Get SharePoint Site Collection (Code)

private static Dictionary GetSites()
{
Dictionary sites = new Dictionary(32);



WSSModule.WebAppOp(
delegate(SPWebApplication webapp)
{
foreach (SPSite site in webapp.Sites)
{
try
{

using (SPWeb web = site.RootWeb)
{
if (web.DoesUserHavePermissions(SPBasePermissions.ViewPages))
sites.Add(web.ServerRelativeUrl, web.Title);
}

} catch(SPException)
{

}
}
}
);


return sites;

}

SharePoint Site (individual) Provisioning (Code)

in my previous blog for SharePoint Site Provisioning (Code), it is only used when you are creating sites for the first time. Now imagine if you have already and site and you want to add another site to the WebApp individually. You might want to consider the below.


public static string CreateClientSite(SPWebApplication app, string path, int siteId, string title, string owner)
{
string url;

if (string.IsNullOrEmpty(owner) owner == "{current}")
{
IIdentity identity = System.Threading.Thread.CurrentPrincipal.Identity;
WindowsIdentity winIdentity = identity as WindowsIdentity;
owner = winIdentity != null ? winIdentity.Name : clientSiteOwner;
}

using (SPSite site = app.Sites.Add(string.Format(path, siteId),
title, string.Empty, 1033, null, owner,
"Application Admins",
"<EmailID>"))
{
url = SetWebSettings(site, siteId);
}

return url;
}

private static string SetWebSettings(SPSite site, int siteId)
{
string url;
using (SPWeb web = site.RootWeb)
{
web.Properties<:Property>] = <VALUE>;
web.Properties.Update();
web.ApplyWebTemplate(<TemplateId>);

url = web.ServerRelativeUrl;
}
return url;
}

SharePoint Site Provisioning (Code)

// FIRT TIME COMPLETE SITE PROVISIONING. YOU MIGHT NOT RUN THIS EVERY TIME
try
{
// JOB STARTING

SPWebApplication app = SPWebApplication.Lookup(new Uri(ConfigurationCollection.Instance.ApplicationPath));

List allowPrefixes = new List();
foreach (Configuration usersGroup in ConfigurationCollection.Instance.Configurations)
{
allowPrefixes.Add(usersGroup.SitesLocation);
}

List siteNames = new List();
WebApp.ProcessSites(true, app, delegate(SPSite site)
{
using (SPWeb root = site.RootWeb)
{
foreach (string prefix in allowPrefixes)
{
if (root.ServerRelativeUrl.TrimStart('/').StartsWith(prefix))
{
siteNames.Add(root.ServerRelativeUrl.TrimStart('/'));
root.Properties[WebApp.propPKIDiSDirty] = "true";
root.Properties.Update();
return;
}
}
}
});



foreach (Configuration configuration in ConfigurationCollection.Instance.Configurations)
{
Configuration configuration1 = configuration;
ProvisioningModule.ProcessConfig(configuration,
delegate(Dictionary userInfo)
{
string url = ProvisioningModule.GetEntityRelativeUrl(userInfo);
if (!siteNames.Contains(url))
{
using (SPSite site =
CreateSite(app, url, Formatter.GetFormatString(Convert.ToString(userInfo[ProvisioningModule.fieldEntityFormatField]), userInfo),
configuration1, userInfo))
using (SPWeb root = site.RootWeb)
{
root.Properties[WebApp.propPKID] =
userInfo[ProvisioningModule.fieldPKID].ToString
();
root.Properties.Update();
}
Log.Trace(Level.Info, "Created site{0}", url);
Console.WriteLine("Created site {0}", url);
}
else
{
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite site = new SPSite(WebApp.ApplicationPath + url))
using (SPWeb web = site.RootWeb)
{
web.Properties[WebApp.propPKIDiSDirty] = "false";
web.Properties.Update();
}
});
// UPDATED SITE

}
});
}

if (ConfigurationCollection.Instance.PerformArchival)
{
WebApp.ProcessSites(true, app,
delegate(SPSite site)
{
using (SPWeb root = site.RootWeb)
{
if (null != root.Properties[WebApp.propPKIDiSDirty] && root.Properties[WebApp.propPKIDiSDirty].Contains("true"))
{
if (!string.IsNullOrEmpty(ConfigurationCollection.Instance.ArchiveLocation))
ReloacateSite(app.Sites, site,
ConfigurationCollection.Instance.ApplicationPath + ConfigurationCollection.Instance.ArchiveLocation +
site.ServerRelativeUrl);
else
StripAccess(root);
}
}
}
);
}
// JOB FINISHING
}
catch (Exception e)
{
// JOB ABORTED
}

Creating SP Site Feature

This post would make one understand in simple 10 steps how to create and deploy a SharePoint Site Feature (in this case a page).

This is simple but very useful in case of you already have an existing portal and want to deploy a new page / item (could be anything) when there is no provision to modify ONET.xml file.

Step 1 # Create a folder in the web project (you can create any where... using Visual Studio is not a mandate here) with the name of the Site Feature you want to deploy to the SP Site / Web. NewFeaturePage in this example. It is preferable to have no space in the Feature name but thats not mandatory. Best practices suggests to have 'u20' (html encoded) to replace spaces in the feature name.
Step 2 # Add a (new) XML File to the folder and name it as Elements.xml
Step 3 # Create a new .aspx page to the folder and name it as NewFeaturePage.aspx (in this example)
Step 4 # Add a (new) XML File to the folder and name it as Feature.xml
Step 5 # From VS Designer, TOOLS > CREATE GUID create a new GUID. Use this new GUID in the Feature.xml as shown below for Feature ID.

the contents of Elements.xml can be as simple as below...
------------------------------------------------------------------------
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="NewFeaturePage" Path="" Url="" >
<File Url="NewFeaturePage.aspx" Type="Ghostable" IgnoreIfAlreadyExists="FALSE" />
</Module>
</Elements>
------------------------------------------------------------------------
the contents of Feature.xml would be as below...
------------------------------------------------------------------------
<Feature
Id="{USE THE NEW GUID HERE}"
Title="New Feature"
Description="New Feature"
Scope="Web"
xmlns="http://schemas.microsoft.com/sharepoint/"
Hidden="False"
>
<ElementManifests>
<ElementManifest Location="Elements.xml" />
</ElementManifests>
</Feature>
------------------------------------------------------------------------

Step # 6 Copy the NewFeature folder from your project or local folder) to the following location on the SharePoint Server box. If you followed Step 1 - 6 by log in to the SP Server box, copy the folder locally.

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

SKIP THE BELOW STEP IF YOU ARE ON SP SERVER BOX ALREADY
Step # 7 Logon to SP Server box.

Step # 8 If you have map path to stsadm run the below command directly. Else, map to the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\bin\

stsadm -o installfeature –filename NewFeature\Feature.xml

This would install the feature

Step # 9 C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\bin\

stsadm -o activatefeature –filename NewFeature\Feature.xml -url http://ServerName/Sitecollection

This would activate the feature.

and now one should be able to access the NewFeaturePage.aspx page from http://ServerName/NewFeaturePage.aspx (based on where you deploy as part of your Elements file File URL Property).

Saturday, November 15, 2008

SharePoint - Add Users (Code)

private void Button1_Click(object sender, System.EventArgs e)
{
SPWeb web = SPControl.GetContextWeb(Context);
string username = TextBox1.Text;
string displayname = TextBox2.Text;
string email = TextBox3.Text;

SPRole admins = web.Roles["Administrator"];
try
{
admins.AddUser(username,email,displayname,"");
Label4.Text="Successfully added user";
}
catch(Exception ex)
{
Label4.Text=ex.ToString();
}
}

SharePoint - Copy Files (Code)

private SPWeb web;

private void Page_Load(object sender, System.EventArgs e)
{
web = SPControl.GetContextWeb(Context);
}


private void Button1_Click(object sender, System.EventArgs e)
{
int maxsize = Convert.ToInt32(TextBox1.Text);
SPFolder myfolder=web.GetFolder("Shared Documents");
SPFileCollection myfiles = myfolder.Files;
foreach (SPFile file in myfiles)
{
if (file.Length>(maxsize*1024))
{
Response.Write(file.Name + ": " + file.Length/1024 + "kb
");
file.CopyTo("Archive/"+file.Name,true);
}
}
}

CAML Query Builder

http://www.u2u.info/Blogs/karine/Lists/Posts/Post.aspx?ID=28

from Karine Bosch.

Friday, November 14, 2008

Collabarative Application Markup Language (CAML)

CAML (Collaborative Application Markup Language) is an XML based markup language used with the family of Microsoft SharePoint technologies (Windows Sharepoint Services and Office SharePoint Server). Unlike plain XML, CAML contains specific groups of tags to both define and display (render) data.

CAML allows developers to both construct and display data. Microsoft refers to elements used to display data as "Rendering" elements.

In general, most of all xml files in a sharepoint installation include CAML. Specifically CAML is very important in site and list definitions, via the Onet.xml files as well as other corresponding xml files. Here the CAML is used to define what elements exist on an instance of a site, and the display of these sub-elements, while the aspx files are used to define how to arrange and display those elements to form the site.
CAML is also used to query against Sharepoint lists and views, when programming against the SharePoint API.

CAML can be used to do the following:

1. Provide schema definition to the Web site provisioning system about how the site looks and acts.
2. Define views and forms for data and page rendering or execution.
3. Act as a rendering language that performs functions in the DLL like pulling a value from a particular field.
4. Provide batch functionality for posting multiple commands to the server using protocol.

Why would you use CAML as opposed to just using Microsoft FrontPage® or other editing tools?

1. To make universal changes, such as adding a new logo to the main pages of every site you create.
2. To define a content type, such as for adding Flash movies to the SharePoint team Web site.
3. It provides the ultimate in customization and flexibility; manipulating CAML allows you total control over the site provisioning system, for instance, when creating a list or adding a view.

CAML Queries:

CAML can be used to query data from various lists. See the below example...

SPWeb web = SPControl.GetContextWeb(this.Context);
SPView view = web.Lists["List Name"].Views["Search"];

// create a List View called "Search"

// Get
string query = view.Query;

// Set
view.Query = query;
view.Update();

String query = "";

// Some of other query conditions
query += ""; // Condtion
query += ""; // Operator
query += ""; // Field Name
query += "a"; // Value
query += "
"; // Close tags

-------------------------------------------------------------------
Resources : Google Search

SP Site Architecture

SP Object Model