Synchronizing SharePoint Lists Between Internal and External Sites

I have created a sample program to synchronize SharePoint lists between two sites. There are many ways to accomplish this task:

1. SharePoint List Event Handler (ItemAdded, ItemUpdated, ItemDeleted etc.)

2. Custom WorkFlow to copy list items when modified

3. Windows Form to Push Data Manually

4. Windows Service to schedule the move on scheduled times

Here is the sample for the 3rd Approach [Windows Form to Push Data Manually]:

In this approach. Create a C# Class Library Project and Add a reference to Microsoft.SharePoint.DLL from 12 Hive. Create 2 XML Files [Feature.XML, Elements.XML] to intall the feature.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Xml;

using System.Net;

namespace AMIMoverByWebService

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void btnSync_Click(object sender, EventArgs e)

{

syncLists();

}

private void syncLists()

{

try

{

using (SourceList.Lists sourceListService=new AMIMoverByWebService.SourceList.Lists())

{

using(DestList.Lists destListService = new DestList.Lists())

{

// SharePoint Web Serices require authentication

NetworkCredential mySourceCred= new NetworkCredential("kito", "sunny", "MyDomain");

NetworkCredential myDestCred = new NetworkCredential("kito", "sunny", "MyDomain");

sourceListService.PreAuthenticate = false;

sourceListService.Credentials = mySourceCred;

//Incase you want to use default credentials

//sourceListService.Credentials = System.Net.CredentialCache.DefaultCredentials;

destListService.PreAuthenticate = false;

destListService.Credentials = myDestCred;

//Incase you want to use default credentials

//destListService.Credentials = System.Net.CredentialCache.DefaultCredentials;

String sourceList = txtSourceListGUID.Text;

String destList = txtDestListGUID.Text;

System.Xml.XmlNode ndSourceListView = sourceListService.GetListAndView("Schedule", "{D5114EBE-C217-4BBD-9951-6F33332D8269}");

string sourceListGUID = ndSourceListView.ChildNodes[0].Attributes["Name"].Value;

string sourceViewGUID = ndSourceListView.ChildNodes[1].Attributes["Name"].Value;

// first check if item is already in the list

XmlNode sourceItemData = sourceListService.GetListItems(sourceListGUID, sourceViewGUID, null, null, "5000", null, "");

using (XmlNodeReader reader = new XmlNodeReader(sourceItemData))

{

using (DataSet _ds = new DataSet())

{

_ds.ReadXml(reader);

using (DataTable _dt = _ds.Tables[1])

{

for (int i = 0; i < _dt.Rows.Count; i++)

{

DataRow _dr = _dt.Rows[i];

this.statusStrip1.Text = "Synchronizing " + _dr["ows_Sub Station Name"].ToString();

//xmldocument to create necessary nodes for getalllistitems method..

XmlDocument xdoc = new XmlDocument();

XmlNode queryNode = xdoc.CreateNode(XmlNodeType.Element, "Query", "");

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.Append(" <Where>");

stringBuilder.Append(" <Eq>");

stringBuilder.Append(" <FieldRef Name=\"Sub_x0020_Number\" />");

stringBuilder.Append(" <Value Type=\"Text\">" + _dr["ows_Sub Number"].ToString() + "</Value>");

stringBuilder.Append(" </Eq>");

stringBuilder.Append(" </Where>");

string strQuery = stringBuilder.ToString();

queryNode.InnerXml = strQuery;

XmlNode viewNode = xdoc.CreateNode(XmlNodeType.Element, "ViewFields", "");

string strViewFields = "<FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" /><FieldRef Name=\"Sub_x0020_Number\" />";

viewNode.InnerXml = strViewFields;

XmlNode nodeQueryOption = xdoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

nodeQueryOption.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>";

string rowlimit = "5000";

string webid = "";

System.Xml.XmlNode ndDestListView = destListService.GetListAndView("Schedule", "{6378E656-772B-4C33-B49B-AF8471466613}");

string destListGUID = ndDestListView.ChildNodes[0].Attributes["Name"].Value;

string destViewGUID = ndDestListView.ChildNodes[1].Attributes["Name"].Value;

XmlNode destItemData = destListService.GetListItems(destListGUID, destViewGUID, queryNode, viewNode, rowlimit, nodeQueryOption, webid);

using (XmlNodeReader reader1 = new XmlNodeReader(destItemData))

{

using (DataSet _ds1 = new DataSet())

{

_ds1.ReadXml(reader1);

//DataTable _dt1 = _ds1.Tables[1];

if (_ds1.Tables.Count == 1)

{

/*Create an XmlDocument object and construct a Batch element and its attributes. Note that an empty ViewName parameter causes the method to use the default view. */

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

System.Xml.XmlElement batchElement = doc.CreateElement("Batch");

batchElement.SetAttribute("OnError", "Continue");

batchElement.SetAttribute("ListVersion", "1");

batchElement.SetAttribute("ViewName", destViewGUID);

/*Specify methods for the batch post using CAML. To update or delete, specify the ID of the item, and to update or add, specify

the value to place in the specified columns.*/

StringBuilder stringBuilder1 = new StringBuilder();

stringBuilder1.Append("<Method ID='1' Cmd='Update'>");

stringBuilder1.Append("</Method>");

stringBuilder1.Append("<Method ID='2' Cmd='New'>");

stringBuilder1.Append("<Field Name='Title'>" + _dr["ows_Title"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Sub_x0020_Number'>" + _dr["ows_Sub Number"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Sub_x0020_Station_x0020_Name'>" + _dr["ows_Sub Station Name"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Prime_x0020_Contractor'>" + _dr["ows_Prime Contractor"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Design_x0020_Contractor'>" + _dr["ows_Design Contractor"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Contractor'>" + _dr["ows_Construction Contractor"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='RF_x0020_Implementation_x0020_Pl'>" + _dr["ows_RF Implementation Pl"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Date_x0020_for_x0020_issue_x0020'>" + _dr["ows_Date for issue_x0020"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='FAI_x0020_PO_x0020_Receipt_x0020'>" + _dr["ows_FAI PO Receipt_x00200"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Start_x0020_date_x0020_for_x0020'>" + _dr["ows_Start date for_x0020"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='L_x0026_G_x0020_Equipment_x0020_'>" + _dr["ows_L&G Equipment "].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='L_x0026_G_x0020_Equipment_x0020_0'>" + _dr["ows_L&G Equipment 0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='L_x0026_G_x0020_Equipment_x0020_1'>" + _dr["ows_L&G Equipment 1"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='L_x0026_G_x0020_Equipment_x0020_2'>" + _dr["ows_L&G Equipment 2"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='All_x0020_FAI_x0020_Equipment_x0'>" + _dr["ows_All FAI Equipment_x0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='All_x0020_FAI_x0020_Equipment_x00'>" + _dr["ows_All FAI Equipment_x00"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Site_x0020_Visit_x0020__x002d__x'>" + _dr["ows_Site Visit -_x"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Site_x0020_Visit_x0020__x002d__x0'>" + _dr["ows_Site Visit -_x0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='End_x0020_date_x0020_for_x0020_l'>" + _dr["ows_End date for l"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Land_x0020_Agreement_x0020_Requi'>" + _dr["ows_Land Agreement Requi"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Design_x0020_Brief_x0020_Submitt'>" + _dr["ows_Design Brief Submitt"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Partial_x0020_Construction_x0020'>" + _dr["ows_Partial Construction_x0020"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='DB_x0020_Sub_x0020_by_x0020_Fort'>" + _dr["ows_DB Sub by Fort"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Design_x0020_Brief_x0020_Approve'>" + _dr["ows_Design Brief Approve"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Design_x0020_Brief_x0020_Approve0'>" + _dr["ows_Design Brief Approve0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Start_x0020_Data_x0020_GS_x0020_'>" + _dr["ows_Start Data GS "].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Grounding_x0020_Study_x0020_Subm'>" + _dr["ows_Grounding Study Subm"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Grounding_x0020_Study_x0020_Subm0'>" + _dr["ows_Grounding Study Subm0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Gounding_x0020_Study_x0020_Appro'>" + _dr["ows_Gounding Study Appro"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Grounding_x0020_Study_x0020_Appr'>" + _dr["ows_Grounding Study Appr"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Design_x0020_IFCR_x0020_Submitte'>" + _dr["ows_Design IFCR Submitte"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Deadline_x0020_for_x0020_Commiss'>" + _dr["ows_Deadline for Commiss"].ToString().Replace("datetime;#", "") + "</Field>");

//stringBuilder1.Append("<Field Name='Detail_x0020_Design_x0020_IFCR_x'>" + _dr["ows_Detail Design IFCR_x"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Detail_x0020_Design_x0020_IFC_x0'>" + _dr["ows_Detail Design IFC_x0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Detail_x0020_Design_x0020_IFCR_x0'>" + _dr["ows_Detail Design IFCR_x0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Authorization'>" + _dr["ows_Construction Authorization"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Authorization0'>" + _dr["ows_Construction Authorization0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Authorization1'>" + _dr["ows_Construction Authorization1"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Authorization2'>" + _dr["ows_Construction Authorization2"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Hot_x0020_Connection_x0020_Ties_'>" + _dr["ows_Hot Connection Ties_"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Sched_x0020_Insp_x0020_by_x0020_'>" + _dr["ows_Sched Insp by "].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Comms_x0020_Upgrade_x0020_to_x00'>" + _dr[41].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Const_x0020_Start_x0020_Date_x00'>" + _dr["ows_Const Start Date_x00"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Complete_x002'>" + _dr["ows_Construction Complete_x002"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Complete_x0020'>" + _dr["ows_Construction Complete_x0020"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Construction_x0020_Complete_x0021'>" + _dr["ows_Construction Complete_x0021"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Commissioning_x0020_by_x0020_L_x'>" + _dr["ows_Commissioning by L_x"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Commissioning_x0020_by_x0020_L_x0'>" + _dr["ows_Commissioning by L_x0"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Commissioning_x0020_by_x0020_L_x1'>" + _dr["ows_Commissioning by L_x1"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Turnover_x0020_Docs'>" + _dr["ows_Turnover Docs"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Comments'>" + _dr["ows_Comments"].ToString().Replace("<div>", "").Replace("<font face=Arial>", "").Replace("</div>", "").Replace("</font>", "") + "</Field>");

stringBuilder1.Append("<Field Name='Start_x0020_Date_x0020_for_x00200'>" + _dr["ows_Start Date for_x00200"].ToString().Replace("datetime;#", "") + "</Field>");

stringBuilder1.Append("<Field Name='Type_x0020_of_x0020_Work'>" + _dr["ows_Type of Work"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Prcnt_x0020_Construction_x0020_C'>" + _dr["ows_Prcnt Construction C"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Scope_x0020_Year'>" + _dr["ows_Scope Year"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='FAI_x0020_Equipment'>" + _dr["ows_FAI Equipment"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Substation_x0020_Owner'>" + _dr["ows_Substation Owner"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Post_x0020_Const_x0020_Fortis_x0'>" + _dr["ows_Post Const Fortis_x0"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='GS_x0020_Engineer'>" + _dr["ows_GS Engineer"].ToString() + "</Field>");

stringBuilder1.Append("<Field Name='Comm_x0020_Configuration'>" + _dr["ows_Comm Configuration"].ToString() + "</Field>");

//stringBuilder1.Append("<Field Name='Commissioning_x0020_Turnover_x00'>" + _dr["ows_Commissioning Turnover_x00"].ToString() + "</Field>");

stringBuilder1.Append("</Method>");

string strQuery1 = stringBuilder1.ToString();

batchElement.InnerXml = strQuery1;

/*Update list items. This example uses the list GUID, which is recommended, but the list display name will also work.*/

destListService.UpdateListItems(destListGUID, batchElement);

}

}

}

}

}

}

}

this.statusStrip1.Text = "Synchronization Successfully Completed";

MessageBox.Show("Synchronization Successfully Completed","AMIMover");

}

}

}

catch (Exception ex)

{

MessageBox.Show("Message:->\n" + ex.Message + "\nStackTrace:->\n" + ex.StackTrace, "LDAPLookUp - Personal Information Lookup Tool", MessageBoxButtons.OK, MessageBoxIcon.Warning);

}

}

private string NullCheck(object dataRow)

{

if (dataRow == null)

{

return "";

}

else

{

return dataRow.ToString();

}

}

private void btnExit_Click_1(object sender, EventArgs e)

{

this.Close();

this.Dispose();

}

}

}

Here is the sample for the 1st Approach [ItemAdded Event Handler]:

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

namespace AMIAddEventHandler

{

public class AddAction : SPItemEventReceiver

{

public override void ItemAdded(SPItemEventProperties properties)

{

string _errorStage = "Initializing...";

try

{

_errorStage = "Creating Instance of The Destination Site";

using (SPSite destSite = new SPSite(@"http://spsandbox/sites/DevSite2"))

{

_errorStage = "Creating Instance of The Destination Web";

using (SPWeb destWeb = destSite.RootWeb)

{

_errorStage = "Creating Instance of The Destination List";

SPList destList = destWeb.GetList("/Lists/Schedule");

_errorStage = "Adding New List Item";

SPListItem newDestItem = destList.Items.Add();

_errorStage = "Defining Field Values";

SPListItem item = properties.ListItem;

foreach (SPField field in item.Fields)

{

if (!field.ReadOnlyField)

newDestItem[field.Id] = item[field.Id];

newDestItem.Update();

}

destList.Update();

}

}

}

catch (Exception ex)

{

properties.Cancel = true;

properties.ErrorMessage = "Fazlul's Error:" + ex.Message;

}

}

}

}

Feature.XML:

<Feature Scope="Web"

Title="AMI Inserting Event Handler"

Id="{9BD865C8-75C2-4a83-AF67-561BD46B5C95}"

xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>

<ElementManifest Location="Elements.xml"/>

</ElementManifests>

</Feature>

Elements.XML

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Receivers ListTemplateId="100">

<Receiver>

<Name>AMIAddEventHandler</Name>

<Type>ItemAdding</Type>

<SequenceNumber>10000</SequenceNumber>

<Assembly>AMIAddEventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d9b9c1eae2e779b</Assembly>

<Class>AMIAddEventHandler.AddAction</Class>

<Data></Data>

<Filter></Filter>

</Receiver>

</Receivers>

</Elements>

Then, create a Install.bat file with the following contents or run those command from SharePoint Server:

cd c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
stsadm -o installfeature -filename AMIAddEventHandler\Feature.xml
stsadm -o activatefeature -filename AMIAddEventHandler\Feature.xml -url
http://spsandbox/sites/DevSite1
iisreset
pause

Download Source Code from: http://spinternalexternal.codeplex.com/

Comments

Popular posts from this blog

How to Create SSRS Report on SharePoint List

Database Testing With DBUnit

SAP RFC Integration through BizTalk