Tuesday, September 30, 2008

Opening PDF in separate window

Scenario:
When you browse a PDF file , by default open in same window. Now you want to change the default behaviour to open it in separate window.

Solution:
PDF has the setting enabled. You can disable that setting.

Steps:
1. Open Acrobat Reader on you PC
2. Go to View > Preferences
3. Select 'Internet' from left side
4. Uncheck 'Display PDF in Browser' option

Note: This setting is a client side setting and all the above steps need to be followed on client machine which ever want to change the default behaviour.

Article:
http://www.bnl.gov/itd/webapps/pdf_help.asp

Programatically updating Field properties

Scenario:
You want to set the Field properties programatically

Code:

using(SPSite siteColl = new SPSite("http://localhost/testsite")){
using(SPWeb web = siteColl.OpenWeb()){

site.AllowUnsafeUpdates = true ;

SPList list = web.Lists["Tasks"];

SPField field = list.Fields["Title"];
field.Description = "This is the title";
field.Update(true);

list.Update();
web.AllowUnsafeUpdates = false ;
}
}
Article:

Making the Title as required field in Document Library

Scenario:
Document Library has Name as the required field , whereas Title is not. Now you want to make the Title field as required in a Document Library.

Solution:
You can navigate to the Document Library Settings and enable it by managing content type.

Steps:
1. Go to Document Library Settings
2. Click on Advanced Settings
3. Select 'Yes' for the option 'Do you want to manage the content types ?' and Save
4. Click on 'Document' link under Content Types section
5. You will see all the column listed
6. Click on 'Title' and now you can make it required field.
7. Save the changes

Sunday, September 28, 2008

Updating List Item for recalculate the Calculated Columns

Scenario:
You are using calculated columns in your list and you have reference to Today.

Solution:
Run a nightly job

Code:

using Microsoft.SharePoint;
using System.Configuration;

namespace UpdateSPList
{
class Program
{
static void Main(string[] args)
{
using(SPSite site = new SPSite(ConfigurationManager.AppSettings["Site"])) {
using(SPWeb web = site.OpenWeb()) {

SPList list = web.Lists[ConfigurationManager.AppSettings["List"]];
web.AllowUnsafeUpdates = true;
foreach (SPListItem item in list.Items)
{
item.SystemUpdate();
}
web.AllowUnsafeUpdates = false;
}
}
}
}
}
Application Configuration File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Site" value="http://My_Portal/Sites/TheSite"/>
<add key="List" value="Tasks"/>
</appSettings>
</configuration>
Article:

Saturday, September 27, 2008

Writing cookie at SharePoint Application startup

Scenario:
You want to write a Cookie value when SharePoint application is accessed by user.

Solution:
SharePoint being an ASP.Net Application, you can stuff some code in Global.asax file which is location in the WebApplication folder.

Code(Global.asax):

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Import Namespace="System.Web" %>

<SCRIPT language="C#" runat="server">
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
try
{
HttpContext ctx = HttpContext.Current;
HttpCookie newCookie = new HttpCookie("LoggedInUser",ctx.User.Identity.Name);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(newCookie);

}
catch (Exception)
{
// Eat the exception so that the site is still usable
// even if the stats go down from some reason.
}
}
</SCRIPT>
Article:
http://msdn.microsoft.com/en-us/library/aa287547(VS.71).aspx

Sending document as attachment in email

Scenario:
You client want to be able to actually e-mail the document itself from the document library to themselves, so they could read it apart from being on the SharePoint site.

Solution:
Design a Custom Application Page and use the code below to email the document.

Code:

using System.Net.Mail

private void SendEmail(string toAddress, string subject, SPFile file, SPList list)
{
SPWebApplication webApp = SPContext.Current.Site.WebApplication;
SPOutboundMailServiceInstance mailServer = webApp.OutboundMailServiceInstance;
string smtpServer = mailServer.Server.Address;

string listUrl = SPContext.Current.Web.Url + list.DefaultViewUrl;

MailMessage message = new MailMessage("administrator@training.com", toAddress);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = "This file was sent from the following SharePoint list: " +
"<a href=\"" + listUrl + "\">" + listUrl + "</a>.";

Stream stream = file.OpenBinaryStream();
//You can add code to figure out which MIME type to use based on the type of attachment.
Attachment attachment = new Attachment(stream, @"application/msword");
attachment.Name = file.Name;
message.Attachments.Add(attachment);

try
{
SmtpClient client = new SmtpClient(smtpServer);
//client.Send(message);
client.SendAsync(message,"mail sent.");

}
catch (Exception e)
{
throw e;
}
finally
{
stream.Close();
}
}
Article:http://furuknap.blogspot.com/2008/07/send-sharepoint-document-library-file.html

Friday, September 26, 2008

List of Content Type using Powershell

Scenario:
Getting list of Content Type for a site.

Solution:
Get the Web object and enumerate the content types

Code:

$site=spweb "http://localhost"
$web=$site.OpenWeb()

$web.lists | select title,contenttypes
Output:

Title
-----
Documents
Images
Master Page Gallery
Pages
Workflow History
Workflow Tasks

Article:
http://blogs.flexnetconsult.co.uk/colinbyrne/2006/12/03/SharePointPowerShell6ApprovingAllPublishingPages.aspx

Wednesday, September 24, 2008

Getting the site usage information

Scenario:
You want to get the basic site usage information

Solution:
You can get the basic site usage information using UsageInfo structure of site.

Code:

SPSite oSiteCollection = SPContext.Current.Site;
SPSite.UsageInfo oUsageInfo = oSiteCollection.Usage;

Int64 int64DiscussionStorage = oUsageInfo.DiscussionStorage;
Int64 int64Storage = oUsageInfo.Storage;
Int64 int64Bandwidth = oUsageInfo.Bandwidth;
Int64 int64Hits = oUsageInfo.Hits;
Int64 int64Visits = oUsageInfo.Visits;
Article:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.usageinfo.aspx

Manage SharePoint

SharePoint Manager 2007
The SharePoint Manager 2007 is a SharePoint object model explorer. It enables you to browse every site on the local farm and view every property. It also enables you to change the properties (at your own risk). This is a very powerfull tool for developers that like to know what the SharePoint holds of secrets.
http://www.codeplex.com/spm

Microsoft SharePoint Monitoring Kit download
http://www.microsoft.com/downloads/details.aspx?FamilyId=E4600FD9-F53D-4DED-88BF-6BB1932794F9&displaylang=en

Imtech Fields Explorer
Imtech Fields Explorer is a tool that can help you during the development process while working with fields. The tool allows you to explore properties of the fields contained within the (Site Collection) Content Types and Lists.
http://www.sharepointblogs.com/tmt/archive/2007/08/24/imtech-fields-explorer.aspx

Tuesday, September 23, 2008

Checking if a user has View Rights in Site Collection

SPSite siteCollection = new SPSite("http://localhost"); 

SPWeb ParentWeb = siteCollection.OpenWeb("/");
SPUserCollection allUsers = ParentWeb.Users;

foreach ( SPUser user in allUsers) {

if (user.LoginName.ToLower() == "sandeep") {

SPRoleCollection allGroups = user.Roles;

foreach ( SPRole role in allRoles) {

int right = group.PermissionMask & SPRights.ViewListItems;

if (right == SPRights.ViewListItems) {

Console.Write("User has Reader permissions.");

}
}
}
}

Monday, September 22, 2008

Adding users/ groups to sharepoint web

Scenario:
You want to add certain users/group as a part of site creation.

SPWeb web = SPContext.Current.Web;

SPRoleDefinition role = site.RoleDefinitions["Contribute"];

// Adding User Groups

SPRoleAssignment roleAssignmentGroup;

roleAssignmentGroup = new SPRoleAssignment(@"Training\ConsumerGroup","consumers@training.com","All Consumers of the website","Notes about Consumer Group");

roleAssignmentGroup.RoleDefinitionBindings.Add(role);

web.RoleAssignments.Add(roleAssignmentGroup);

// Adding specific users

SPRoleAssignment roleAssignmentUser;

roleAssignmentUser = new SPRoleAssignment(@"TRAINING\SandeepK","sandeep@training.com","Sandeep Nahta","Notes:SharePoint Consultant");

roleAssignmentUser.RoleDefinitionBindings.Add(role);

web.RoleAssignments.Add(roleAssignmentUser);
Usage:
Provisioning Feature Activation , Console Application

Programatically enabling / disabling Auditing

Enabling:

SPSite siteCollection = this.Site;
siteCollection.Audit.AuditFlags = SPAuditMaskType.All;
siteCollection.Audit.Update();
Disabling:
SPSite siteCollection = this.Site;
siteCollection.Audit.AuditFlags = SPAuditMaskType.None;
siteCollection.Audit.Update();

Executing any Timer job using code

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using Microsoft.SharePoint.Administration;

public ExecuteSharePointJob(string sJobName)
{
SPSite site = new SPSite("http://localhost");
//foreach (SPService srv in SPFarm.Local.Services)
//{
//foreach (SPJobDefinition job in srv.JobDefinitions)
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
string jobTitle = job.Title;

if (jobTitle == JobName)
{
Trace.WriteLine("***************** Start of execution for job");
job.Execute(new Guid("PassTheContentDBGUID"));
Trace.WriteLine("***************** End of execution for job");
}
}
//}
}

Friday, September 19, 2008

Programatically exporting item version and properties


string webUrl = workflowProperties.Web.Url;
SPListItem item = workflowProperties.Item;

// Create an object for the record to transfer.
SPExportObject exportObject = new SPExportObject();
exportObject.Type = SPDeploymentObjectType.ListItem;
exportObject.Url = webUrl + "/" + item.Url;

// Set the export settings.
SPExportSettings exportSettings = new SPExportSettings();
exportSettings.ExportMethod = SPExportMethodType.ExportAll;
exportSettings.IncludeSecurity = SPIncludeSecurity.All;
exportSettings.IncludeVersions = SPIncludeVersions.All;

exportSettings.AutoGenerateDataFileName = false;
exportSettings.BaseFileName = item.Name + ".cab";
exportSettings.SiteUrl = webUrl;
exportSettings.FileLocation = transferLocation;
exportSettings.ExportObjects.Add(exportObject);

// Export the record.
SPExport export = new SPExport(exportSettings);
export.Run();

// Write transfer event to audit log.
item.Audit.WriteAuditEvent("Record Transfered");

Thursday, September 18, 2008

Codes for out-of-box site templates

Template ID = 0
Desc: This template is used for initializing a new site.
Title: Global template
Name: GLOBAL#0

Template ID = 1
Desc: A site for teams to quickly organize, author, and share information. It provides a document library, and lists for managing announcements, calendar items, tasks, and discussions.
Title: Team Site
Name: STS#0

Template ID = 1
Desc: A blank site for you to customize based on your requirements.
Title: Blank Site
Name: STS#1

Template ID = 1
Desc: A site for colleagues to work together on a document. It provides a document library for storing the primary document and supporting files, a tasks list for assigning to-do items, and a links list for resources related to the document.
Title: Document Workspace
Name: STS#2

Template ID = 2
Desc: A site to plan, organize, and capture the results of a meeting. It provides lists for managing the agenda, meeting attendees, and documents.
Title: Basic Meeting Workspace
Name: MPS#0

Template ID = 2
Desc: A blank meeting site for you to customize based on your requirements.
Title: Blank Meeting Workspace
Name: MPS#1

Template ID = 2
Desc: A site for meetings that track status or make decisions. It provides lists for creating tasks, storing documents, and recording decisions.
Title: Decision Meeting Workspace
Name: MPS#2

Template ID = 2
Desc: A site to plan social occasions. It provides lists for tracking attendees, providing directions, and storing pictures of the event.
Title: Social Meeting Workspace
Name: MPS#3

Template ID = 2
Desc: A site to plan, organize, and capture the results of a meeting. It provides lists for managing the agenda and meeting attendees in addition to two blank pages for you to customize based on your requirements.
Title: Multipage Meeting Workspace
Name: MPS#4

Template ID = 3
Desc: A site for central administration. It provides Web pages and links for application and operations management.
Title: Central Admin Site
Name: CENTRALADMIN#0

Template ID = 4
Desc: A site for a community to brainstorm and share ideas. It provides Web pages that can be quickly edited to record information and then linked together through keywords
Title: Wiki Site
Name: WIKI#0

Template ID = 9
Desc: A site for a person or team to post ideas, observations, and expertise that site visitors can comment on.
Title: Blog
Name: BLOG#0

Template ID = 7
Desc: A site to centrally manage documents in your enterprise.
Title: Document Center
Name: BDR#0

Template ID = 14483
Desc: This template creates a site designed for records management. Records managers can configure the routing table to direct incoming files to specific locations. The site prevents records from being modified after they are added to the repository.
Title: Records Center
Name: OFFILE#0

Template ID = 14483
Desc: This template creates a site designed for records management. Records managers can configure the routing table to direct incoming files to specific locations. The site prevents records from being modified after they are added to the repository.
Title: Records Center
Name: OFFILE#1

Template ID = 40
Desc: This template creates a site for administering shared services
Title: Shared Services Administration Site
Name: OSRV#0

Template ID = 20
Desc: This template is obsolete.
Title: SharePoint Portal Server Site
Name: SPS#0

Template ID = 21
Desc: This web template defines a Personal Space for an individual participating on a SharePoint Portal.
Title: SharePoint Portal Server Personal Space
Name: SPSPERS#0

Template ID = 22
Desc: A site for delivering personalized views, data, and navigation from this site collection into My Site. It includes personalization specific Web Parts and navigation that is optimized for My Site sites.
Title: Personalization Site
Name: SPSMSITE#0

Template ID = 30
Desc: This template is obsolete.
Title: Contents area Template
Name: SPSTOC#0

Template ID = 31
Desc: This template is obsolete.
Title: Topic area template
Name: SPSTOPIC#0

Template ID = 32
Desc: This template is obsolete.
Title: News Site
Name: SPSNEWS#0

Template ID = 39
Desc: A blank site for expanding your Web site and quickly publishing Web pages. Contributors can work on draft versions of pages and publish them to make them visible to readers. The site includes document and image libraries for storing Web publishing assets.
Title: Publishing Site
Name: CMSPUBLISHING#0

Template ID = 53
Desc: This template creates a site for publishing Web pages on a schedule, with workflow features enabled. By default, only Publishing subsites can be created under this site. A Document and Picture Library are included for storing Web publishing assets.
Title: Publishing Site
Name: BLANKINTERNET#0

Template ID = 53
Desc: This template creates the Press Releases subsite for an Internet-facing corporate presence website.
Title: Press Releases Site
Name: BLANKINTERNET#1

Template ID = 53
Desc: A site for publishing Web pages on a schedule by using approval workflows. It includes document and image libraries for storing Web publishing assets. By default, only sites with this template can be created under this site.
Title: Publishing Site with Workflow
Name: BLANKINTERNET#2

Template ID = 33
Desc: A site for publishing news articles and links to news articles. It includes a sample news page and an archive for storing older news items.
Title: News Site
Name: SPSNHOME#0

Template ID = 34
Desc: A site for listing and categorizing important sites in your organization. It includes different views for categorized sites, top sites, and a site map.
Title: Site Directory
Name: SPSSITES#0

Template ID = 36
Desc: This template is obsolete.
Title: Community area template
Name: SPSCOMMU#0

Template ID = 38
Desc: A site for creating, managing, and delivering Web pages, dashboards, and key performance indicators that communicate metrics, goals, and business intelligence information.
Title: Report Center
Name: SPSREPORTCENTER#0

Template ID = 47
Desc: A starter site hierarchy for an intranet divisional portal. It includes a home page, a News site, a Site Directory, a Document Center, and a Search Center with Tabs. Typically, this site has nearly as many contributors as readers and is used to host team sites.
Title: Collaboration Portal
Name: SPSPORTAL#0

Template ID = 50
Desc: A site for delivering the search experience. The welcome page includes a search box with two tabs: one for general searches, and another for searches for information about people. You can add and customize tabs to focus on other search scopes or result types.
Title: Search Center with Tabs
Name: SRCHCEN#0

Template ID = 51
Desc: This template creates a profile site that includes page layout with zones
Title: Profiles
Name: PROFILES#0

Template ID = 52
Desc: A starter site hierarchy for an Internet-facing site or a large intranet portal. This site can be customized easily with distinctive branding. It includes a home page, a sample press releases subsite, a Search Center, and a login page. Typically, this site has many more readers than contributors, and it is used to publish Web pages with approval workflows.
Title: Publishing Portal
Name: BLANKINTERNETCONTAINER#0

Template ID = 54
Desc: A site used for hosting personal sites (My Sites) and the public People Profile page. This template needs to be provisioned only once per Shared Service Provider, please consult the documentation for details.
Title: My Site Host
Name: SPSMSITEHOST#0

Template ID = 90
Desc: A site for delivering the search experience. The site includes pages for search results and advanced searches.
Title: Search Center
Name: SRCHCENTERLITE#0

Template ID = 90
Desc: The Search Center template creates pages dedicated to search. The main welcome page features a simple search box in the center of the page. The template includes a search results and an advanced search page. This Search Center will not appear in navigation.
Title: Search Center
Name: SRCHCENTERLITE#1

Creating a new list using SharePoint List WebService


MyWebService.Lists lists = new MyWebService.Lists();
lists.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Tasks List feature Guid ( get it from SharePoint )
Guid featureGuid = new Guid("{8D6E4CFC-A0A2-4769-BC3D-8B63DD030A24}");
lists.AddListFromFeature("Tasks List", "This is new task list instance!", featureGuid, 10010);

Using the SPGridView in custom code

ApplicationPage.aspx


<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Assembly Name="CustomApplicationPages, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=d4e5777b16a5749f" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
Inherits="CustomApplicationPages.ApplicationPage" EnableViewState="false" EnableViewStateMac="false" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint,Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">

<SharePoint:SPGridView runat="server"
ID="grid"
AutoGenerateColumns="false"
RowStyle-BackColor="#DDDDDD"
AlternatingRowStyle-BackColor="#EEEEEE" />
</asp:Content>

<asp:Content ID="PageTitle" contentplaceholderid="PlaceHolderPageTitle" runat="server">SharePoint GridView</asp:Content>

<asp:Content ID="PageTitleInTitleArea" contentplaceholderid="PlaceHolderPageTitleInTitleArea" runat="server">
Application Page : Using the SPGridView control
</asp:Content>
ApplicationPage.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomApplicationPages {

public class ApplicationPage : LayoutsPageBase {

// add control fields to match controls tags on .aspx page
protected SPGridView grid;

protected override void OnLoad(EventArgs e) {

grid = new SPGridView();
grid.AutoGenerateColumns = false ;
grid.CssClass = "ms-listviewtable";
grid.AlternatingRowStyle.CssClass = "ms-alternating";
grid.Width = new Unit(50, UnitType.Percentage);
grid.GridLines = GridLines.None;
grid.HeaderStyle.Font.Bold = true;
grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

DataTable table = new DataTable();
//TO DO : Populate the DataTable here <-----

SPBoundField col= new SPBoundField();
col.HeaderText = "Product Name";
col.DataField = "ProductName";

grid.Columns.Add(col);
Controls.Add(grid);

grid.DataSource = table.DefaultView;
grid.DataBind();

}
}
}

MOSS Feature GUID Details

Office SharePoint Server Enterprise Site Collection features(Scope:Site)
Features such as the business data catalog, forms services, and Excel Services, included in the Office SharePoint Server Enterprise License.

<Feature  Id="8581A8A7-CF16-4770-AC54-260265DDB0B2"">
<!-- Office SharePoint Server Enterprise Site Collection features -->
</Feature>
Office SharePoint Server Publishing Infrastructure(Scope:Site)
Provides centralized libraries, content types, master pages and page layouts and enables page scheduling and other publishing functionality for a site collection.
<Feature ID="F6924D36-2FA8-4f0b-B16D-06B7250180FA">
  <!-- Office SharePoint Server Publishing Infrastructure  -->
</Feature>
Office SharePoint Server Search Web Parts
This feature uploads all web parts required for Search Center.

Office SharePoint Server Standard Site Collection features
Features such as user profiles and search, included in the Office SharePoint Server Standard License.
<Feature ID="b21b090c-c796-4b0f-ac0f-7ef1659c20ae">
<!-- Office SharePoint Server Standard Site Collection features -->
</Feature>
Collect Signatures Workflow
Gathers signatures needed to complete a Microsoft Office document.

Disposition Approval Workflow
Manages document expiration and retention by allowing participants to decide whether to retain or delete expired documents.

Routing Workflows
Workflows that send a document for feedback or approval.

Three-state workflow
Use this workflow to track items in a list.

Translation Management Workflow
Manages document translation by creating copies of the document to be translated and assigning translation tasks to translators.

Search Center Url (Scope:Site)
<Feature ID="7AC8CC56-D28E-41f5-AD04-D95109EB987A" >
<!-- SearchCenter Url feature -->
<Properties xmlns="http://schemas.microsoft.com/sharepoint/">
<Property Key="SearchCenterUrl" Value="~SiteCollection/SearchCenter/" />
</Properties>
</Feature>
Other Features and GUIDs:
14173c38-5e2d-4887-8134-60f9df889bad : PageConverters
1dbf6063-d809-45ea-9203-d3ba4a64f86d : SearchAndProcess
d992aeca-3802-483a-ab40-6c9376300b61 : BulkWorkFlowTimerJob
4f56f9fa-51a0-420c-b707-63ecbb494db1 : Office Sharepoint Server Standard Web Application features
E978B1A6-8DE7-49d0-8600-09A250354E14 : LocalSiteDirectorySettings
14AAFD3A-FCB9-4bb7-9AD7-D8E36B663BBD : LocalSiteDirectoryControl
5F3B0127-2F1D-4cfd-8DD2-85AD1FB00BFC : PortalLayouts
2ED1C45E-A73B-4779-AE81-1524E4DE467A : WebPartAdderGroups
FeatureId="00BFEA71-D1CE-42de-9C63-A44004CE0104" <!-- AnnouncementsList Feature -->
FeatureId="00BFEA71-7E6D-4186-9BA8-C047AC750105" <!-- ContactsList Feature -->
FeatureId="00BFEA71-DE22-43B2-A848-C05709900100" <!-- CustomList Feature -->
FeatureId="00BFEA71-F381-423D-B9D1-DA7A54C50110" <!-- DataSourceLibrary Feature -->
FeatureId="00BFEA71-6A49-43FA-B535-D15C05500108" <!-- DiscussionsList Feature -->
FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" <!-- DocumentLibrary Feature -->
FeatureId="00BFEA71-EC85-4903-972D-EBE475780106" <!-- EventsList Feature -->
FeatureId="00BFEA71-513D-4CA0-96C2-6A47775C0119" <!-- GanttTasksList Feature -->
FeatureId="00BFEA71-3A1D-41D3-A0EE-651D11570120" <!-- GridList Feature -->
FeatureId="00BFEA71-5932-4F9C-AD71-1557E5751100" <!-- IssuesList Feature -->
FeatureId="00BFEA71-2062-426C-90BF-714C59600103" <!-- LinksList Feature -->
FeatureId="00BFEA71-F600-43F6-A895-40C0DE7B0117" <!-- NoCodeWorkflowLibrary Feature -->
FeatureId="00BFEA71-52D4-45B3-B544-B1C71B620109" <!-- PictureLibrary Feature -->
FeatureId="00BFEA71-EB8A-40B1-80C7-506BE7590102" <!-- SurveysList Feature -->
FeatureId="00BFEA71-A83E-497E-9BA0-7A5C597D0107" <!-- TasksList Feature -->
FeatureId="00BFEA71-C796-4402-9F2F-0EB9A6E71B18" <!-- WebPageLibrary Feature -->
FeatureId="00BFEA71-2D77-4A75-9FCA-76516689E21A" <!-- WorkflowProcessLibrary Feature -->
FeatureId="00BFEA71-4EA5-48D4-A4AD-305CF7030140" <!-- WorkflowHistoryList Feature -->
FeatureId="00BFEA71-1E1D-4562-B56A-F05371BB0115" <!-- XmlFormLibrary Feature -->

Wednesday, September 17, 2008

Using ListView control in custom code

SPListView.aspx

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" 
Inherits="SPListView, ListView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=566105bsandeepbe" %>

<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebControls" TagPrefix="sharepoint" %>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<sharepoint:ListView ID="SPListView" runat="server" />
</asp:Content>


SPListView.cs
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class SPListView : LayoutsPageBase
{
protected ListView SPListView;

protected void Page_Load(object sender, EventArgs e)
{
SPListView.ListId = Request.QueryString["ListId"];
}
}

Programatically creating an Application Pool

Code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.ComponentModel;
using System.Collections.Generic;

SPWebApplicationBuilder wab = new SPWebApplicationBuilder(SPFarm.Local);
wab.Port = 100
SPWebApplication wa = wab.Create();
wa.Provision();

Using ListViewByQuery control in your custom code

Code:

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" 
Inherits="SPListViewPage, ListView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=566105b43a7965be" %>

<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebControls" TagPrefix="sharepoint" %>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<sharepoint:ListViewByQuery ID="SPListViewByQuery" runat="server" />
</asp:Content>

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class SPListViewPage : LayoutsPageBase
{
protected ListViewByQuery SPListViewByQuery;

protected void Page_Load(object sender, EventArgs e)
{
SPList list = this.Web.Lists["Contacts"];
SPView view = list.Views["All contacts"];
SPQuery query = new SPQuery(view);
query.ViewFields = "<FieldRef Name='LinkTitle'/>" +
"<FieldRef Name='FirstName'/>" +
"<FieldRef Name='Company'/>" +
"<FieldRef Name='WorkCity'/>";
query.Query = "<Where>" +
"<Eq>" +
"<FieldRef Name='Company' />" +
"<Value Type='Text'>Sandeep Training Company</Value>" +
"</Eq>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='LinkTitle' />" +
"</OrderBy>";
SPListViewByQuery.List = list;
SPListViewByQuery.Query = query;
}
}

Getting all the Application Pool information

Code:


using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration
using System.ComponentModel;
using System.Collections.Generic;

SPWebServiceCollection wsc = new SPWebServiceCollection(SPFarm.Local);

foreach (SPWebService ws in wsc)
{
SPApplicationPoolCollection apc = ws.ApplicationPools;
foreach (SPApplicationPool ap in apc)
{
Response.Write(ap.Name);
Response.Write("</br>");
}
}

Using People Picker control in your Webpart

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls;

namespace PeoplePickerWebPart
{
public class TeamMemberPicker : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void CreateChildControls()
{
try
{
PeopleEditor PeoplePickerControl = new PeopleEditor();
PeoplePickerControl.AllowEmpty = true;
PeoplePickerControl.AllowTypeIn = true;
PeoplePickerControl.BrowseButtonImageName = "browse";
PeoplePickerControl.BrowseButtonToolTip = "Pick an TeamMember";
PeoplePickerControl.CheckButtonImageName = "Validate user";
PeoplePickerControl.ErrorMessage = "No TeamMember Found";

this.Controls.Add(PeoplePickerControl);
base.CreateChildControls();
}
catch (Exception ex)
{
Literal _ErrorMessageLiteral = new Literal();
_ErrorMessageLiteral.Text = "Custom Error: " + ex.Message;

this.Controls.Clear();
this.Controls.Add(_ErrorMessageLiteral);
}
}
}
}
Articles:
http://dotnet.org.za/zlatan/archive/2008/04/21/using-peopleeditor-control-with-web-parts-in-sharepoint-2007-wss-3-0.aspx

Reading Change Log for a User Profile

Code:

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

namespace ChangeLog
{
class Program
{
static void Main(string[] args)
{
try
{
using (SPSite spSite = new SPSite(@"http://localhost"))
{
ServerContext siteContext = ServerContext.GetContext(spSite);
UserProfileManager pmManager = new UserProfileManager(siteContext);

// This gets some subset of changes to a user profile

// Display the changes that have occurred in the last month
DateTime dtNumberDays =
DateTime.UtcNow.Subtract(TimeSpan.FromDays(30));
// Create a change token to compare the number of days
UserProfileChangeToken upChangeToken =
new UserProfileChangeToken(dtNumberDays);

// Create a query object to determine which changes are displayed
UserProfileChangeQuery QueryAnniversayAndColleagues =
new UserProfileChangeQuery(false, true);
QueryAnniversayAndColleagues.ChangeTokenStart = upChangeToken;
QueryAnniversayAndColleagues.Anniversary = true;
QueryAnniversayAndColleagues.Colleague = true;

string strUserName = "domain\\sandeep";

if (pmManager.UserExists(strUserName))
{
UserProfile spMyUser = pmManager.GetUserProfile(strUserName);

UserProfileChangeCollection MyUserProfileChanges = spMyUser.GetChanges(QueryAnniversayAndColleagues);

foreach (UserProfileChange MyUserChange in MyUserProfileChanges)
{
Console.WriteLine(MyUserChange.EventTime.ToString());
if (MyUserChange is UserProfileAnniversaryChange)
{
UserProfileAnniversaryChange AnniversryEvent =
(UserProfileAnniversaryChange)MyUserChange;
Console.WriteLine(AnniversryEvent.Anniversary);
Console.WriteLine(AnniversryEvent.ProfileProperty);
}
else if (MyUserChange is UserProfileColleagueChange)
{
UserProfileColleagueChange ColleagueEvent = (UserProfileColleagueChange)MyUserChange;
}
}
}
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}

Programatically deleting an Audience from Audience Collection

Code:

using (SPSite spSite = new SPSite(@"http://localhost"))
{
ServerContext siteContext = ServerContext.GetContext(spSite);
AudienceManager amManager = new AudienceManager(siteContext);

string strName = "Technology Department";

if (amManager.Audiences.AudienceExist(strName))
{
amManager.Audiences.Remove(strName);
}
}

Programatically getting the Audience Membership

Code:

using (SPSite spSite = new SPSite(@"http://localhost"))
{
ServerContext siteContext = ServerContext.GetContext(spSite);
AudienceManager amManager = new AudienceManager(siteContext);

string strName = "HR Department";
Audience oAudience = amManager.Audiences[strName];

ArrayList oAudienceMembers = oAudience.GetMembership();

foreach (UserInfo oUser in oAudienceMembers)
{
Console.WriteLine(oUser.PreferredName);
Console.WriteLine(oUser.NTName);
Console.WriteLine(oUser.Email);
}
}

Programatically adding Audience

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Audience;

namespace LearnSharePoint
{
class Audience
{
static void Main(string[] args)
{
try
{
using (SPSite spSite = new SPSite(@"http://localhost"))
{
ServerContext siteContext = ServerContext.GetContext(spSite);
AudienceManager amManager = new AudienceManager(siteContext);

AudienceCollection acCollection = amManager.Audiences;
string strName = "HR Department";
string strDescription = "All members of the human resource department";

if (!acCollection.AudienceExist(strName))
{
acCollection.Create(strName, strDescription);
}

foreach (Audience tempAudience in acCollection)
{
Console.WriteLine(tempAudience.AudienceName);
Console.WriteLine(tempAudience.AudienceSite);
Console.WriteLine(tempAudience.MemberShipCount);
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}

Tuesday, September 16, 2008

Import Export SiteCollection using STSADM

Export:


stsadm -o export -url http://localhost/sites/recovery -filename recovery.export -versions 4 -includeusersecurity
Create Site Collection:
Create a site collection because IMPORT command doesn't create a new site collection
stsadm -o createsite -url http://localhost/sites/recovery_copy -owneremail administrator@company.com -ownerlogin domain\administrator -sitetemplate STS#1
Import:
stsadm -o import -url http://localhost/sites/recovery_copy -filename recovery.export -includeusersecurity
Note :
Please note import / export is only used to backup/restore a sub-web ( SPWeb ). For backup/restore of site collection you will need Backup / Restore commands from STSADM or Powershell

Creating multiple sites/webs using STSADM

CreateSites.bat

for /f "skip=1 tokens=1-4" %%a in (sites.txt) do @stsadm -o createsite -url http://server/sites/%%a -sitetemplate STS#1 -owneremail %%b -ownerlogin %%c -title %%d

for /f "skip=1 tokens=1-4" %%a in (webs.txt) do @stsadm -o createweb -url http://server/%%a -sitetemplate STS#1 -title %%d

pause
sites.txt
URL OwnersEmail OwnerLogin Title
Site01 administrator@company.com administrator SiteNo1
Site02 administrator@company.com administrator SiteNo2
Site03 administrator@company.com administrator SiteNo3
Site04 administrator@company.com administrator SiteNo4
Webs.txt
URL Title
Web01 WebName1
Web02 WebName2
Web03 WebName3
Web04 WebName4
Article:
http://www.robvanderwoude.com/ntfortokens.html
http://www.geocities.com/rick_lively/MANUALS/COMMANDS/F/FOR_F.HTM

Monday, September 15, 2008

Verify and Upload Form Template from Command line


stsadm –o verifyformtemplate –filename path\filename

stsadm –o uploadformtemplate –filename path\filename
Article:
http://technet.microsoft.com/en-us/library/cc262921.aspx

Friday, September 12, 2008

Learn SharePoint

I think this is the most common question I get from anyone who is new to Sharepoint.
Here's my favorites. Also one strong recommendation from my side is , dont buy 10 books and dont read 100 blogs .. trust me you will be most lost. Focus on reading SDK , its awesome and just buy one good book which you can read on the way to work in Metro

:-)

Video's

MSDN
Sharepoint Videos
Watch and Learn Training
Sharepoint Community

SDK's
http://msdn.microsoft.com/en-us/library/bb931736.aspx ( MOSS )
http://msdn.microsoft.com/en-us/library/bb931737.aspx ( WSS )

Training Material
Training Wssdemo

VHD's
www.microsoft.com/vhd

Books
<<<----- My recommendations you can see on left side.

Automate SharePoint

STSADM Custom Extensions
Automating SharePoint 2007 Configurations via STSADM Custom Extensions
http://stsadm.blogspot.com/2007/08/stsadm-commands_09.html

SharePoint PowerShell Scripts
A must have!
http://www.codeplex.com/iLoveSharePoint

Debug SharePoint

SharePoint Portal Server Support Report Tool (SPSReport)
The SPS Reporting Tool is utilized to gather detailed information regarding a systems current configuration. The data collected will assist the Microsoft Support Professional with fault isolation. The reporting tool DOES NOT make any registry changes or modifications to the operating system.
http://www.codeplex.com/spsreport/Release/ProjectReleases.aspx?ReleaseId=5706

WinDbg
http://www.microsoft.com/whdc/devtools/debugging/install64bit.mspx

Fiddler
HTTP traffic monitors for IE
http://www.fiddler2.com/fiddler2/

Live HTTP Headers 0.14
HTTP traffic monitors for FireFox
https://addons.mozilla.org/en-US/firefox/addon/3829

SharePoint SUSHI
http://www.codeplex.com/sushi

Logging Solution ( Multiple options )
http://hristopavlov.wordpress.com/sptraceview/
http://www.codeplex.com/wssmosslogfilereader/

SpsDev.Com ULS Log Reader
http://www.spsdev.com/ulsreader.aspx

SharePoint Log Viewer
http://www.codeplex.com/SPLogViewer

SharePoint Logging Spy
http://www.codeplex.com/sharepointloggingspy

Business Data Catalog Sample File

<LobSystem
Type="Database"
Version="1.0.0.01"
Name="AdventureWorks"
xmlns="http://schemas.microsoft.com/office/2006/03/BusinessDataCatalog">


<AccessControlList>
<AccessControlEntry Principal="domain\you">
<Right BdcRight="Execute"/>
<Right BdcRight="Edit"/>
<Right BdcRight="SetPermissions"/>
<Right BdcRight="SelectableInClients"/>
</AccessControlEntry>
<AccessControlEntry Principal="domain\BDCUsers">
<Right BdcRight="Execute"/>
<Right BdcRight="SelectableInClients"/>
</AccessControlEntry>
</AccessControlList>


<LobSystemInstances>
<LobSystemInstance Name="AdventureWorksDB">
<Properties>
<Property Name="AuthenticationMode" Type="System.String">PassThrough</Property>
<Property Name="DatabaseAccessProvider" Type="System.String">SqlServer</Property>
<Property Name="RdbConnection Data Source" Type="System.String">SQLServerMachineName</Property>
<Property Name="RdbConnection Initial Catalog" Type="System.String">AdventureWorks</Property>
<Property Name="RdbConnection Integrated Security" Type="System.String">SSPI</Property>
</Properties>
</LobSystemInstance>
</LobSystemInstances>

<Entities>
<Entity Name="Customer">

<Properties>
<Property Name="Title" Type="System.String">Name</Property>
</Properties>

<Identifiers>
<Identifier Name="CustomerID" TypeName="System.Int32"/>
</Identifiers>


<Methods>
<Method Name ="GetCustomers">
<Properties>
<Property Name="RdbCommandText" Type="System.String">
SELECT CustomerID,LastName + ', ' + FirstName as Name,Phone, EmailAddress
FROM Sales
</Property>

<Property Name="RdbCommandType" Type="System.String">Text</Property>
</Properties>

<Parameters>
<Parameter Direction="Return" Name="Customers">
<TypeDescriptor TypeName="System.Data.IDataReader, System.Data, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" IsCollection="true" Name="CustomerDataReader">
<TypeDescriptors>
<TypeDescriptor TypeName="System.Data.IDataRecord, System.Data,Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Name="CustomerDataRecord">
<TypeDescriptors>
<TypeDescriptor TypeName="System.Int32" IdentifierName="CustomerID" Name="customerID" />
<TypeDescriptor TypeName="System.String" Name="Name" />
<TypeDescriptor TypeName="System.String" Name="Phone" />
<TypeDescriptor TypeName="System.String" Name="EmailAddress" />
</TypeDescriptors>
</TypeDescriptor>
</TypeDescriptors>
</TypeDescriptor>
</Parameter>
</Parameters>

<MethodInstances>
<MethodInstance
Name="CustomerFinderInstance" Type="Finder" ReturnParameterName="Customers" ReturnTypeDescriptorName="CustomerDataReader" />

</MethodInstances>

</Method>
</Methods>
</Entity>
</Entities>

</LobSystem>
Articles:
http://msdn.microsoft.com/en-us/office/bb251754.aspx

What is Business Data Catalog ?

Business Data Catalog, a new feature introduced in Microsoft Office SharePoint Server 2007, provides an easy way to integrate business data from back-end server applications, such as SAP or Siebel, within Office SharePoint Server 2007 without writing any code.Business Data Catalog provides built-in support for displaying data from databases and Web services. That is, you can use Business Data Catalog to display data from your SAP, Siebel, or other line-of-business (LOB) application via Web services or databases.

Wednesday, September 10, 2008

Scripting STSADM commands

pushd %programfiles%\common files\microsoft shared\web server extensions\12\bin

//call the STSADM commands here

popd
OR
SET PATH=%PATH%;%programfiles%\common files\microsoft shared\web server extensions\12\bin

//call the STSADM commands here

Custom Content Page with Code

Scenario:
You want to add a new custom Content Page with some code. You have two different choices to do that, inline code or code behind.

Recommended:
Go for Code Behind. Content Page lives in SharePoint Content Database and can be customized using SPD. Inline script will only work when the page is uncustomized, but once it is customized, SharePoint's safe mode parser will block the page from being executed.

Article:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx

Getting all the group for a particular web


public IList<string> GetAllUserGroups(string url)
{
IList<string> groupList = new List<string>();

using (SPSite site = new SPSite(url))
{
SPGroupCollection groups = site.RootWeb.SiteGroups;

foreach (SPGroup g in groups)
{
groupList.Add(g.Name);
}
}

return groupList;
}

Modifying Content Query Webpart programatically

Scenario:
You want to move your CQWP from one environment to another. Suggested way is to configure them in DEV environment and Export them. But painful aspect of this process is that with most of the Out of Box webparts they carry LISTGUIDs which are not available in next environment.

Steps:
1. Configure CQWP with filters and List you want to attach
2. Export the WEBPART file and open it using Visual Studio or Notepad
3. Look for ListGuid property and delete it all together.( Look for remarks )
4. Now Import it in new environment
5. Set List either manually in new environment or Set it programatically as shown , i created a layout page to configure the webparts )

ConfigureCQWP.ASPX ( 12/Template/Layouts/Client/):

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, 
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
protected override void OnLoad(EventArgs e)
{

try
{
SPWeb web= SPContext.Current.Web;
lblSiteTitle.Text = site.Title;

string sDocumentLibraryName = "Shared Documents";
Guid listID = default(System.Guid);

bool bFound = false;

foreach (SPList list in web.Lists)
{
if (list.Title.ToLower() == sDocumentLibraryName.ToLower())
{
listID = list.ID;
bFound = true;
break;
}
}

if (bFound)
{

web.AllowUnsafeUpdates = true;

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager WPMgr = web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);

foreach (WebPart wp in WPMgr.WebParts)
{
ContentByQueryWebPart CQWPart = wp as ContentByQueryWebPart;
if (CQWPart != null)
{
CQWPart.WebUrl = site.ServerRelativeUrl;
WPMgr.SaveChanges(CQWPart);
//CQWPart.ListName = sDocumentLibraryName;
//CQWPart.ListGuid = listID;
//CQWPart.Title = "NewP";
}
}
lblSiteStatus.Text = "Configured Sucessfully...";
}
else
{
lblSiteStatus.Text = "Some Error occured during WebPart configuration, Please configure manually...";
}
}
catch (Exception ex)
{
lblSiteStatus.Text = "Error :" + ex.ToString();
}
}
</script>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table border="1" cellpadding="4" cellspacing="0" style="font-size: 12">
<tr>
<td>
Site Title:</td>
<td>
<asp:Label ID="lblSiteTitle" runat="server" /></td>
</tr>
<tr>
<td>
Site ID:</td>
<td>
<asp:Label ID="lblSiteStatus" runat="server" /></td>
</tr>
</table>
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">Configure Content Query Webpart</asp:Content>
<asp:Content ID="PageTitleInTitleArea" runat="server" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea">Configure Content Query Webpart
</asp:Content>
Remarks:
The WebUrl property determines the ContentByQueryWebPart object's mode is determined by the WebUrl, ListGuid, and ListName properties.

-- If the WebUrl, ListGuid, and ListName properties are set, the mode is List.

-- If the WebUrl is set and ListGuid and ListName are empty, the mode is Web.

-- If WebUrl, ListGuid and ListName are empty, the mode is Site Collection.

-- If both ListGuid and ListName properties are set, ListGuid takes precedence.

Tuesday, September 9, 2008

Custom Application Page for ListID issue

Scenario:
You want to provide a link to a particular System Application Page, but all the application pages accepts parameter in form of some ID which is not unique in different environments.

Solution:
Custom Application page that accepts the ListName and page you want to get redirected to. The new custom page will internally gets the correct ListID and then will re-direct to the correct Application page.

Redirect.aspx(12\Template\Layouts\Client\):

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
protected override void OnLoad(EventArgs e)
{
SPWeb site = this.Web;

Guid listID = default(System.Guid);

string listName = Request.QueryString["List"];
string pageName = Request.QueryString["Page"];

if (listName != null && pageName != null)
{
foreach (SPList list in site.Lists)
{
if (list.Title.ToLower() == listName.ToLower())
{
listID = list.ID;
break;
}
}

Response.Redirect(this.Web.Url + @"/_layouts/" + pageName + ".aspx?List=" + listID);
}
}
</script>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
Redirection Page - Please pass the proper Request Query Parameters to get the redirection to work.</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">Redirection Page</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea">Redirection Page</asp:Content>


Usage:
Now you can call this Redirect page as
http://localhost/_layouts/client/redirect.aspx?List=Tasks&Page=listedit

and you will be redirected to the List Settings ( listedit.aspx ) of the Tasks list.

Monday, September 8, 2008

Creating User-Defined Function for Excel

Code:

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Office.Excel.Server.Udf;

namespace ExcelSamples
{
[UdfClass]
public class MyFirstUDF
{
[UdfMethod]
public Int32 RandomNo()
{
Random r = new Random();
return (Int32)((r.NextDouble()*5)+1);
}
}
}
Article:
http://msdn.microsoft.com/en-us/library/bb428649.aspx
http://www.wrox.com/WileyCDA/Section/Excel-Services-User-Defined-Functions-UDFs-.id-305100.html

Creating Custom Application Page ( Code Behind )

Scenario:
You want to write a Custom Application Page for some additional configurations for all of your sites.

MyConfig.ASPX(12/TEMPLATE/Layouts/Client/):


<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="CustomApplicationPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d4e5777b16a5749f" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
Inherits="CustomApplicationPages.MyConfig"
EnableViewState="false" EnableViewStateMac="false" %>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">
<table border="1" cellpadding="1" cellspacing="0" style="font-size:12">
<tr>
<td>Site Title:</td>
<td><asp:Label ID="lblSiteTitle" runat="server" /></td>
</tr>
<tr>
<td>Site ID:</td>
<td><asp:Label ID="lblSiteID" runat="server" /></td>
</tr>
</table>
</asp:Content>

<asp:Content ID="PageTitle" runat="server"
contentplaceholderid="PlaceHolderPageTitle" >
Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
Custom Application Page : 'Hello World' with code behind
</asp:Content>

MyConfig.cs(GAC ,CustomApplicationPages.dll)
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomApplicationPages {

public class MyConfig : Microsoft.SharePoint.WebControls.LayoutsPageBase {

// add control fields to match controls tags on .aspx page
protected Label lblSiteTitle;
protected Label lblSiteID;

protected override void OnLoad(EventArgs e) {

// get current site and web
SPSite siteCollection = this.Site;
SPWeb site = this.Web;

// program against controls on .aspx page
lblSiteTitle.Text = site.Title;
lblSiteID.Text = site.ID.ToString().ToUpper();
}
}
}
Usage:
You can access to the page from any web i.e.
 http://localhost/_layouts/client/myconfig.aspx
or you can also write a CustomAction to access the URL

ListID fix for the DataView webpart

Scenario:
You want to use a ListView webpart on your page, but ListView is tied to a ListID which will not be the same ListID in any other environment.

Fix:
Open the ListView in SharePoint Designer and tie it to ListName ( Tasks in this example) rather than ListView ID

Code:

<%@ Register TagPrefix="sharepoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register TagPrefix="webpartpages" Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<sharepoint:SPDataSource runat="server" DataSourceMode="List" SelectCommand="&lt;View&gt;&lt;Query&gt;&lt;OrderBy&gt;&lt;FieldRef Name=&quot;ID&quot;/&gt;&lt;/OrderBy&gt;&lt;/Query&gt;&lt;/View&gt;" UpdateCommand="" InsertCommand="" DeleteCommand="" UseInternalName="True" IncludeHidden="True" ID="datasource1">


<SelectParameters>
<webpartpages:DataFormParameter ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Tasks" Name="ListName">
</webpartpages:DataFormParameter>

<asp:QueryStringParameter QueryStringField="RootFolder" Name="RootFolder" Type="String"></asp:QueryStringParameter>
<asp:Parameter DefaultValue="0" Name="StartRowIndex"></asp:Parameter>
<asp:Parameter DefaultValue="0" Name="nextpagedata"></asp:Parameter>
<asp:Parameter DefaultValue="100" Name="MaximumRows"></asp:Parameter>

</SelectParameters>

<UpdateParameters>
<webpartpages:DataFormParameter ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Tasks" Name="ListName">
</webpartpages:DataFormParameter>
</UpdateParameters>

<InsertParameters>
<webpartpages:DataFormParameter ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Tasks" Name="ListName">
</webpartpages:DataFormParameter>
</InsertParameters>

<DeleteParameters>
<webpartpages:DataFormParameter ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="Tasks" Name="ListName">
</webpartpages:DataFormParameter>
</DeleteParameters>
</sharepoint:SPDataSource>


Articles:
SPDataSource for every sharepoint developer

SPDatasource every developer friend

SPDatasource fields for webs listsoflists

Rollups with the data view

http://sharepointdevwiki.com/display/public/Accessing+List+Items+using+SPDataSource+using+the+object+model

Local Activation permission for CLSID {61738644-F196-11D0-9953-00C04FD919C1}

Scenario:
I was investigating an error for my Custom Content Source crawl.I checked ( Event Log > System Node )

I found the following information :

The application-specific permission settings do not grant 'Local Activation' permission for the COM Server application with CLSID {61738644-F196-11D0-9953-00C04FD919C1}

After searching for the CLSID in Registry I found that SharePoint AppPool account needed launching privileges to the Ifilter's 'PDFThunkingSvr' DCOM object and the 'IIS WAMREG Admin service' DCOM object.

Steps:

Start > Administrative Tools > Component Services

1. Look for 'PDFThunkingSvr' DCOM and give access to the database account
2. Look for 'IIS WAMREG Admin service' and give access to the database account
3. Restart Search service ( net stop osearch )
4. After re-crawling , I dont see that DCOM error anymore

Protocol Handler Issues

Scenario:
You wrote a new Protocol Handler and configured it to be used by SharePoint Search.

Possible Errors:
1. Protocol Handler is not registered.
2. Access Denied


Possible Resolution:
1. Protocol Handler is not registered.
Make sure you have registerd the protocol handler assembly, you can verify the same by checking the Registry ( REGEDIT ) , make sure 'codebase' value is specified for the Protocol Handler binary

2. Access Denied
Protocol Handler uses two different accounts to get the information to be crawled.
-- First call to 'Init()' function is made using the Account running the deamon process( mssdmn.exe )
-- Second call to 'CreateAccessor()' function is made using the Account you have configured to access the particular Content Source

Sunday, September 7, 2008

Cross-list queries with SPSiteDataQuery

Scenario:
You need to query cross-list items across multiple Web sites

Solution:
'SPSiteDataQuery' is more efficent for such a situation.
'SPQuery' should be used to query a particular list

Sample Code:


SPWeb webSite = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();

query.Lists = "<Lists ServerTemplate=\"107\" />";
query.Query = "<Where><Eq><FieldRef Name=\"Status\"/>" +
"<Value Type=\"Text\">Completed</Value></Eq></Where>";

System.Data.DataTable items = webSite.GetSiteData(query);

foreach (System.Data.DataRow item in items)
{
Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + "<BR>");
}

Creating Custom Application Page

Scenario:
You want to write a Custom Application Page for some additional configurations for all of your sites.

Myconfig.ASPX(12/TEMPLATE/Layouts/Client/):


<%@ Assembly Name="Microsoft.SharePoint,[rest of 3-part assembly infomation]"%>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
protected override void OnLoad(EventArgs e) {
SPWeb site = this.Web;
lblSiteTitle.Text = site.Title;
lblSiteID.Text = site.ID.ToString().ToUpper();
}
</script>

<asp:Content ID="Main" runat="server" contentplaceholderid="PlaceHolderMain" >
Site Title: <asp:Label ID="lblSiteTitle" runat="server" />
<br/>
Site ID: <asp:Label ID="lblSiteID" runat="server" />
</asp:Content>

<asp:Content ID="PageTitle" runat="server" contentplaceholderid="PlaceHolderPageTitle" >
Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server" contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
'Hello World' of Application Page
</asp:Content>
Usage:
You can access to the page from any web i.e.
 http://localhost/_layouts/client/myconfig.aspx
or you can also write a CustomAction to access the URL

Extending STSADM Command set

Scenario:
You want to extend STSADM by including a new operation for enumerating all the features for a given site.

Code(GAC):


using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.StsAdmin;

namespace TrainingSamples
{
public class SimpleCommandHandler : ISPStsadmCommand
{
public string GetHelpMessage(string command)
{
return "-url <full url to a site in SharePoint>";
}

public int Run(string command, StringDictionary keyValues, out string output)
{
command = command.ToLowerInvariant();

switch (command)
{
case "enumfeatures":
return this.EnumerateFeatures(keyValues, out output);

default:
throw new InvalidOperationException();
}
}

private int EnumerateFeatures(StringDictionary keyValues, out string output)
{
if (!keyValues.ContainsKey("url"))
{
throw new InvalidOperationException("The url parameter was not specified.");
}

String url = keyValues["url"];

SPFeatureCollection features = null;
SPWeb web = null;

try
{
SPSite site = new SPSite(url);

web = site.OpenWeb();

features = web.Features;
}
catch (Exception e)
{
throw new InvalidOperationException("Error retrieving url '" + url + "'. Please check the format of your url, and ensure that the site exists. Details: " + e.Message);
}

StringBuilder sb = new StringBuilder();

sb.AppendLine("Features at '" + web.Url + "':\n");

foreach (SPFeature feature in features)
{
sb.AppendLine(feature.Definition.DisplayName + " (" + feature.DefinitionId + ")");
}

output = sb.ToString();

return 0;
}
}
}


STSADMCommands.TrainingSamples.xml(12\Config):


<?xml version="1.0" encoding="utf-8" ?>

<commands>
<command
name="enumfeatures"
class="TrainingSamples.SimpleCommandHandler, [full 4-part assembly name]"/>
</commands>



Usage:

stsadm -o enumfeatures -url http://localhost

Saturday, September 6, 2008

Creating a basic Item Event Handler

Scenario:
You want to write an event handler to cancel the deletion of an item from Announcement List ( Type = 104 )

Event Handler Code:


using Microsoft.SharePoint;

namespace TrainingSamples
{
public class DeletingAction : SPItemEventReceiver{
public override void ItemDeleting(SPItemEventProperties properties){
properties.Cancel = true;
properties.ErrorMessage = "Deleting items from " + properties.RelativeWebUrl + " is not supported.";
}
}
}
Feature.xml

<Feature Scope="Web"
Title="Deleting Event Handler"
Id="GUID"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="Elements.xml"/>
</ElementManifests>
</Feature>
Elements.xml:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListTemplateId="104">
<Receiver>
<Name>DeletingEventHandler</Name>
<Type>ItemDeleting</Type>
<SequenceNumber>10000</SequenceNumber>
<Assembly>DeletingEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a26b5449ac4a4cf3</Assembly>
<Class>DeletingEventHandler.DeletingAction</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
</Receivers>
</Elements>


Additional Notes:
This will attach event handler to any list of Type=104. So If you have specific requirements to attach event handler to a particular list only, then go for a Feature Receiver.

Test Case for a Feature receiver

Scenario:
You want to write a test case for the Feature Receiver

Sample Feature Code:

namespace TrainingSamples
{
public class SampleFeatureReceiver:SPFeatureReceiver
{

[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
if (properties == null)
{
return;
}

SPWeb web = (SPWeb)properties.Feature.Parent;
this.OnActivationCode(web);
}

public void OnActivationCode(SPWeb web)
{
//Code

}
}
}
Sample Test Case Code:
namespace TrainingSamples
{
[TestMethod()]
public void FeatureRecieverOnActivationTest()
{
SampleFeatureReceiver target = new SampleFeatureReceiver();

SPSite site;
SPWeb web;
//Bind to the site where you are testing provisioning code.

site = new SPSite("http://servername");
using (site)
{
web = site.RootWeb;
using (web)
{
target.OnActivationCode(web);
}
}

Assert.IsTrue(true,
"Feature Activation did not throw any exceptions.");
}
}
}

Provisioning Workflow programatically

Scenario:
You want to provision a Workflow programatically for a given list/document library

Steps:
01. Create an SPList object that references a list or document library that hosts the items used by the workflow.
02. Create an SPList object that references an approval task list.
03. Create an SPList object that references the Workflow History list.
04. Create an SPWorkflowTemplate object by using the workflow GUID from Workflow.xml.
05. Create an SPWorkflowAssociation object that connects the SPWorkflowTemplate object with the SPList objects for the approval task list and the Workflow History list.
06. Add an SPWorkflowAssociation object to the SPList object you created in the first step.

Code:

public void ProvisionWorkflow(SPWeb web)
{
using (web)
{
//Bind to lists.
SPList approvalsList = web.Lists["Your Approval List Name Goes Here"];
SPList approvalTasksList = web.Lists["Task List"];
SPList workflowHistoryList = web.Lists["Workflow History"];

//WorkflowGUID is the workflow GUID
//from workflow.xml\<Elements>\<Workflow>\[ID].
SPWorkflowTemplate workflowTemplate =
web.WorkflowTemplates[new Guid("WorkflowGUIDWithoutBraces")];

//Create workflow association.
SPWorkflowAssociation workflowAssociation =
SPWorkflowAssociation.CreateListAssociation(workflowTemplate,
workflowTemplate.Description, approvalTasksList,
workflowHistoryList);

//Set workflow options.
workflowAssociation.AllowManual = true;
workflowAssociation.AutoStartChange = true;
workflowAssociation.AutoStartCreate = false;

//Add workflow association.
SPWorkflowAssociation workflowAssociationInList =
approvalsList.AddWorkflowAssociation(workflowAssociation);
}
return;
}

Writing , Reading and Deleting entries from property bag

Scenario:
You want to save some keys/value information for a web.

Code:

// Add new key/value pair to the property bag.
web.Properties.Add("SomeKey", "SomeValue");
web.Properties.Update();

// Read the value of some key.
string keyValue = web.Properties["SomeKey"];

// Delete the key/value pair.
web.Properties.Remove["SomeKey"];
web.Properties.Update();

Programatically making a Web Request

Scenario:
You want to read a web-page or file programatically.

Code:

private void AccessWeb(string siteURL) {
WebRequest request = WebRequest.Create(siteURL);
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "GET";

WebResponse response = request.GetResponse();
response.Close();
}
Also you can use HTTPWebRequest object

private void GetBookReview(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();

try
{
string request = "http://xml.amazon.com/onca/xml2?" +
"t=webservices-20&dev-t=[D1LKOL21AANCMO]&"+
"AsinSearch=" + textBoxASIN.Text +
"&mode=books&type=heavy&page=1&f=xml";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(request);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

StreamReader s = new StreamReader
(resp.GetResponseStream(),Encoding.ASCII);

XmlDocument doc = new XmlDocument();
doc.LoadXml(s.ReadToEnd());

s.Close();

sb.Append("<HR><TABLE width='95%' align='center'>");

XmlNode salesRankNode = doc.SelectSingleNode("//SalesRank");
if(salesRankNode!=null)
sb.AppendFormat("<B>Sales Rank: {0}</B><BR><BR>",salesRankNode.InnerText);

XmlNodeList customerReviewNodes = doc.SelectNodes("//CustomerReview");
if(customerReviewNodes.Count>0)
{
foreach(XmlNode reviewNode in customerReviewNodes)
{
sb.AppendFormat("<B><U>Review (Rating {0}): {1}</U></B><BR>",
reviewNode.ChildNodes[0].InnerText,
reviewNode.ChildNodes[1].InnerText);
sb.AppendFormat("<I>{0}</I><BR><BR>",
reviewNode.ChildNodes[2].InnerText);
}
}

sb.Append("</DIV>");
sb.Append("</TABLE>");
}
catch(Exception ex)
{
throw new Excepion("Sorry, unable to retrieve the books!");
}
}

Writing a Timer Job

Scenario:
You want to run some code on a regular interval and decided to write a timer Job.

Sample Timer Job Code:

using System;
using System.Net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharePoint.TrainingSamples {

public class SharePointTimerJob:SPJobDefinition {

public SharePointTimerJob():base(){ }

public SharePointTimerJob(string jobName,SPWebApplication webApplication)
:base(jobName, webApplication, null, SPJobLockType.ContentDatabase) {
this.Title = "MyTimerJob";
}

public override void Execute (Guid targetInstanceId) {
foreach (SPSite siteCollection in this.WebApplication.Sites) {
// Code to be executed as a part of Timer Job
foreach (SPSite siteCollection in this.WebApplication.Sites)
{
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

// get reference to "Tasks" list in the RootWeb of
// the first site collection in the content database
SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];

// create a new task, and update item
SPListItem newTask = taskList.Items.Add();
newTask["Title"] = DateTime.Now.ToString();
newTask.Update();

}
}
}
}
}
Feature Activation Code:
Now that timer job is ready you need to add it to SharePoint Timer Jobs Store, One way is to add it as a part of Feature Activation
// get a reference to our job class in the GAC
public override void FeatureActivating (SPFeatureReceiverProperties properties) {

SPSite site = properties.Feature.Parent as SPSite;

//This is the timer class you have created above
SharePoint.TrainingSamples.SharePointTimerJob oSharePointTimerJob = new SharePoint.TrainingSamples.SharePointTimerJob("MyTimerJob", site.WebApplication);
// set the execution schedule to every 5 minute
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 5;
oSharePointTimerJob.Schedule = schedule;
//update the job
oSharePointTimerJob.Update();
}
Feature De-Activation Code:
You might want to remove it from SharePoint Timer Jobs Store on de-activation
public override void FeatureDeactivating (SPFeatureReceiverProperties properties) {
SPSite site = properties.Feature.Parent as SPSite;

// Delete the job.
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) {
if (job.Name == "MyTimerJob")
job.Delete();
}
}
Articles:
MUST READ : Issues with Timer job , OTHER Helpful links MSDN , Must Read , Andrew Connell

Retrieving list items with CAML

Scenario:
You want to retrieve all the items of list

Code:

SPQuery qry = new SPQuery();

string camlquery = "<OrderBy><FieldRef Name='Country' /></OrderBy><Where>"

+ "<Eq><FieldRef Name='LastName' /><Value Type='Text'>Sandeep</Value></Eq>"

+ </Where>";

qry.Query = camlquery;
Usage:
You can use the above 'qry' object in few different ways
SPListItemCollection listItemsCollection = list.GetItems(qry);


or

DataTable listItemsTable = list.GetItems(qry).GetDataTable();
Additonal Note: This query will return all the columns of the list, so if you are intrested in only a few of the columns then you can use

qry.ViewFields = "<FieldRef Name='FirstName' /><FieldRef Name='LastName' />";
Article:
http://sharepointmagazine.net/technical/development/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list

Friday, September 5, 2008

Creating a Custom Action

feature.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Feature Id="GUIDWithoutBraces"
Title="Site Action Menu Custom Action"
Description="This example shows how you can add new menu to WSS Site Actions"
Version="1.0.0.0"
Scope="Site"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="element.xml" />
</ElementManifests>
</Feature>
element.xml:
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
<CustomAction Id="GUIDWithoutBraces"
GroupId="SiteActions"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="1000"
Title="Configure Site"
Description="Click on this link to configure extra settings."
Rights="ViewUsageData"
ImageUrl="_layouts/images/crtsite.gif">
<UrlAction Url="~site/_layouts/Client/CustomPage.aspx"/>
</CustomAction>

<CustomAction
Id="NEWGUID"
Location="Microsoft.SharePoint.StandardMenu"
GroupId="ActionsMenu"
ControlAssembly="Training, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0000000000000000"
ControlClass="Training.NewMenuClass">
</CustomAction>
</Elements>
CodeBehind.cs:
using System; 
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Training
{
class NewMenuClass : System.Web.UI.WebControls.WebControl
{
protected override void CreateChildControls()
{
base.CreateChildControls();

ToolBarMenuButton siteActionsControl = ToolBarMenuButton.GetMenuControl(this);

switch (siteActionsControl.List.RootFolder.Name)
{
case "Shared Documents":
{
Controls.Add(CreateMenuItem("MenuTitle", "Description", 100, "_layouts/custompage.aspx", "_layouts/images/logo.gif"));
break;
}
}
}

private MenuItemTemplate CreateMenuItem(string Text, string Description, int Sequence, string OnClickUrl, string ImageUrl)
{
MenuItemTemplate menuItem = null;
menuItem = new MenuItemTemplate();
menuItem.ID = Guid.NewGuid().ToString();
menuItem.Text = Text;
menuItem.Description = Description;
menuItem.Sequence = Sequence;
menuItem.ClientOnClickNavigateUrl = OnClickUrl;
menuItem.ImageUrl = ImageUrl;

return menuItem;
}
}
}
Notes:
Possible values for the 'Location' attribute:

Microsoft.SharePoint.ContentTypeTemplateSettings
Microsoft.SharePoint.ContentTypeSettings
Microsoft.SharePoint.Administration.ApplicationCreated
Office.Server.ServiceProvider.Administration (Shared Services/SSP links)
Microsoft.SharePoint.ListEdit.DocumentLibrary
Microsoft.SharePoint.Workflows
NewFormToolbar
DisplayFormToolbar
EditFormToolbar
Microsoft.SharePoint.StandardMenu (SiteActions menu)
Mcrosoft.SharePoint.Create (_layouts/create.aspx )
Microsoft.SharePoint.ListEdit (To edit the properties of a list item)
EditControlBlock (image below)
Articles:
http://blogs.breezetraining.com.au/mickb/2007/03/27/MOSSHowToAddActionsToTheUserInterface.aspx

http://blog.sharepointalist.com/2009/03/moss-central-admin-application-pages-p1.html

Which assemblies need to be in SafeControl List

Doubt:
Why some assemblies need to be in SafeControl list , and other not.

Answer:
Assemblies using 'System.Web' namespace and 'Microsoft.SharePoint.WebControls' need to be in Safe Control list.

Deserializing XML file

Scenario:
You want to serialize the data from a class

XML:


<?xml version="1.0" encoding="utf-8"?>
<Address>
<Address1>One Microsoft Way</Address1>
<City>Redmond</City>
<State>WA</State>
<Zip>98052</Zip>
</Address>

Class:

public class Address {
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
}
Code:
Address oAddress = new Address();
XmlSerializer serializer = new XmlSerializer(typeof(Address));
FileStream file = new FileStream(@"c:\address.xml", FileMode.Open);
oAddress = serializer.Deserialize(file) as Address;

Serializing data

Scenario:
You want to serialize the data from a class

Class:

public class Address {
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
}
XML Output:
<?xml version="1.0" encoding="utf-8"?>
<Address>
<Address1>One Microsoft Way</Address1>
<City>Redmond</City>
<State>WA</State>
<Zip>98052</Zip>
</Address>
Code:
Address oAddress = new Address();
XmlSerializer serializer = new XmlSerializer(typeof(Address));
TextWriter writer = new StreamWriter(@"c:\addresses.xml");
serializer.Serialize(writer, oAddress);
writer.Close();

Site Template vs Site Definition

Site Definition Advantage:

  • Data is stored directly on the Web servers, so performance is typically better.
  • A higher level of list customization is possible through direct editing of a various XML files.
  • Certain kinds of customization to sites or lists can only be done with site definitions, such as introducing new file types, defining view styles, or modifying the drop-down Edit menu.
Site definition Disadvantages:
  • Customization of site definition requires more effort than creating custom templates. ( Not a big difference in effort if planning is proper )
  • Users cannot apply a SharePoint theme through a site definition.
  • Users cannot create two lists of the same type with different default content.
  • Customizing site definitions requires access to the file system of the front-end Web server.
Site Templates Advantages:
  • Site templates are easy to create.
  • Almost anything that can be done in the user interface can be preserved in the template.
  • Site templates can be modified without affecting existing sites that have been created from the templates.
  • Site templates are easy to deploy (Basically just a file upload).
Site Template Disadvantages:
  • Site templates are not created in a development environment.
  • They are less efficient in large-scale environments, not very easy to move them across various environments.
  • If the site definition on which the custom template is based does not exist on the front-end server or servers, the custom template will not work. The reason is that Site Template is a delta file applied on an existing Site Definition.