Create a user profile synchronisation with c# code

by Bas Hammendorp 19. August 2010 10:01

For a current project I'm working on, we need to script the user profile synchronisation connection so that we can deploy it on our different servers. To do this, you need to take a few different steps.

First you have to open the user profile manager context

// Open the central administration
SPSite centralAdminSite = SPAdministrationWebApplication.Local.Sites[0];

// Open the user profile manager context
SPServiceContext context = SPServiceContext.GetContext(centralAdminSite);
UserProfileManager userProfileManager = new UserProfileManager(context);
UserProfileConfigManager userProfileConfigManager = new UserProfileConfigManager(context);

Then set up the parmaters for the connection

string connectionName = "My Connection"; //
string systemName = "UserProfileLOBSystemInstance"; // The LobSystemInstance name
string entityName = "UserProfileEntity"; // The Entity name
string filterName = ""; // The filter ??
string entityNamespace = "UserProfiles.BdcModel1"; // Namespace of the project
string profilePropertyName = "AccountName"; // The unique SharePoint property to map the BDC to
string mappedAttribute = "ID"; // The unique BDC property

List<DSMLAttribute> dsmlAttributes = new List<DSMLAttribute>();
DSMLAttribute attr = null;

// Loop through all items from some sort of resource, E.G. an XML file
// The DSML attributes seem to be required so the connection knows these properties are available for mapping
// and that these properties can be mapped to a BDC field
foreach (var item in items)
{
   attr = new DSMLAttribute(); // create a new attribute
   attr.Indexible = bool.Parse(item.indexible);
   attr.Name = item.name; // the name of de BDC property
   attr.ID = item.id;
   attr.SingleValued = bool.Parse(item.singledValue);
   attr.Syntax = (DSMLSyntax)Enum.Parse(typeof(DSMLSyntax), item.syntax);
   dsmlAttributes.Add(attr);
}

and finally create the connection

try
{
 // Create the new user profile synchronisation connection
 userProfileConfigManager.ConnectionManager.AddBusinessDataCatalogConnection(
         connectionName, systemName, entityName, entityNamespace, profilePropertyName,
                filterName, mappedAttribute, dsmlAttributes);
}
catch (SystemException sex)
{
 // In some way, sometimes there is thrown an exception when nothing was wrong
}
catch (Exception ex)
{

}

To figure all this stuff out, I needed a lot of reflection and patience. Hope this gives you the right start to work with user profile sync connections.

Have fun!

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | SharePoint 2010

Update SharePoint workflow approvers, notification message and other properties with object model

by Bas Hammendorp 2. July 2010 06:25

When you setup a workflow in SharePoint UI, there are two screens. One with the general workflow settings and the second to adjust some specific settings like the approvers and the notification message. The first screen is not so hard to update in the object model, the second gives you more headache. You need to change the property AssociationData of the SPWorkflowAssociation which is contains an XML string with several properties, not so intuative.

To make my life a little easier, I have created a wrapper class to update these properties. Hope this helps you out!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel;

namespace myProject
{
    public class WorkflowAssociationData
    {
        #region properties
        public enum AccounTypeOption { User, SharePointGroup };
        public enum AssignmentTypeOption
        {
            [Description("Allemaal tegelijk (parallel)")]   parallel,
            [Description("Eén tegelijk (serieel)")] serial
        };

        public enum DurationUnitsOption
        {
            [Description("Dag(en)")]    day,
            [Description("We(e)k(en)")] week,
            [Description("Maand(en)")]  month
        };

        private XDocument xmlData;
        public XDocument XmlData
        {
            get { return xmlData; }
            set { xmlData = value; }
        }

        public string NotificationMessage
        {
            get { return readNodeValue("NotificationMessage"); }
            set { setNodeValue("NotificationMessage", value); }
        }

        public int DurationforSerialTasks
        {
            get { return int.Parse(readNodeValue("DurationforSerialTasks")); }
            set { setNodeValue("DurationforSerialTasks", value.ToString()); }
        }

        public DurationUnitsOption DurationUnits
        {
            get { return ((DurationUnitsOption)Enum.Parse(typeof(DurationUnitsOption), readNodeValue("DurationUnits"))); }
            set { setNodeValue("DurationUnits", value.GetDescription()); }
        }

        public bool CancelonRejection
        {
            get { return bool.Parse(readNodeValue("CancelonRejection")); }
            set { setNodeValue("CancelonRejection", value.ToString().ToLower()); }
        }

        public bool CancelonChange
        {
            get { return bool.Parse(readNodeValue("CancelonChange")); }
            set { setNodeValue("CancelonChange", value.ToString().ToLower()); }
        }

        public bool EnableContentApproval
        {
            get { return bool.Parse(readNodeValue("EnableContentApproval")); }
            set { setNodeValue("EnableContentApproval", value.ToString().ToLower()); }
        }

        public AssignmentTypeOption AssignmentType
        {
            get { return ((AssignmentTypeOption)Enum.Parse(typeof(AssignmentTypeOption), readNodeValue("AssignmentType"))); }
            set { setNodeValue("AssignmentType", value.GetDescription()); }
        }
        #endregion

        private WorkflowAssociationData() { }

        /// <summary>
        /// Create a new object with the default or existing XML
        /// </summary>
        /// <param name="xml"></param>
        public WorkflowAssociationData(string inputXml)
        {
            XmlData = XDocument.Parse(inputXml);
        }

        /// <summary>
        /// Update the approvers for this workflow
        /// </summary>
        /// <param name="displayName"></param>
        /// <param name="accountName"></param>
        /// <param name="accountType"></param>
        public void UpdateApprovers(string displayName, string accountName, AccounTypeOption accountType)
        {
            insertPersonElement("Assignee", displayName, accountName, accountType);
        }

        /// <summary>
        /// Update the CC receivers for this workflow
        /// </summary>
        /// <param name="displayName"></param>
        /// <param name="accountName"></param>
        /// <param name="accountType"></param>
        public void UpdateCc(string displayName, string accountName, AccounTypeOption accountType)
        {
            insertPersonElement("CC", displayName, accountName, accountType);
        }

        /// <summary>
        /// Attach the person element to the node <nodeName>
        /// </summary>
        /// <param name="nodeName"></param>
        /// <param name="displayName"></param>
        /// <param name="accountName"></param>
        /// <param name="accountType"></param>
        private void insertPersonElement(string nodeName, string displayName, string accountName, AccounTypeOption accountType)
        {
            XNamespace d = ""http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields">http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields";
            XNamespace pc = ""http://schemas.microsoft.com/office/infopath/2007/PartnerControls">http://schemas.microsoft.com/office/infopath/2007/PartnerControls";

            XElement dElement = XmlData.Descendants(d + nodeName).First();
            if (dElement.Descendants().Count() == 0)
            {
                XElement el = new XElement(pc + "Person",
                                    new XElement(pc + "DisplayName", displayName),
                                    new XElement(pc + "AccountId", accountName),
                                    new XElement(pc + "AccountType", accountType.ToString())
                                );
                dElement.Add(el);
            }
        }

        private string readNodeValue(string name)
        {
            XNamespace d = ""http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields">http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields";
            XElement el = XmlData.Descendants(d + name).First();
            return el.Value;
        }

        private void setNodeValue(string name, string value)
        {
            XNamespace d = ""http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields">http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields";
            XElement el = XmlData.Descendants(d + name).First();
            el.Value = value;
        }
    }

    public static class EnumMethods
    {
        /// <summary>
        /// Get the description from the enum
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
    }
}

An example to use this class:

// defaultXml is the default XML from a new SPWorkflowAssociation
WorkflowAssociationData data = new WorkflowAssociationData(defaultXml);
data.UpdateApprovers("Site Approvers Group", "Site Approvers Group", WorkflowAssociationData.AccounTypeOption.SharePointGroup);
data.NotificationMessage = "Please approve this item";
workflowAssociation.AssociationData = data.XmlData.ToString();

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | SharePoint 2010 | Workflow

Set option 'start this workflow to approve publishing a major version of an item' in c#

by Bas Hammendorp 1. July 2010 05:36

Today i was trying to figure out how to set the option 'Start this workflow to approve publishing a major version of an item' on my SharePoint list workflow. After some research I found out that the way to go is this:

  1. Cast the SPList object to an SPDocumentLibrary
  2. Attach the workflow to the document library object
  3. Set the DefaultContentApprovalWorkflowId
  4. Update the list

The code will be something like this:

// list is an SPList object, workflowAssociation is an SPWorkflowAssociation object
SPDocumentLibrary docLib = (SPDocumentLibrary)list; // cast
docLib.WorkflowAssociations.Add(workflowAssociation); // attach
docLib.DefaultContentApprovalWorkflowId = workflowAssociation.Id; // set property
list.Update(); // save the list

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | SharePoint 2010 | Workflow

Upload a file in central admin document library

by Bas Hammendorp 16. May 2010 09:15

I was making a simple console application to upload a zip file (with a WSP Listener solution) in the document library. This document library was located in the central admin, so I also wanted to find the central admin web application dynamic. I came up with the next solution:

// Set the path to the zip file and the name of the document library
string path = "c:\temp\testfile.zip";
string documentLibraryName = "WSPListener document library";

// Get the central administration web application and the upload folder
SPWeb centralAdminWeb = SPAdministrationWebApplication.Local.Sites[0].OpenWeb();
SPFolder uploadFolder = centralAdminWeb.Folders[documentLibraryName];
bool replaceExistingFiles = true;

SPFolder myLibrary = centralAdminWeb.Folders[documentLibraryName];

// Open a file stream to add the file in the document library
using (FileStream fileStream = File.OpenRead(path))
{
   SPFile spFile = myLibrary.Files.Add(fi.Name, fileStream, replaceExistingFiles);
   myLibrary.Update(); // save the file

   // Get the corresponding SPItem to update some properties and start the installation
   SPListItem item = spFile.Item;
   item["InstallationStartTime"] = null;
   item["InstallationEndTime"] = null;
   item["InstallationStatus"] = "Install";
   item["InstallationResult"] = "";
   item.Update();
}

As you can see, it's very easy :)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | Sharepoint

Save a file to disk from a document library

by Bas Hammendorp 13. March 2010 07:17

In my new update for the WSP Listener I need to save a file from a document library to disk. This can be done by the following code:

// item is an SPListItem
SPFile myFile = item.File;
DestinationFile = Path.Combine(@"c:\temp", myFile.Name);
if (File.Exists(DestinationFile))
{
   // Remove the old file
   File.Delete(DestinationFile);
}

// Open the binary data
byte[] data = myFile.OpenBinary();
using (FileStream stream = new FileStream(DestinationFile, FileMode.CreateNew))
{
   // Save the file
   BinaryWriter writer = new BinaryWriter(stream);
   writer.Write(data, 0, (int)myFile.Length);
   writer.Close();
   stream.Close();
}

Have fun!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C# | Sharepoint

Update the title of the welcome page in sharepoint and c#

by Bas Hammendorp 31. August 2009 05:23

I was looking for a way to update the page title of my welcome page in c# and I got to the following example:

SPWeb web = SPContext.Current.Site.OpenWeb();
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(childWeb);
SPFile defaultPage = pubWeb.DefaultPage;

defaultPage.CheckOut();
defaultPage.Update();

defaultPage.Item["Title"] = "My title";
defaultPage.Item.Update();

defaultPage.CheckIn("My comment");
defaultPage.Update();

Have fun!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | Sharepoint

Compare two datetime values the right way

by Bas Hammendorp 23. June 2009 03:44

I always forget the outcome of the DateTime.Compare method; Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. Just a reminder to myself ;) The result of the next piece of code:

int result = DateTime.Compare(date1, date2)

result is less than zero : date1 is earlier than date2. 
 
result is zero : date1 is the same as date2.
 
result is greater than zero : date1 is later than date2.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Copy datatable row to another datatable

by Bas Hammendorp 23. June 2009 03:36

Sometimes you need to copy one or more rows from a source datatable to another datatable. The importrow method can do this for you. It copies a DataRow into a DataTable, preserving any property settings, as well as original and current values. An important condition is that the destination datatable must be the same as the source datatable:

// copy the table definition from source to destination table
DataTable destinationTable = sourceTable.Clone();

In the destination table, you can now import rows:

foreach (DataRow dr in sourceTable)
{
   destinationTable.ImportRow(dr);
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Default method to execute stored procedures

by Bas Hammendorp 16. June 2009 07:11

I was creating the same method over and over again to execute different stored procedures. Now I have created one general method which you can use for all stored procedures (with no result set). Off course it can be extended with, for example, the return of a datatable:

public void ExecuteStoredProcedure(string name, string[] parameters, object[] values)
{
    using (SqlConnection connection = new SqlConnection(ConnectionString))
   {
      connection.Open();

      try
      {
         SqlCommand command = new SqlCommand(name, connection);
         command.CommandType = CommandType.StoredProcedure;

         for (int i = 0; i < parameters.Length; i++)
         {
            command.Parameters.Add(new SqlParameter(parameters[i], values[i]));
         }
                   
         command.ExecuteNonQuery();
      }
      catch (Exception ex)
      {

      }
      finally
      {
         connection.Close();
       }
   }
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | SQL

SQL bulk insert

by Bas Hammendorp 9. June 2009 08:27

If you want to insert a complete DataTable at once, you can use SqlBulkCopy:

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
   using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
   {
      bulkCopy.DestinationTableName = "myNewTable";
      bulkCopy.WriteToServer(dt);
   }
}

It's easy as that!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C# | SQL

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

My name is Bas Hammendorp, I work as an Enterprise Engineer at PGGM. My specialties are ASP.NET, C#, SQL and Sharepoint 2007.

Google ads