using System;

using System.Collections.Generic;

using System.Text;

using System.Threading;

using System.Net;

using Colligo.WML;

using Colligo.WML.Sync;

using Colligo.Properties;

using Colligo.Util.Office;

 

namespace ColligoSDKTest

{

      class ColligoSDKTest

    {

        const string DEVELOPER_KEY = "0K1Q8-075YJ-Q8FEN-GS64P-45JXG";

 

            static void Main (string[] args)

            {

                  ColligoSDKTest test = new ColligoSDKTest();

            test.RunTest();

            test.RunSyncTest();

            test.RunBlockingSyncTest();

                  test.RunAddInTest();

            }

 

            void RunTest()

            {

                  IWebManager webMgr = null;

                  SyncManager syncMgr = null;

                  try

                  {

                        // get web manager

                        webMgr = WMLApp.GetWebManager();

 

                        // initialize web manager

                        webMgr.Initialize(DEVELOPER_KEY);

 

                        // get and initialize sync manager

                        syncMgr = SyncManager.GetInstance();

                        syncMgr.Initialize();

 

                        // get web by URL

                        IWeb web = webMgr.GetWebByUrl("http://sharepoint/development");

 

                        if (web == null)

                        {

                              throw new System.Exception("Could not find web with specified URL");

                        }

 

                        // show the lists and libraries in the web, including their GUID identifier

                        DisplayLists(web);

 

                        // show the users and AD groups in the web, including their integer ID

                        DisplayUsers(web);

 

                        // get list using its GUID identifier

                        IList lib = web.GetListByServerName("{76379E87-0BA1-4DC6-BB9A-82E337085BA0}");

 

                        if (lib == null)

                        {

                              throw new System.Exception("Could not find list with specified GUID");

                        }

 

                        // locate subfolder

                        IListItem folder = lib.GetListItemByPath("/Subfolder1/Subfolder2");

 

                        if ( folder == null )

                        {

                              throw new System.Exception( "Could not find folder with specified path" );

                        }

 

                        // get multiple update lock to defer auto-sync until operations are

                        // complete

                        using (lib.GetMultipleUpdateLock())

                        {

                              // this call immediately commits changes to database

                              IListItem imported = lib.ImportFile(folder, "BITS.doc", null, true);

 

                              // set metadata on the imported file

                              SetMetaData(lib, imported);

                        }

 

                        // now an example of creating a list item and setting its metadata

                        IList taskList = web.GetListByServerName("{6D8293FA-81C4-48EC-821F-59265B854484}");

 

                        if (taskList == null)

                        {

                              throw new System.Exception("Could not locate Tasks list");

                        }

 

                        // create new item, initializing default column values

                        IListItem newItem = taskList.CreateNewItem(true);

 

                        // set metadata values (does not commit anything to database)

                        newItem.SetProperty("Title", "Evaluation Task");

                        newItem.SetProperty("Status", "In Progress");

                       

                        // commit changes

                        newItem.Update();

                  }

                  catch (System.Exception except)

                  {

                        Console.WriteLine("System.Exception: " + except);

                  }

 

                  Console.WriteLine("Hit any key to exit ...");

                  Console.ReadKey();

 

                  // need to shutdown sync manager and web manager in the correct order

                  if (syncMgr != null)

                  {

                        syncMgr.Shutdown();

                  }

                  if (webMgr != null)

                  {

                        webMgr.Shutdown();

                  }

            }

 

            void DisplayLists(IWeb web)

            {

                  Console.WriteLine("Displaying lists for site: " + web.Title);

                  foreach (IList list in web.Lists)

                  {

                        Console.WriteLine("List Title: " + list.Title);

                        Console.WriteLine("List GUID: " + list.ServerName);

                        Console.WriteLine();

                  }

            }

 

            void DisplayUsers(IWeb web)

            {

                  Console.WriteLine("Displaying users for site: " + web.Title);

                  foreach (IUser user in web.Users)

                  {

                        Console.WriteLine("User Name: " + user.Name);

                        Console.WriteLine("User ID: " + user.UserID);

                        Console.WriteLine();

                  }

            }

 

            /// <summary>

            /// Display columns, including the internal name of the column.

            /// </summary>

            /// <param name="list"></param>

            void DisplayColumns(IList list)

            {

                  Console.WriteLine("Displaying columns for list: " + list.Title);

                  foreach (PropertyContext ctx in list.Fields)

                  {

                        Console.WriteLine("Column display name: " + ctx.DisplayName);

                        Console.WriteLine("Column internal name: " + ctx.Name);

                        Console.WriteLine();

                  }

            }

 

            void SetMetaData(IList list, IListItem item)

            {

                  // note that you must use the internal column name when setting column values

                  DisplayColumns(list);

 

                  // set text column: single-line, multi-line, or choice;

                  // for multiple choices, use ';#' as delimiter

                  item.SetProperty("MyChoice", "Apple;#Orange");

 

                  // set numeric or currency column

                  item.SetProperty("Numerical_x0020_Column", 2811);

 

                  // set date-time column

                  item.SetProperty("Time_x0020_of_x0020_Incident", DateTime.Now + new TimeSpan(

                        0, 15, 0 ) );

 

                  // set hyperlink column

                  item.SetProperty("Hyperlink_x0020_column", new HyperlinkPrimitive(

                        "Colligo Networks", "www.colligo.com"));

 

                  // set lookup or person/group column in form <id>;#<value>;#<id>;#<value>

                  // value can be left blank

                  item.SetProperty("Task_x0020_Lookup", "53;#Task 53;#57;#Task 57");

 

                  item.SetProperty("MultiPerson", "18;#Andrew Block;#25;#David Whitehead");

 

                  // set yes/no column

                  item.SetProperty("My_x0020_YesNo", true);

 

                  item.Update();

            }

 

            void RunSyncTest()

            {

                  IWebManager webMgr = null;

                  SyncManager syncMgr = null;

                  try

                  {

                        // get web manager

                        webMgr = WMLApp.GetWebManager();

 

                        // initialize web manager

                        webMgr.Initialize(DEVELOPER_KEY);

 

                        // get and initialize sync manager

                        syncMgr = SyncManager.GetInstance();

                        syncMgr.Initialize();

 

                        // get web by URL

                        IWeb web = webMgr.GetWebByUrl("http://sharepoint/development");

 

                        if (web == null)

                        {

                              throw new System.Exception("Could not find web with specified URL");

                        }

 

                        // the SDK currently only supports two methods for initiating sync;

                        // in both methods, sync is delegated to the main CFS program (which

                        // will be automatically launched if it is not already running)

 

                        // handle sync completed notification

                        syncMgr.SyncUpdate += new SyncUpdateHandler(HandleSyncResults);

 

                        // request that a site be synchronized

                        syncMgr.RequestServerSync(web, false);

 

                        // get list using its GUID identifier

                        IList lib = web.GetListByServerName("{76379E87-0BA1-4DC6-BB9A-82E337085BA0}");

 

                        if (lib == null)

                        {

                              throw new System.Exception("Could not find list with specified GUID");

                        }

 

                        // request that an individual list or library be synchronized

                        syncMgr.RequestListSync(web, lib, false);

                  }

                  catch (System.Exception except)

                  {

                        Console.WriteLine("System.Exception: " + except);

                  }

 

                  Console.WriteLine("Hit any key to exit ...");

                  Console.ReadKey();

 

                  // need to shutdown sync manager and web manager in the correct order

                  if (syncMgr != null)

                  {

                        syncMgr.Shutdown();

                  }

                  if (webMgr != null)

                  {

                        webMgr.Shutdown();

                  }

            }

 

            private void HandleSyncResults(object source, SyncUpdateArgs args)

            {

                  Console.WriteLine("Received sync results:");

                  Console.WriteLine("  Web = " + args.SyncResults.WebURL);

                  Console.WriteLine("  Result = " + args.SyncResults.CompletionStatus);

            }

 

            void RunBlockingSyncTest()

            {

                  IWebManager webMgr = null;

                  SyncManager syncMgr = null;

                  try

                  {

                        // get web manager

                        webMgr = WMLApp.GetWebManager();

 

                        // initialize web manager

                        webMgr.Initialize(DEVELOPER_KEY);

 

                        // get and initialize sync manager

                        syncMgr = SyncManager.GetInstance();

                        syncMgr.Initialize();

 

                        string url = "http://sharepoint/development";

 

                        Console.WriteLine("Downloading web '" + url + "' ...");

 

                        SyncResults results = BlockingDownload(syncMgr, url, null, 15 * 60 );

 

                        if ( results == null )

                        {

                              Console.WriteLine( "Download timed out" );

                        }

                        else if ( results.CompletionStatus != SyncStatus.Completed )

                        {

                              Console.WriteLine("Error downloading '" + url + "': " +

                                    results.CompletionStatus);

                        }

                        else

                        {

                              Console.WriteLine("Finished downloading '" + url + "'");

 

                              // enable a specific list for synchronization

                              IWeb web = webMgr.GetWeb(results.WebHandle);

                              IList lib = web.GetListByServerName("{76379E87-0BA1-4DC6-BB9A-82E337085BA0}");

 

                              lib.SyncSettings.SyncEnabled = true;

                              lib.UpdateSyncSettings();

 

                              Console.WriteLine("Enabled sync for library, now synchronizing library ...");

 

                              results = BlockingListSync(syncMgr, web, lib, 15 * 60);

 

                              if (results == null)

                              {

                                    Console.WriteLine("Sync timed out");

                              }

                              else if (results.CompletionStatus != SyncStatus.Completed)

                              {

                                    Console.WriteLine("Error synchronizing library: " + results.CompletionStatus);

                              }

                              else

                              {

                                    Console.WriteLine("Sync completed");

                              }

                        }

                  }

                  catch (System.Exception except)

                  {

                        Console.WriteLine("System.Exception: " + except);

                  }

 

                  Console.WriteLine("Hit any key to exit ...");

                  Console.ReadKey();

 

                  // need to shutdown sync manager and web manager in the correct order

                  if (syncMgr != null)

                  {

                        syncMgr.Shutdown();

                  }

                  if (webMgr != null)

                  {

                        webMgr.Shutdown();

                  }

            }

 

            private SyncResults BlockingDownload(SyncManager mgr, string url,

                  System.Net.NetworkCredential cred, int secondsTimeout)

            {

                  object notifyComplete = new object();

                  SyncTransaction transaction = null;

                  SyncResults results = null;

                  SyncUpdateHandler handleSyncResults = delegate(object source,

                        SyncUpdateArgs args)

                        {

                              if (args.StatusInfo.Transaction.Equals(transaction) &&

                                    args.SyncResults != null)

                              {

                                    results = args.SyncResults;

                                    lock (notifyComplete)

                                    {

                                          Monitor.Pulse(notifyComplete);

                                    }

                              }

                        };

                  mgr.SyncUpdate += handleSyncResults;

 

                  transaction = mgr.DownloadWeb(url, cred);

 

                  lock (notifyComplete)

                  {

                        Monitor.Wait(notifyComplete, secondsTimeout * 1000);

                  }

 

                  mgr.SyncUpdate -= handleSyncResults;

 

                  return results;

            }

 

            private SyncResults BlockingWebSync(SyncManager mgr, IWeb web, int secondsTimeout)

            {

                  object notifyComplete = new object();

                  SyncTransaction transaction = null;

                  SyncResults results = null;

                  SyncUpdateHandler handleSyncResults = delegate(object source,

                        SyncUpdateArgs args)

                        {

                              if (args.StatusInfo.Transaction.Equals(transaction) &&

                                    args.SyncResults != null)

                              {

                                    results = args.SyncResults;

                                    lock (notifyComplete)

                                    {

                                          Monitor.Pulse(notifyComplete);

                                    }

                              }

                        };

                  mgr.SyncUpdate += handleSyncResults;

 

                  transaction = mgr.RequestServerSync(web);

 

                  lock (notifyComplete)

                  {

                        Monitor.Wait(notifyComplete, secondsTimeout * 1000);

                  }

 

                  mgr.SyncUpdate -= handleSyncResults;

 

                  return results;

            }

 

            private SyncResults BlockingListSync(SyncManager mgr, IWeb web, IList list, int secondsTimeout)

            {

                  object notifyComplete = new object();

                  SyncTransaction transaction = null;

                  SyncResults results = null;

                  SyncUpdateHandler handleSyncResults = delegate(object source,

                        SyncUpdateArgs args)

                        {

                              if (args.StatusInfo.Transaction.Equals(transaction) &&

                                    args.SyncResults != null)

                              {

                                    results = args.SyncResults;

                                    lock (notifyComplete)

                                    {

                                          Monitor.Pulse(notifyComplete);

                                    }

                              }

                        };

                  mgr.SyncUpdate += handleSyncResults;

 

                  transaction = mgr.RequestListSync(web, list);

 

                  lock (notifyComplete)

                  {

                        Monitor.Wait(notifyComplete, secondsTimeout * 1000);

                  }

 

                  mgr.SyncUpdate -= handleSyncResults;

 

                  return results;

            }

 

            public void RunAddInTest()

            {

                  IWebManager webMgr = null;

                  try

                  {

                        // get web manager

                        webMgr = WMLApp.GetWebManager();

 

                        // initialize web manager

                        webMgr.Initialize(DEVELOPER_KEY);

 

                        // get add-in reference, launching Outlook if necessary

                        IOutlookAddIn addIn = webMgr.GetOutlookAddIn(true, -1);

 

                        if (addIn == null)

                        {

                              throw new ApplicationException("Failed to get Outlook Add-in reference");

                        }

 

                        Console.WriteLine("Got add-in reference");

 

                        // create folder for list with offline view enabled

                        addIn.CreateFolder("{7e36bfdb-1310-4d3b-bebd-217bb346ff51}",

                              "{6D8293FA-81C4-48EC-821F-59265B854484}", 0, true,

                              null, "My Tasks Folder", "My Parent Folder");

 

                        Console.WriteLine("Created tasks folder");

 

                        // create folder for doc lib with online view enabled

                        addIn.CreateFolder("{7e36bfdb-1310-4d3b-bebd-217bb346ff51}",

                              "{9CDD6B1F-AE6B-4E80-B81B-3B2621CF752F}", 0,

                              false, "http://sharepoint/development/documents", "Documents", "Development");

 

                        Console.WriteLine("Created doc lib folder");

 

                        // delete folders matching specified criteria

                        int deleted = addIn.DeleteMatchingFolders("{7e36bfdb-1310-4d3b-bebd-217bb346ff51}",

                              "{9CDD6B1F-AE6B-4E80-B81B-3B2621CF752F}", 40);

 

                        Console.WriteLine("Deleted " + deleted + " folders");

                  }

                  catch (System.Exception except)

                  {

                        Console.WriteLine("Exception: " + except);

                  }

 

                  Console.WriteLine("Hit any key to exit ...");

                  Console.ReadKey();

 

                  if (webMgr != null)

                  {

                        webMgr.Shutdown();

                  }

            }

      }

}