Posts Tagged code

SharePoint: Associate Workflow with a list programmatically

Scenario:

We need to associate a workflow with a list or create an instance of workflow for a list using SharePoint Object Model (OM)

Resolution:

In order to associate workflow with a list, we will be using CreateListAssociation method of SPWorkflowAssociaition class. We need following four values:

  • baseTemplate – The workflow template on which to base this workflow association.
  • Name – The name to give this workflow association.
  • taskList – The task list on which to create workflow tasks for this workflow association.
  • historyList – The list to which to log workflow history events

Code is as under:

using(SPSite spSite = new SPSite(“SiteURL”))

{

SPWeb spWeb = spSite.OpenWeb();

SPList assocList = spWeb.Lists[“NameOfTheList”];

SPWorkflowTemplate wflTemplate = spWeb.WorkflowTemplates.GetTemplateByName(“NameOfWorkflowTemplate”, System.Globalization.CultureInfo.CurrentCulture);

SPList wflTaskList = spWeb.Lists[“Tasks”];

SPList wflHistoryList = spWeb.Lists[“Workflow History”];

SPWorkflowAssociation wflAss = SPWorkflowAssociation.CreateListAssociation(wflTemplate, “NameOfTheWorkflow”, wflTaskList, wflHistoryList);

wflAss.AutoStartChange = false;

wflAss.AutoStartCreate = false;

wflAss.AllowManual = true;

spWeb.AllowUnsafeUpdates = true;

assocList.AddWorkflowAssociation(wflAss);

assocList.Update();

spWeb.AllowUnsafeUpdates = false;

}

Advertisements

Comments (1)

SharePoint 2010: Display titles instead of URL’s in WhatsPopularWebPart

Scenario:

We need to display / render titles instead of the URL’s in “WhatsPopularWebPart”.

Resolution:

Google the problem and found following blog with an excellent idea how to accomplish above:

http://rolandoldengarm.wordpress.com/2011/04/08/whatspopularwebpart-render-titles-instead-of-urls/

As per “Roland Oldengarm” already stated that we “to created a webpart derived from WhatsPopularWebPart and implemented also ICallbackEventHandler”. Started working on it and found some implementation issues. First, we need to change the Regex and second, we need to change the code.


public class TestWebPart :

Microsoft.Office.Server.WebAnalytics.Reporting.WhatsPopularWebPart, ICallbackEventHandler

{

private const string ItemRegEx = @”<span dir=’ltr’>(?<url>[^<]*)</span>”;

private static string ReplaceUrlsWithTitles(string html)

{

if (Regex.IsMatch(html, ItemRegEx))

{

html = Regex.Replace(html, ItemRegEx, delegate(Match match)

{

var url = match.Groups[“url”].Value;

string title = url;

using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))

{

using (SPWeb spWeb = spSite.OpenWeb(title))

{

try

{

var item = spWeb.GetListItem(title);

if (item != null)

{

title = item.Title;

}

}

catch (Exception e) { }

}

}

return
“<span>” + title + “</span>”;

},RegexOptions.IgnoreCase);

}

return html;

}

string ICallbackEventHandler.GetCallbackResult()

{

return ReplaceUrlsWithTitles(base.GetCallbackResult());

}

void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)

{

base.RaiseCallbackEvent(eventArgument);

}

}

Comments (33)

MOSS 2007: Changing landing page (default.aspx)

We need to change the landing page of site from default.aspx to one of our customized page. We used the following code:

 

static void Main(string[] args)

        {

            SPSite oSiteCollection = null;

            SPWeb oWibSite = null;

            SPFolder oFolder = null;

 

            try

            {

                oSiteCollection = new SPSite(http://site URL”);

                oWibSite = oSiteCollection.OpenWeb();

                oFolder = oWibSite.RootFolder;

                oFolder.WelcomePage = “document library/page name”;

                oFolder.Update();                         

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

                Console.WriteLine(e.StackTrace);

            }

            finally

            {

                oWibSite.Dispose();

                oSiteCollection.Dispose();

            }           

        }

 

Source: MSDN – forgot URL L

Leave a Comment

MOSS 2007: Event Viewer Error Code 6482 and 6398

Recently we encountered a problem in the Event Viewer of MOSS server machine. The event viewer is getting populated after approximately every 40 second with the Error Code 6482 and 6398. Details of the error are as under:-

 

Event ID:   6482

 

Event Type:        Error

Event Source:     Office SharePoint Server

Event Category:  Office Server Shared Services

Event ID:   6482

Date:        6/24/2008

Time:                10:12:41 AM

User:         N/A

Computer:  ABC

 

Description:

Application Server Administration job failed for service instance Microsoft.Office.Server.Search.Administration.SearchAdminSharedWebServiceInstance (f0fc6cd7-fd20-49e3-8965-218a64ed4fbc).

 

Reason: An error occurred loading a configuration file: Access to the path ‘C:\Program Files\Microsoft Office Servers\12.0\WebServices\Root\ibgueyl_.tmp’ is denied. (C:\Program Files\Microsoft Office Servers\12.0\WebServices\Root\web.config)

 

Techinal Support Details:

System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Access to the path ‘C:\Program Files\Microsoft Office Servers\12.0\WebServices\Root\ibgueyl_.tmp’ is denied. (C:\Program Files\Microsoft Office Servers\12.0\WebServices\Root\web.config) —> System.UnauthorizedAccessException: Access to the path ‘C:\Program Files\Microsoft Office Servers\12.0\WebServices\Root\ibgueyl_.tmp’ is denied.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)

   at System.CodeDom.Compiler.TempFileCollection.EnsureTempNameCreated()

   at System.CodeDom.Compiler.TempFileCollection.AddExtension(String fileExtension, Boolean keepFile)

   at System.CodeDom.Compiler.TempFileCollection.AddExtension(String fileExtension)

   at System.Configuration.Internal.WriteFileContext..ctor(String filename, String templateFilename)

   at System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForWrite(String streamName, String templateStreamName, Object& writeContext, Boolean assertPermissions)

   at System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForWrite(String streamName, String templateStreamName, Object& writeContext, Boolean assertPermissions)

   at System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForWrite(String streamName, String templateStreamName, Object& writeContext)

   at System.Configuration.Internal.DelegatingConfigHost.OpenStreamForWrite(String streamName, String templateStreamName, Object& writeContext)

   at System.Configuration.UpdateConfigHost.OpenStreamForWrite(String streamName, String templateStreamName, Object& writeContext)

   at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)

   — End of inner exception stack trace —

   at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)

   at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)

   at System.Configuration.Configuration.Save()

   at Microsoft.Office.Server.Administration.SharedWebServiceInstance.ProvisionSharedResourceProviderWebConfigSettings(SharedResourceProvider srp)

   at Microsoft.Office.Server.Administration.SharedWebServiceInstance.Synchronize()

   at Microsoft.Office.Server.Administration.ApplicationServerJob.ProvisionLocalSharedServiceInstances(Boolean isAdministrationServiceJob)

 

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

 

 

Event ID:   6398

 

Event Type:        Error

Event Source:     Windows SharePoint Services 3

Event Category:  Timer

Event ID:   6398

Date:        6/27/2008

Time:                3:07:38 PM

User:         N/A

Computer:  ABC

Description:

The Execute method of job definition Microsoft.SharePoint.Administration.SPUpgradeJobDefinition (ID 2d9efa9c-d2e8-4be4-9312-b8ff74b93247) threw an exception. More information is included below.

 

Requested registry access is not allowed.

 

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

 

Resolution:

 

After a lot of net search, the final solution was of installing Office SharePoint Server 2007 Service Pack 1 available at the URL (http://technet.microsoft.com/en-us/office/sharepointserver/bb735839.aspx).

 

But for this solution work, you should have a server with version older than 12.0.0.6219.

You can check the version number by running SharePoint Central Administration and moving to Operation to “Servers in Farm”.

 

Hope that this solution works for you as well. J

 

Comments (3)

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&#8221;);            

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 (6)

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 (57)

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 (8)

Older Posts »