private void LookUpListProcess(XElement dataMapping, SPSite site, LogUtility logUtility, XElement fieldElement, Guid webID, Guid listID, XElement contentType)
        {
            using (SPWeb lookupWeb = site.AllWebs[webID])
            {
                SPList existingList = (from SPList l in lookupWeb.Lists
                                       where l.ID.Equals(listID)
                                       select l).FirstOrDefault();
                if (null != existingList)
                {
                    SPList lookupList = existingList;
                    fieldElement.Add(new XAttribute("SPType", "Lookup"),
                                    new XAttribute("AssociatedTypeName", "List"),
                                    new XAttribute("AssociationTableName", lookupList.Title));
                    contentType.Add(fieldElement);
                    string url = urlBuilder(lookupWeb);

                    logUtility.TraceDebugInformation(string.Format("Generating SLAM config for List with title: {0} on web at: {1}", lookupList.Title, url), GetType());
                    XElement LookUpListElement = new XElement("List",
                                                new XAttribute("Site", url),
                                                new XAttribute("Name", lookupList.Title),
                                                new XAttribute("ActivationOrder", activateOrder++));
                    SetFieldElements(dataMapping, site, lookupList.Fields, LookUpListElement);
                    dataMapping.Add(LookUpListElement);

                }
            }
        }
 public void CreateRuleManagedMetadataField(IContentOrganizerRuleCreationData data)
 {
     data.RequireNotNull("data");
     ILogUtility logger = new LogUtility();
     string conditionsXml = setConditions(data);
     logger.TraceDebugInformation(string.Format("Conditions:{0}", conditionsXml), GetType());
     using (SPSite site = new SPSite(data.SiteAbsoluteUrl))
     using (SPWeb web = site.OpenWeb())
     {
         creator.CreateRuleManagedMetadataField(data, conditionsXml, site, web, managedMetadataAutoCreator);
     }
 }
        public SPListTemplate GetListTemplate(SPListTemplateCollection listTemplates, string templateName)
        {
            listTemplates.RequireNotNull("listTemplates");
            templateName.RequireNotNullOrEmpty("templateName");

            try
            {
                return listTemplates[templateName];
            }
            catch (Exception exception)
            {
                LogUtility logUtility = new LogUtility();
                logUtility.TraceDebugException("Can't find list template", GetType(), exception);
                return null;
            }
        }
        /// <summary>
        /// The Byte array is the SLAM Configuration file
        /// </summary>
        /// <param name="webApplication"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public Byte[] WriteSlamConfig(SPWebApplication webApplication, string connectionString)
        {
            webApplication.RequireNotNull("webApplication");
            connectionString.RequireNotNullOrEmpty("connectionString");
            Byte[] SLAMConfigData = null;
            LogUtility logUtlity = new LogUtility();

            try
            {
                logUtlity.TraceDebugInformation("Writing SLAM Configuration now.", GetType());
                SLAMConfigData = WriteSlamConfigImpl(webApplication, connectionString);
            }
            catch (Exception exception)
            {
                logUtlity.TraceDebugException("Error while writing SLAM configuration!", GetType(), exception);
            }

            finally
            {
                logUtlity.TraceDebugInformation("Finished writing SLAM Configuration now.", GetType());
            }

            return SLAMConfigData;
        }
 private static void registerTypeMappings(IServiceLocatorConfig typeMappings)
 {
     LogUtility logger = new LogUtility();
     logger.TraceDebugInformation("starting registerTypeMappings", typeof(ServiceLocationRegistration));
     typeMappings.RegisterTypeMapping<IServiceLocatorConfig, ServiceLocatorConfig>();
     typeMappings.RegisterTypeMapping<IAddSandboxedSolutions, AddSandboxedSolutions>();
     typeMappings.RegisterTypeMapping<IContentTypeOperations, ContentTypeOperations>();
     typeMappings.RegisterTypeMapping<IDocIconOperations, DocIconOperations>();
     typeMappings.RegisterTypeMapping<IFeatureActivator, FeatureActivator>();
     typeMappings.RegisterTypeMapping<IFieldOperations, FieldOperations>();
     typeMappings.RegisterTypeMapping<IListOperations, ListOperations>();
     //typeMappings.RegisterTypeMapping<ILogUtility, SPListLogger>();
     typeMappings.RegisterTypeMapping<ILogUtility, LogUtility>();
     typeMappings.RegisterTypeMapping<IManagedMetaDataOperations, ManagedMetaDataOperations>();
     typeMappings.RegisterTypeMapping<IModifyContentType, ModifyContentType>();
     typeMappings.RegisterTypeMapping<IViewOperations, ModifyViewClass>();
     typeMappings.RegisterTypeMapping<INavigationCustomization, NavigationCustomization>();
     typeMappings.RegisterTypeMapping<ISiteColumnOperations, SiteColumnOperations>();
     typeMappings.RegisterTypeMapping<ISPFileOperations, SPFileOperations>();
     typeMappings.RegisterTypeMapping<ISPUserOperations, SPUserOperations>();
     typeMappings.RegisterTypeMapping<ITimerJobOperations, TimerJobOperations>();
     typeMappings.RegisterTypeMapping<IWebPartOperations, WebPartOperations>();
     typeMappings.RegisterTypeMapping<IWorkflowOperations, WorkflowOperations>();
     typeMappings.RegisterTypeMapping<IFaceBookGraphAPIOperations, FaceBookGraphAPIOperations>();
     typeMappings.RegisterTypeMapping<IWorkflowMessageParser, WorkflowMessageParser>();
     typeMappings.RegisterTypeMapping<IUserParser, UserParser>();
     typeMappings.RegisterTypeMapping<ISLAMConfigurationGenerator, SLAMConfigurationGenerator>();
     typeMappings.RegisterTypeMapping<IListTemplateFinder, ListTemplateFinder>();
     typeMappings.RegisterTypeMapping<IWikiPagesOperations, WikiPagesOperations>();
     typeMappings.RegisterTypeMapping<IContentOrganizerRuleCreationData, ContentOrganizerRuleCreationData>();
     typeMappings.RegisterTypeMapping<IContentOrganizerConditionalData, ContentOrganizerConditionalData>();
     typeMappings.RegisterTypeMapping<IContentOrganizerCreator, ContentOrganizerCreator>();
     typeMappings.RegisterTypeMapping<ICustomContentOrganizerRouterRegistrar, CustomContentOrganizerRouterRegistrar>();
     typeMappings.RegisterTypeMapping<ILinkToDocumentCreator, LinkToDocumentCreator>();
     logger.TraceDebugInformation("Finishing registerTypeMappings", typeof(ServiceLocationRegistration));
 }
        public void RemoveSiteContentTypeAssociation(SPSite site, string associationName)
        {
            LogUtility logUtility = new LogUtility();
            SPWeb rootWeb = site.RootWeb;
            SPWorkflowAssociation association = null;
            logUtility.TraceDebugInformation(string.Format("Removing site contenttype workflow association '{0}'.", associationName), GetType());
            // Remove all site content type workflow associations
            foreach (SPContentType ctype in rootWeb.ContentTypes)
            {
                // Remove site content type workflow association
                association = ctype.WorkflowAssociations.GetAssociationByName(associationName, rootWeb.Locale);
                if (association != null)
                {
                    ctype.WorkflowAssociations.Remove(association);
                }
            }

            // Remove list content type workflow associations
            foreach (SPWeb web in site.AllWebs)
            {
                // Since we plan to modify some lists later we can not use the standard web.Lists collection
                System.Collections.Generic.List<Guid> lists = new System.Collections.Generic.List<Guid>();
                foreach (SPList list in web.Lists) lists.Add(list.ID);

                // Check all lists
                foreach (Guid listId in lists)
                {
                    // Get list
                    SPList list = web.Lists[listId];

                    // Remove all matching list content type associations
                    foreach (SPContentType ctype in list.ContentTypes)
                    {
                        // Remove list content type workflow association
                        association = ctype.WorkflowAssociations.GetAssociationByName(associationName, web.Locale);
                        if (association != null)
                        {
                            ctype.WorkflowAssociations.Remove(association);
                        }
                    }

                    // Find all workflow status fields in the list
                    System.Collections.Generic.List<Guid> fields = new System.Collections.Generic.List<Guid>();
                    foreach (SPField field in list.Fields)
                    {
                        // Check field and save Guid on match
                        if (field.Type == SPFieldType.WorkflowStatus && field.Title == associationName)
                        {
                            fields.Add(field.Id);
                        }
                    }

                    // Remove the fields from the list
                    foreach (Guid fieldId in fields)
                    {
                        SPField f = list.Fields[fieldId];   // Get the status field
                        f.ReadOnlyField = false;            // Flag read/write
                        f.Update(true);                     // Update first otherwise the field cannot be deleted
                        f.Delete();                         // Now delete
                    }

                    // Save modified list in database
                    list.Update();
                }
                web.Dispose();

            }
        }
        private byte[] WriteSlamConfigImpl(SPWebApplication webApplication, string connectionString)
        {
            LogUtility logUtlity = new LogUtility();
            XDocument configurationFile = new XDocument();
            XElement configuration = new XElement("Configuration");
            configurationFile.Add(configuration);
            XElement connectionStrings = new XElement("ConnectionStrings");
            configuration.Add(connectionStrings);
            XAttribute defaultAttribute = new XAttribute("Default", "SLAM");
            connectionStrings.Add(defaultAttribute);
            connectionStrings.Add(new XElement("add",
                                                new XAttribute("Name", "SLAM"),
                                                new XAttribute("ConnectionString", connectionString)
                                                ));
            XElement dataMapping = new XElement("DataMapping", new XAttribute("DataSchema", "SLAM"));

            configuration.Add(dataMapping);
            SPWebApplication app = webApplication;
            if (null != app)
            {
                foreach (SPSite site in app.Sites)
                {
                    try
                    {
                        AddConfigInfo(dataMapping, site);
                    }
                    catch (Exception exception)
                    {
                        logUtlity.TraceDebugException("Error trying to write Config information", GetType(), exception);
                    }

                    finally
                    {
                        site.Dispose();
                    }
                }

                Byte[] slamConfigData = null;

                using (MemoryStream stream = new MemoryStream())
                {
                    XmlWriter xmlWriter = XmlWriter.Create(stream);
                    configurationFile.WriteTo(xmlWriter);
                    xmlWriter.Close();
                    slamConfigData = stream.ToArray();
                }
                logUtlity.TraceDebugInformation(string.Format("Writing {0} bytes of SLAM configuration data", slamConfigData.Length), GetType());
                return slamConfigData;
            }

            else
            {
                logUtlity.TraceDebugInformation("Cannot find Web Application at http://localhost!", GetType());
            }
            return null;
        }
        private string urlBuilder(SPWeb lookupWeb)
        {
            LogUtility logUtility = new LogUtility();
            SPWeb currentWeb = lookupWeb;
            List<SPWeb> webs = new List<SPWeb>();
            bool lastWebWasRoot = false;
            while (!lastWebWasRoot)
            {
                logUtility.TraceDebugInformation(string.Format("Last web was not the root! Current Web is {0}", currentWeb), GetType());
                webs.Add(currentWeb);
                lastWebWasRoot = currentWeb.IsRootWeb;
                currentWeb = currentWeb.ParentWeb;
            }
            webs.Reverse();

            StringBuilder urlBuilder = new StringBuilder(webs.First().Title);
            foreach (SPWeb web in webs.Skip(1))
            {
                urlBuilder.AppendFormat("//{0}", web.Title);
            }

            return urlBuilder.ToString();
        }
        private void SetFieldElements(XElement dataMapping, SPSite site, IEnumerable<SPField> fields, XElement contentTypeElement)
        {
            LogUtility logUtility = new LogUtility();
            foreach (SPField field in fields)
            {
                XElement fieldElement = new XElement("Field",
                                        new XAttribute("Name", field.Title),
                                        new XAttribute("Required", field.Required)
                        );

                switch (field.Type)
                {
                    case SPFieldType.Recurrence:
                        fieldElement.Add(new XAttribute("SqlType", "bit"), new XAttribute("SPType", "Recurrence"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.AllDayEvent:
                        fieldElement.Add(new XAttribute("SqlType", "bit"), new XAttribute("SPType", "AllDayEvent"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Boolean:
                        fieldElement.Add(new XAttribute("SqlType", "bit"), new XAttribute("SPType", "Boolean"));
                        contentTypeElement.Add(fieldElement);
                        break;

                    case SPFieldType.Calculated:
                        fieldElement.Add(new XAttribute("SqlType", "decimal"), new XAttribute("SPType", "Calculated"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.DateTime:
                        fieldElement.Add(new XAttribute("SqlType", "datetime"), new XAttribute("SPType", "DateTime"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.MultiChoice:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "MultiChoice"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.GridChoice:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "GridChoice"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Choice:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "Choice"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Integer:
                        fieldElement.Add(new XAttribute("SqlType", "int"), new XAttribute("SPType", "Integer"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Lookup:
                        SPFieldLookup lookupField = field as SPFieldLookup;
                        if (null != lookupField)
                        {
                            Guid webID = lookupField.LookupWebId;
                            try
                            {
                                ProcessLookupLists(dataMapping, site, logUtility, fieldElement, lookupField, webID, contentTypeElement);
                            }
                            catch (Exception exception)
                            {
                                logUtility.TraceDebugException(string.Format("Caught exception trying to parse {0} field", field.Title), GetType(), exception);
                            }
                        }
                        break;
                    case SPFieldType.ModStat:
                        fieldElement.Add(new XAttribute("SqlType", "int"), new XAttribute("SPType", "ModStat"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Currency:
                        fieldElement.Add(new XAttribute("SqlType", "float"), new XAttribute("SPType", "Currency"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Number:
                        fieldElement.Add(new XAttribute("SqlType", "float"), new XAttribute("SPType", "Number"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.URL:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "Url"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Note:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(512)"), new XAttribute("SPType", "Note"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.User:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "User"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Computed:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "Computed"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.Text:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "Text"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    case SPFieldType.WorkflowStatus:
                        fieldElement.Add(new XAttribute("SqlType", "nvarchar(255)"), new XAttribute("SPType", "WorkflowStatus"));
                        contentTypeElement.Add(fieldElement);
                        break;
                    default:
                        break;
                }

            }
        }
        private void ProcessLookupLists(XElement dataMapping, SPSite site, LogUtility logUtility, XElement fieldElement, SPFieldLookup lookupField, Guid webID, XElement contentType)
        {
            Guid listID = Guid.Empty;
            try
            {
                listID = new Guid(lookupField.LookupList);
            }
            catch (FormatException formatException)
            {
                logUtility.TraceDebugException(string.Format("Caught format Exception for field with id: {0} and title: {1}", lookupField.LookupField, lookupField.Title), GetType(), formatException);
            }

            if (!ListIDs.Contains(listID))
            {
                ListIDs.Add(listID);
                LookUpListProcess(dataMapping, site, logUtility, fieldElement, webID, listID, contentType);
            }
        }
        private static void UnregisterTypes(SPSite site)
        {
            site.RequireNotNull("site");
            LogUtility logUtility = new LogUtility();
            try
            {
                logUtility.TraceDebugInformation("Deactivating Local utilities", typeof(ServiceLocationRegistration));
                IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
                IServiceLocatorConfig typeMappings = serviceLocator.GetInstance<IServiceLocatorConfig>();
                typeMappings.Site = site;
                unregisterTypeMappings(typeMappings);
                logUtility.TraceDebugInformation("Successfully deactivated Local utilities", typeof(ServiceLocationRegistration));
            }
            catch (Exception exception)
            {
                logUtility.TraceDebugException("Error while deactivating Local utilities", typeof(ServiceLocationRegistration), exception);
            }

            finally
            {
                logUtility.TraceDebugInformation("Finished deactivating Local utilities", typeof(ServiceLocationRegistration));
            }
        }
        private static void UnregisterTypes(SPWeb web)
        {
            LogUtility logUtility = new LogUtility();
            try
            {
                logUtility.TraceDebugInformation("Deactivating Local utilities", typeof(ServiceLocationRegistration));
                IServiceLocator serviceLocator = new SPWebServiceLocator(web);
                IServiceLocatorConfig typeMappings = serviceLocator.GetInstance<IServiceLocatorConfig>();
                unregisterTypeMappings(typeMappings);
                logUtility.TraceDebugInformation("Successfully deactivated Local utilities", typeof(ServiceLocationRegistration));
            }
            catch (Exception exception)
            {
                logUtility.TraceDebugException("Error while deactivating Local utilities", typeof(ServiceLocationRegistration), exception);
            }

            finally
            {
                logUtility.TraceDebugInformation("Finished deactivating Local utilities", typeof(ServiceLocationRegistration));
            }
        }
 private static void RegisterTypes(SPSite site)
 {
     site.RequireNotNull("site");
     LogUtility logger = new LogUtility();
     try
     {
         logger.TraceDebugInformation("Registering types for use across farms", typeof(ServiceLocationRegistration));
         IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
         IServiceLocatorConfig typeMappings = serviceLocator.GetInstance<IServiceLocatorConfig>();
         typeMappings.Site = site;
         registerTypeMappings(typeMappings);
     }
     catch (Exception exception)
     {
         logger.TraceDebugException("Exception while registering types!", typeof(ServiceLocationRegistration), exception);
     }
     finally
     {
         logger.TraceDebugInformation("Finished registering types for use across farms", typeof(ServiceLocationRegistration));
     }
 }
 private static void RegisterTypes(SPWeb web)
 {
     web.RequireNotNull("web");
     LogUtility logger = new LogUtility();
     try
     {
         logger.TraceDebugInformation("Registering types for use across farms", typeof(ServiceLocationRegistration));
         IServiceLocator serviceLocator = new SPWebServiceLocator(web);
         IServiceLocatorConfig typeMappings = serviceLocator.GetInstance<IServiceLocatorConfig>();
         registerTypeMappings(typeMappings);
     }
     catch (Exception exception)
     {
         logger.TraceDebugException("Exception while registering types!", typeof(ServiceLocationRegistration), exception);
     }
     finally
     {
         logger.TraceDebugInformation("Finished registering types for use across farms", typeof(ServiceLocationRegistration));
     }
 }