Archive for code

SharePoint / MOSS: Creating Site Programmatically

I was interested in creating MOSS 2007 site using code. I end up with the following code:

 

SPSite oSiteCollection = new SPSite(“http://servername/SiteDirectory”);            

SPWeb oWebSite = oSiteCollection.OpenWeb();

SPWebCollection oSitesCollection = oWebSite.Webs;

SPWeb newWebSite = oSitesCollection.Add(“abc”, “Document Library                 Template”, “This is site created through code.”, 1033, “STS#2″, true, false);

 

We will only explore SPWebCollection Add Method. The Add method has following parameters:

 

strWebUrl:

 

A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite, specify Website/MyNewWebsite.

 

strTitle

 

A string that contains the title.

 

strDescription

 

A string that contains the description.

 

nLCID

 

An unsigned 32-bit integer that specifies the locale ID. You can find a complete list of local ID at the following URL:

 

http://www.microsoft.com/globaldev/reference/lcid-all.mspx

 

We have used “1033” for English – United States.

 

strWebTemplate

 

A string that contains the name of the site definition configuration or site template. The following table shows the values for the default site definition configurations that are included in an installation of Windows SharePoint Services

 

Value

Site Definition

STS#0

Team Site

STS#1

Blank Site

STS#2

Document Workspace

MPS#0

Basic Meeting Workspace

MPS#1

Blank Meeting Workspace

MPS#2

Decision Meeting Workspace

MPS#3

Social Meeting Workspace

MPS#4

Multipage Meeting Workspace

WIKI#0

Wiki

BLOG#0

Blog

 

For more MOSS/WSS SiteTemplate codes, visit the following URLs:

 

http://mystepstones.wordpress.com/2008/02/14/sitetemplate-codes/

 

http://stevenjohnevans.co.uk/blogs/dotnet/archive/2007/11/25/standard-site-definitions-within-sharepoint-2007-moss.aspx

 

useUniquePermissions

 

true to create a subsite that does not inherit permissions from another site; otherwise, false.

 

bConvertIfThere

 

true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.

   

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spwebcollection.aspx

Comments

MOSS: Add user to site through code (programmatically)

We can add users to a SharePoint site using object model.  

 

One possible way: 

 

SPRoleAssignment MyRoleAssign = new SPRoleAssignment(”domain/alias”, “email address”, “User Name”, “Description”);

 

SPRoleDefinition MyRoleDef = newSubWeb.RoleDefinitions["Contribute"];

MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef);

site.RoleAssignments.Add(MyRoleAssign);

 

Second is:

 

SPGroup AddUserGroup = site.Groups["Group name"];

AddUserGroup.AddUser(”domain/alias”, “email address”, “User Name”, “Description”);

 

To add bulk of users in one go, following code is preferred:

 

SPUserInfo[] AddUsers = new SPUserInfo[1];

 

AddUsers[0].Email = “email address”;

AddUsers[0].LoginName = “domain\login”;

AddUsers[0].Name = “name”;

AddUsers[0].Notes = “notes”;

 

site.Roles["Contributor"].Users.AddCollection(AddUsers);

Comments (17)

Event Handler to Synchronize (Populate Data) List / Document Library Columns Form Other Document Library / List Columns

We have created a solution for one of our clients. The solution is based on uploading documents and attaching workflows with the documents.

Uploaded documents have different columns describing the document’s meta data. Our clients’ wants that these column in the task list.

We decide to write two event handlers. One was against the list and other was against the document library.

The event handler against list runs when a task is created in the task list. It fetches the information from the desired columns in the document library and populates the columns in the task list row.

The code is:

 public class MyClass : SPItemEventReceiver    {       

public override void ItemAdded(SPItemEventProperties properties)        {           

SPListItem item = properties.ListItem;                       

SPFieldUrlValue MyURL = null;           

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;            

string URLText = null;           

string URL = null;                        

SPWeb site = (SPWeb)properties.OpenWeb();           

SPList DocLib = site.Lists["Document Library Name"];                

MyURL = new SPFieldUrlValue((string)item["Link"]);           

URL = MyURL.Url; URLText = URL.Substring(URL.LastIndexOf(‘/’) + 1);         

DefaultView = DocLib.DefaultView;            

SelectQuery = new SPQuery(DefaultView);            

SelectQuery.Query = “<Where><Eq><FieldRef Name=’FileLeafRef’/><Value Type=’Text’>” + URLText + “</Value></Eq></Where>”           

SelectedDoc = DocLib.GetItems(SelectQuery);  

foreach (SPListItem doc in SelectedDoc) // run for once            {                  

item["Col 1"] = doc["Col 1"];                 

item["Col 2"] = doc["Col 2"];                 

item["Col 3"] = doc["Col 3"];                 

item.Update();           

}              

site.Dispose();                     

}

}

The second event handler was written against the document library for synchronization purpose. If user changes / update the data in the document library column, these changes must be reflected in the task list column. The event handler capture and runs against the update vent.

The code is:

 public class MYClass1 : SPItemEventReceiver    {       

public override void ItemUpdated(SPItemEventProperties properties)        {            

string DocName = null;           

string DocTitle = null;            

SPView DefaultView = null;           

SPQuery SelectQuery = null;           

SPListItemCollection SelectedDoc = null;                       

SPListItem doc = properties.ListItem;           

SPWeb site = properties.OpenWeb();           

SPList TaskList = site.Lists["Task List Name"];            

DocName = doc["Name"].ToString();                       

DocTitle = DocName.Substring(0,DocName.LastIndexOf(‘.’));            

DefaultView = TaskList.DefaultView;            

SelectQuery = new SPQuery(DefaultView);             

SelectQuery.Query = “<Where><Eq><FieldRef Name=’LinkTitle’/><Value Type=’Text’>Please approve “ + DocTitle + “</Value></Eq></Where>”           

SelectedDoc = TaskList.GetItems(SelectQuery);            

foreach (SPListItem task in SelectedDoc)             {               

task["Col 1"] = doc["Col 1"];               

task["Col 2"] = doc["Col 2"];               

task["Col 3"] = doc["Col 3"];               

task.Update();           

}           

site.Dispose();       

}

}

In this way, changes in the columns of document library will be immediately visible in the columns of task list as well.  

In case you don’t know how to create and deploy event handler, follow this link.

Comments (1)

Populate / Set or Get Data / Value from / to Hyperlink Column

Data in the Hyperlink Column can be populated / set in the following manners: 

Item[“HyperLinkColumnName”] = “http://www.google.com, Google”;

Item.Update(); 

Don’t forget space after comma. 

Or 

SPFieldUrlValue MyURL = new SPFieldUrlValue();

MyURL.Description = “Google”;

MyURL.Url = http://www.google.com;

Item[“HyperLinkColumnName”] = MyURL;  

 

Data from the Hyperlink Column can be get in the following manner: 

SPFieldUrlValue MyURL = new SPFieldUrlValue(Item[“HyperLinkColumnName”].ToString()); 

string URLText = MyURL.Description;

string URL = MyURL.Url; 

Comments (2)

Upload file in MOSS / SharePoint using code

It is easy and simple to upload a file in the document library of MOSS / SharePoint. The code for upload the file in C# is as under: 

SPSite sp = new SPSite(“URL of the site collection”);     

SPWeb site = sp.OpenWeb();      

SPFolder folder = site.GetFolder(“Document Library Name”);     

SPFileCollection files = folder.Files; FileStream fStream = File.OpenRead(“C:\\upload.doc”); //path of the file to upload     

byte[] contents = new byte[fStream.Length];     

fStream.Read(contents, 0, (int)fStream.Length);     

fStream.Close();      

Hashtable MetaDataTable = new Hashtable();     

MetaDataTable.Add(“Comments”, “Hello World”);      

SPFile currentFile = files.Add(“URL of the document library/upload.doc”, contents, MetaDataTable, true); 

You can addd the meta data as well by using Hash Table. We have populated the “Comments” column with “Hello World”. 

With or without using the following code

 SPListItem doc = currentFile.Item;  

We can do a lot of things with the uploaded file.

For more information, visit the Microsoft link. It provides more information about the error checking and other.

Comments (14)

In line code to upload (supportive) documents

 Recently we face a requirement from our client that one or more documents should be added against the documents already uploaded in the document library. We created a look up column (on the bases of “Title” field) and asked him to add as many documents as he wanted but he refused the solution giving two arguments. 

1-    Doesn’t have the time to go to the propertied page of each document and attach documents from there.

2-    Don’t want to fellow the process (first step was to upload the supportive document, write the name of the document in the title field and then, using properties of the target document, attach it using the look up column). 

So we have to device another solution and we decided to go in line code. For this, we added a hyperlink column and a look up column. The name of the look up column is “DocAttached”. We selected “Title” as a criteria and option for multiple values is checked. The name of the hyperlink column is “AttachDoc”. The value of the “AttachDoc” is populated by upload event handler. The code of the event handler is below: 

public override void ItemAdded(SPItemEventProperties properties)       

{           

if (properties.ListItemId.Equals(null)){   

SPListItem doc = properties.ListItem;   

doc["AttachDoc"] = “URL of the site/Upload_file.aspx?para=” + doc["ID"] + “, Attach File”;                doc.Update();           

}                   

} 

Above code concatenate the document ID with the URL of the page “Uploaded_file,aspx” that we have added using SharePoint Designer. Each time a document is uploaded, the value of the column “AttachDoc” is populated with a URL which has a concatenated value of the document ID. When the users click on the “Attach File” link provided in the “AttachDoc” column, the control passes to the page “Upload_file.aspx”.

The HTML and in line code for the page “Upload_file.aspx” is as under:   

<%@ Page Language=”C#” masterpagefile=”~masterurl/default.master” title=”|” inherits=”Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” meta:progid=”SharePoint.WebPartPage.Document” %>

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

<asp:Content id=”Content1″ runat=”server” contentplaceholderid=”PlaceHolderMain”>

<head>

<META name=”WebPartPageExpansion” content=”full”>

<script runat=”server”>

SPSite sp;

            SPWeb WebSite;

            SPList DocLib;

int id = 0;

   

            string AddURL = “”;

string DocName = “”;

string DocTitle = “”;  

           

public void Page_Load(object o, EventArgs e)

{

           

            sp = new SPSite(”URL”);

            WebSite = sp.OpenWeb();

            DocLib = WebSite.Lists["Document Library Name"];

           

            if (string.IsNullOrEmpty(Request.QueryString["para"]))

       {

       Response.Redirect(”http://URL/Upload_error.aspx”);

       }

           

            id = Convert.ToInt32(Request.QueryString["para"]);

}

           

   

public void UploadFile(object o, EventArgs e)

{

             if (FileUpload1.HasFile)

        {

            AttachDocument(FileUpload1);           

        }

        if (FileUpload2.HasFile)

        {

            AttachDocument(FileUpload2);

        }

        if (FileUpload3.HasFile)

        {

            AttachDocument(FileUpload3);

        }

        if (FileUpload4.HasFile)

        {

            AttachDocument(FileUpload4);

        }

        if (FileUpload5.HasFile)

        {

            AttachDocument(FileUpload5);

        }       

                       

WebSite.Close();

sp.Close();

WebSite.Dispose();

sp.Dispose(); 

      

        Response.Redirect(”Document Library URL”);

}

public void AttachDocument(FileUpload file)

{

        byte[] content = new byte[file.PostedFile.ContentLength];

        string URL = “URL of the document library/” + file.FileName;

        content = file.FileBytes;

        SPFolder DocLibFolder = WebSite.GetFolder(”DLOne”);

        SPFileCollection DocLists = DocLibFolder.Files;

        sp.AllowUnsafeUpdates = true;

        WebSite.AllowUnsafeUpdates = true;

        SPFile FileAdded = DocLists.Add(URL, content);

        SPListItem DocAdded = FileAdded.Item;

        DocName = DocAdded.Name;

        DocTitle = DocName.Substring(0, DocName.IndexOf(’.'));

        DocAdded["Title"] = DocTitle;

        DocAdded.Update();

        AddURL = “;#” + DocAdded.ID + “;#” + DocTitle;

        SPView DefaultView = DocLib.DefaultView;

        SPQuery SelectQuery = new SPQuery(DefaultView);

        SelectQuery.Query = “<Where><Eq><FieldRef Name=’ID’/><Value Type=’Numeric’>” + id + “</Value></Eq></Where>”;

        SPListItemCollection SelectedDoc = DocLib.GetItems(SelectQuery);

        SPListItem doc = SelectedDoc.GetItemById(id);

        doc["DocAttached"] += AddURL;       // “;#158;#sv002″;

        doc.Update();           

}

public void button_Cancel(object o, EventArgs e)

{

  Response.Redirect(”URL of the Document Library”);

}

</script>

</head>

<body>

<div>

        <table>

            <tr>

                <td><asp:FileUpload ID=”FileUpload1″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload2″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload3″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload4″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                <td><asp:FileUpload ID=”FileUpload5″ runat=”server”/></td>

                <td> </td>

                <td> </td>

            </tr>

            <tr>

                        <td>             </td>

            </tr>

            <tr>

             <td><asp:Button ID=”Button2″ runat=”server” Text=”Upload” OnClick=”UploadFile”/>

                <asp:Button ID=”Button1″ runat=”server” Text=”Cancel” OnClick=”button_Cancel”/></td>

                <td>                   

                </td>

            </tr>

        </table>   

    </div> 

</body>                                              

</asp:Content>

 

The screen shoot of the “Upload_file.aspx” is as under: 

 

5-1.jpg

Comments (2)