public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;

            SPWeb rootweb = site.RootWeb;
            SPContentType ct = rootweb.ContentTypes["Article"];

            SPList list = rootweb.Lists["Organization Units"];

            String internalname = rootweb.Fields.AddLookup("Organization Unit", list.ID, rootweb.ID, true);

            SPFieldLookup lookup = (SPFieldLookup)rootweb.Fields.GetFieldByInternalName(internalname);
            lookup.AllowMultipleValues = true;
            lookup.LookupField = "Title";
            lookup.Group = "NCNewssite";
            lookup.Update(true);
            lookup.StaticName = "OrganizationUnit";

            SPFieldLink fieldLink = new SPFieldLink(lookup);

            ct.FieldLinks.Add(fieldLink);
            //Reorder fields
            List<string> fieldNames = new List<string>(){"Title", "ArticleAuthor", "PublishingStart", "PublishingEnd", "DanishUrl",
                "NorwegianUrl", "EnglishUrl", internalname, "FrontpageHeader1", "FrontpageTopnewsImage", "FrontPageHeader2",
                "FrontpageProfilenewsImage", "ArticleHeader", "ArticleTopImage", "ArticleTopImageText", "ArticleBodyText",
                "RightColumnLinks", "RightColumnFacts"};

            ct.FieldLinks.Reorder(fieldNames.ToArray());
            ct.Update(true);
        }
コード例 #2
0
        //TODO: Error Handling, and move these methods to a more central location if appropriate
        private void AddSiteColumnToListContentType(SPSite curSite, string listName, string contentTypeName, Guid fieldId)
        {
            Logging.Logger.Instance.Info(
                String.Format("Adding Site Column to List Content Type if it Already Exists: List Name: {0}; Content Type Name: {1}; Field: {2}", listName, contentTypeName, fieldId),
                Logging.DiagnosticsCategories.eCaseSite);

            //Get Fresh Site and Web each time to avoid exceptions due to multiple concurrent updates
            using (SPSite freshSite = new SPSite(curSite.ID))
            {
                SPList list = freshSite.RootWeb.Lists.TryGetList(listName);
                if (list != null)
                {
                    SPContentType contentType = list.ContentTypes[contentTypeName];
                    if (!contentType.Fields.Contains(fieldId))
                    {
                        //The field doesn't appear in the Fields collection yet, first see if the field link is there.
                        SPFieldLink fl         = contentType.FieldLinks[fieldId];
                        SPField     siteColumn = freshSite.RootWeb.Fields[fieldId] as SPField;
                        if (fl == null)
                        {
                            contentType.FieldLinks.Add(new SPFieldLink(siteColumn));
                            contentType.Update();
                            list.Update();
                        }

                        //The field is in the FieldLinks collection, now ensure it's in the fields collection.
                        if (!list.Fields.Contains(fieldId) && !siteColumn.Hidden)
                        {
                            list.Fields.Add(siteColumn);
                            list.Update();
                        }
                    }
                }
            }
        }
コード例 #3
0
        private static void AddFieldsToContentType(SPWeb web, SPContentType contentType, Guid[] fieldIdArray, bool required)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            if (fieldIdArray == null)
            {
                throw new ArgumentException("fieldId");
            }

            if (web == null)
            {
                throw new ArgumentNullException("web");
            }

            foreach (Guid fieldId in fieldIdArray)
            {
                SPField field = web.AvailableFields[fieldId];

                SPFieldLink fieldLink = new SPFieldLink(field);
                fieldLink.Required = required;

                if (contentType.FieldLinks[fieldLink.Id] == null)
                {
                    contentType.FieldLinks.Add(fieldLink);
                }
            }
        }
コード例 #4
0
        //Content Type Web Site Correspondencia
        public void CreateCustomContentTypes(string nameCustomType, string nameGroupContentType, List <SPField> siteColumns)
        {
            using (SPSite site = oSPSite)
            {
                using (SPWeb oSPWeb = site.RootWeb)
                {
                    // Get a reference to the Document or Item content type.
                    SPContentType parentCType = oSPWeb.AvailableContentTypes[SPBuiltInContentTypeId.Document];

                    // Create a Customer content type derived from the Item content type.
                    SPContentType childCType = new SPContentType(parentCType, oSPWeb.ContentTypes, nameCustomType);

                    childCType.Group = nameGroupContentType;

                    // Add the new content type to the site collection.
                    childCType = oSPWeb.ContentTypes.Add(childCType);

                    foreach (SPField field in siteColumns)
                    {
                        SPFieldLink fieldLink = new SPFieldLink(field);
                        childCType.FieldLinks.Add(fieldLink);
                    }
                    string[] fieldsToHide = new string[] { "Título" };
                    foreach (string fieldDispName in fieldsToHide)
                    {
                        SPField field = childCType.Fields[fieldDispName];
                        childCType.FieldLinks[field.Id].Hidden = true;
                    }

                    childCType.Update();

                    oSPWeb.Update();
                }
            }
        }
コード例 #5
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = GetContentType(spWeb);
            if (ct == null)
            {
                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            if (!ct.Fields.Contains(SiteColumns.HomeworkAssignmentName))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.HomeworkAssignmentName]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Student))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.IsAssignmentComplete))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.IsAssignmentComplete]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
コード例 #6
0
ファイル: Helpers.cs プロジェクト: eduardpaul/SPHelpers
    /// <summary>
    ///
    /// </summary>
    /// <param name="web"></param>
    /// <param name="contentName"></param>
    /// <param name="column"></param>
    /// <param name="required"></param>
    /// <param name="readonlyField"></param>
    public static void AddColumntToContentType(this SPWeb web, string contentName, string column, bool required = false, bool readonlyField = false)
    {
        try
        {
            SPContentType contentType = web.ContentTypes[contentName];

            if (contentType != null)
            {
                if (!contentType.Fields.ContainsField(column))
                {
                    SPField field = web.Fields.GetField(column);

                    SPFieldLink fieldLink = new SPFieldLink(field);
                    fieldLink.Required = required;
                    fieldLink.ReadOnly = readonlyField;

                    contentType.FieldLinks.Add(fieldLink);
                    contentType.Update(true);
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CORE:HELPERS", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, String.Format("Exception happened in Helpers:AddColumntToContentType. MESSAGE: {0}. EXCEPTION TRACE: {1} ", ex.Message, ex.StackTrace), ex.StackTrace);
        }
    }
コード例 #7
0
        public override bool Perform()
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                try
                {
                    Web.AllowUnsafeUpdates = true;
                    foreach (SPList list in Web.Lists)
                    {
                        if (!list.Hidden && (uint)list.BaseTemplate == 10702)
                        {
                            foreach (SPContentType contentType in list.ContentTypes)
                            {
                                try
                                {
                                    if (contentType != null && contentType.Name == "Task")
                                    {
                                        SPField fldDescription = list.Fields.GetFieldByInternalName("Body");
                                        if (fldDescription != null)
                                        {
                                            SPFieldLink fld = new SPFieldLink(fldDescription);
                                            if (fld != null)
                                            {
                                                if (contentType.FieldLinks[fld.Id] == null)
                                                {
                                                    contentType.FieldLinks.Delete(fld.Name);
                                                    contentType.Update();
                                                    contentType.FieldLinks.Add(fld);
                                                    contentType.Update();
                                                    list.Update();
                                                    LogMessage(string.Format("Update processed with List: {0} , ContentType: {1} , Field: {2}", list.Title, contentType.Name, fld.DisplayName), MessageKind.SUCCESS, 4);
                                                }
                                                else
                                                {
                                                    LogMessage(string.Format("Skipped process with List: {0} , ContentType: {1} , Field: {2}", list.Title, contentType.Name, fld.DisplayName), MessageKind.SKIPPED, 2);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    string message = exception.InnerException != null
                        ? exception.InnerException.Message
                        : exception.Message;

                    LogMessage(message, MessageKind.FAILURE, 4);
                }
            });

            return(true);
        }
コード例 #8
0
        public SPFieldLinkInstance(ObjectInstance prototype, SPFieldLink fieldLink)
            : this(prototype)
        {
            if (fieldLink == null)
            {
                throw new ArgumentNullException("fieldLink");
            }

            m_fieldLink = fieldLink;
        }
コード例 #9
0
        public SPFieldLinkInstance Construct(SPFieldInstance field)
        {
            if (field == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "When constructing a new instance of a field link, a field must be supplied as the first argument.");
            }

            var newFieldLink = new SPFieldLink(field.SPField);

            return(new SPFieldLinkInstance(this.InstancePrototype, newFieldLink));
        }
コード例 #10
0
        public static void EnableTimesheets(SPList list, SPWeb web)
        {
            TryAddField(list, "Timesheet", SPFieldType.Boolean, "Timesheet", false);
            TryAddField(list, "TimesheetHours", SPFieldType.Number, "Timesheet Hours", false);

            SPField field = list.Fields.GetFieldByInternalName("TimesheetHours");

            field.ShowInEditForm = false;
            field.ShowInNewForm  = false;
            field.Hidden         = false;
            field.Update();

            field        = list.Fields.GetFieldByInternalName("Timesheet");
            field.Hidden = false;
            field.Update();

            try
            {
                SPContentType defaultContentType = list.ContentTypes["Item"];
                {
                    if (field != null)
                    {
                        SPFieldLink fld = new SPFieldLink(field);
                        if (fld != null)
                        {
                            if (defaultContentType.FieldLinks[fld.Id] == null)
                            {
                                defaultContentType.FieldLinks.Delete(fld.Name);
                                defaultContentType.Update();
                                defaultContentType.FieldLinks.Add(fld);
                                defaultContentType.Update();
                                list.Update();
                            }
                        }
                    }
                }
            }
            catch { }

            try
            {
                SPWeb rootWeb = web.Site.RootWeb;

                ArrayList lists = new ArrayList(EPMLiveCore.CoreFunctions.getConfigSetting(rootWeb, "EPMLiveTSLists").Replace("\r\n", "\n").Split('\n'));;

                if (!lists.Contains(list.Title))
                {
                    lists.Add(list.Title);

                    EPMLiveCore.CoreFunctions.setConfigSetting(rootWeb, "EPMLiveTSLists", String.Join("\n", (string[])lists.ToArray(typeof(string))).Replace("\n", "\r\n"));
                }
            }
            catch { }
        }
コード例 #11
0
 /// <summary>
 /// Fields the exist.
 /// </summary>
 /// <param name="contentType">Type of the content.</param>
 /// <param name="fieldLink">The field link.</param>
 /// <returns></returns>
 private static bool FieldExist(SPContentType contentType, SPFieldLink fieldLink)
 {
     try
     {
         //will throw exception on missing fields
         return(contentType.Fields[fieldLink.Id] != null);
     }
     catch (Exception)
     {
         return(false);
     }
 }
コード例 #12
0
        private void AssociateFieldWithContentType(SPDocumentLibrary reportLibrary, string fieldName, string contentName)
        {
            var field       = reportLibrary.Fields[fieldName];
            var fieldLink   = new SPFieldLink(field);
            var contentType = reportLibrary.ContentTypes[contentName];

            if (contentType.FieldLinks[fieldName] == null)
            {
                contentType.FieldLinks.Add(fieldLink);
                contentType.Update();
            }
        }
コード例 #13
0
        private void DeployHideContentTypeLinks(object modelHost, ContentTypeModelHost contentTypeModelHost, HideContentTypeFieldLinksDefinition hideFieldLinksModel)
        {
            var contentType = contentTypeModelHost.HostContentType;
            var fieldLinks  = contentType.FieldLinks.OfType <SPFieldLink>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = contentType,
                ObjectType       = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost        = modelHost
            });

            // re-order
            foreach (var srcFieldLink in hideFieldLinksModel.Fields)
            {
                SPFieldLink currentFieldLink = null;

                if (!string.IsNullOrEmpty(srcFieldLink.InternalName))
                {
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Name == srcFieldLink.InternalName);
                }

                if (currentFieldLink == null && srcFieldLink.Id.HasValue)
                {
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Id == srcFieldLink.Id.Value);
                }

                if (currentFieldLink != null)
                {
                    currentFieldLink.ReadOnly = false;
                    currentFieldLink.Required = false;
                    currentFieldLink.Hidden   = true;
                }
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = contentType,
                ObjectType       = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost        = modelHost
            });

            contentTypeModelHost.ShouldUpdateHost = true;
        }
コード例 #14
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = spWeb.ContentTypes[ContentTypeID];
            if (ct == null)
            {

                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            if (!ct.Fields.Contains(SiteColumns.Class))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Class]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Student))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.ClassYear))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.ClassYear]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.TotalPoints))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.TotalPoints]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.TotalPointsAllowed))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.TotalPointsAllowed]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.LetterGrade))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.LetterGrade]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
        private bool AddFieldLink(SPWeb web, SPContentType contentType, string fieldName, bool required)
        {
            bool    fieldLinkAdded = false;
            SPField field          = web.Fields[fieldName];

            if (field != null && !contentType.Fields.ContainsField(fieldName))
            {
                SPFieldLink link = new SPFieldLink(field);
                link.Required = required;
                contentType.FieldLinks.Add(link);
                fieldLinkAdded = true;
            }
            return(fieldLinkAdded);
        }
コード例 #16
0
        public static SPFieldLink AddFieldLink(this SPContentType contentType, Guid fieldId)
        {
            SPField field = contentType.ParentWeb.AvailableFields[fieldId];
            SPFieldLink fieldLink = new SPFieldLink(field);

            if (contentType.FieldLinks[fieldLink.Id] == null)
            {
                contentType.FieldLinks.Add(fieldLink);
            }
            else
            {
                fieldLink = contentType.FieldLinks[fieldLink.Id];
            }

            return fieldLink;
        }
コード例 #17
0
        public static SPFieldLink AddFieldLink(this SPContentType contentType, Guid fieldId)
        {
            SPField     field     = contentType.ParentWeb.AvailableFields[fieldId];
            SPFieldLink fieldLink = new SPFieldLink(field);

            if (contentType.FieldLinks[fieldLink.Id] == null)
            {
                contentType.FieldLinks.Add(fieldLink);
            }
            else
            {
                fieldLink = contentType.FieldLinks[fieldLink.Id];
            }

            return(fieldLink);
        }
コード例 #18
0
        private void DeployHideContentTypeLinks(object modelHost, SPContentType contentType, RemoveContentTypeFieldLinksDefinition hideFieldLinksModel)
        {
            var fieldLinks = contentType.FieldLinks.OfType <SPFieldLink>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = contentType,
                ObjectType       = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost        = modelHost
            });

            // re-order
            foreach (var srcFieldLink in hideFieldLinksModel.Fields)
            {
                SPFieldLink currentFieldLink = null;

                if (!string.IsNullOrEmpty(srcFieldLink.InternalName))
                {
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Name == srcFieldLink.InternalName);
                }

                if (currentFieldLink == null && srcFieldLink.Id.HasValue)
                {
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Id == srcFieldLink.Id.Value);
                }

                if (currentFieldLink != null)
                {
                    contentType.FieldLinks.Delete(currentFieldLink.Id);
                }
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = contentType,
                ObjectType       = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost        = modelHost
            });
        }
コード例 #19
0
        private void CreateContentType(object sender, EventArgs e)
        {
            // Create new content type
            SPContentType baseCT = selectedWeb.AvailableContentTypes["Document"];
            SPContentType newCT  = new SPContentType(baseCT, selectedWeb.ContentTypes, "KB File");

            selectedWeb.ContentTypes.Add(newCT);

            // Add FieldLink to content type
            SPField     fld     = selectedWeb.AvailableFields["KBTopic"];
            SPFieldLink fldLink = new SPFieldLink(fld);

            newCT.FieldLinks.Add(fldLink);
            newCT.Update(true);

            PopulateContentTypeDD(selectedWeb);
        }
コード例 #20
0
 /// <summary>
 /// Add the specified field to the provided ContentType (Id)
 /// </summary>
 /// <param name="web"></param>
 /// <param name="contentTypeId"></param>
 /// <param name="field"></param>
 public void AddFieldToContentType(string teamUrl, SPContentTypeId contentTypeId, SPField field)
 {
     using (SPWeb spWeb = GetTeamWeb(teamUrl))
     {
         SPContentType contentType = spWeb.ContentTypes[contentTypeId];
         if (contentType == null)
         {
             return;
         }
         if (contentType.Fields.ContainsField(field.Title))
         {
             return;
         }
         SPFieldLink fieldLink = new SPFieldLink(field);
         contentType.FieldLinks.Add(fieldLink);
         contentType.Update();
     }
 }
コード例 #21
0
        protected override void ProcessRecord()
        {
            var schema = XDocument.Load(SchemaPath);
            XNamespace ns = "http://schemas.microsoft.com/sharepoint/";

            using (var site = new SPSite(Url))
            {
                var web = site.OpenWeb();

                // Process fields.
                foreach (var field in schema.Root.Descendants(ns+"Field"))
                {
                    WriteObject("Processing " + field.Attribute("Name").Value);

                    var fieldName = web.Fields.Add(field.Attribute("Name").Value, SPFieldType.Text, false);
                    var spField = web.Fields.GetFieldByInternalName(fieldName);
                    spField.StaticName = field.Attribute("StaticName").Value;
                    spField.Title = field.Attribute("DisplayName").Value;
                    spField.Update();
                }

                // Process content types.
            }

            return;

            using (var site = new SPSite(Url))
            {
                var web = site.RootWeb;

                var field = web.Fields["URL"];

                var id = new SPContentTypeId("0x01010075425CE93BDC404F8B042629FC235785");
                var termsAndConditionsType = new SPContentType(id, web.ContentTypes, "TermsAndConditionsType");
                web.ContentTypes.Add(termsAndConditionsType);
                termsAndConditionsType = web.ContentTypes[id];
                termsAndConditionsType.Group = "Custom Content Types";
                termsAndConditionsType.Description = "Custom Content Type for Terms and Conditions";
                termsAndConditionsType.Update();
                var l = new SPFieldLink(field) { DisplayName = "My URL" };
                termsAndConditionsType.FieldLinks.Add(l);
                termsAndConditionsType.Update();
            }
        }
コード例 #22
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = spWeb.ContentTypes[ContentTypeID];
            if (ct == null)
            {

                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            //if (!ct.Fields.Contains(SiteColumns.StudentFirstname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentFirstname]);
            //    ct.FieldLinks.Add(field);
            //}

            //if (!ct.Fields.Contains(SiteColumns.StudentLastname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentLastname]);
            //    ct.FieldLinks.Add(field);
            //}

            //if (!ct.Fields.Contains(SiteColumns.StudentFullname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentFullname]);
            //    ct.FieldLinks.Add(field);
            //}
            if (!ct.Fields.Contains(SiteColumns.Student)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Parents)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Parents]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
コード例 #23
0
 /// <summary>
 /// Add Column Site of Content Type
 /// </summary>
 /// <param name="name">name of column</param>
 /// <returns></returns>
 public bool AddColumn(string name)
 {
     try
     {
         var contentType = Web.ContentTypes[Name];
         var field       = GetField(name, Web);
         var fieldLink   = new SPFieldLink(field);
         if (contentType.FieldLinks[fieldLink.Id] == null)
         {
             contentType.FieldLinks.Add(fieldLink);
         }
         contentType.Update(true);
     }
     catch (Exception exception)
     {
         Logger.Error(string.Concat("Add Column ContentType: ", exception.Message));
         return(false);
     }
     return(true);
 }
コード例 #24
0
        private static void AddFieldsToContentType(SPWeb web, SPContentType contentType, Guid[] fieldIdArray)
        {
            Validation.ArgumentNotNull(web, "web");
            Validation.ArgumentNotNull(contentType, "contentType");
            Validation.ArgumentNotNull(fieldIdArray, "fieldIdArray");

            foreach (Guid fieldId in fieldIdArray)
            {
                if (web.AvailableFields.Contains(fieldId))
                {
                    SPField     field     = web.AvailableFields[fieldId];
                    SPFieldLink fieldLink = new SPFieldLink(field);
                    if (contentType.FieldLinks[fieldLink.Id] == null)
                    {
                        contentType.FieldLinks.Add(fieldLink);
                        contentType.Update();
                    }
                }
            }
        }
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //Get references to the site and web, ensuring correct disposal
            using (SPSite site = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb web = site.RootWeb)
                {
                    //Check if the custom field already exists.
                    if (web.AvailableFields.Contains(MyFieldId) == false)
                    {
                        //Create the new field
                        web.Fields.AddFieldAsXml(MyFieldDefXml);
                        web.Update();
                    }
                    //Check if the content type already exists
                    SPContentType myContentType = web.ContentTypes["Product Announcement Content Type"];
                    if (myContentType == null)
                    {
                        //Our content type will be based on the Annoucement content type
                        SPContentType announcementContentType = web.AvailableContentTypes[SPBuiltInContentTypeId.Announcement];

                        //Create the new content type
                        myContentType = new SPContentType(announcementContentType, web.ContentTypes, "Product Announcement Content Type");

                        //Add the custom field to it
                        SPFieldLink newFieldLink = new SPFieldLink(web.AvailableFields["Contoso Product Name"]);
                        myContentType.FieldLinks.Add(newFieldLink);

                        //Add the new content type to the site
                        web.ContentTypes.Add(myContentType);
                        web.Update();

                        //Add it to the Announcements list
                        SPList annoucementsList = web.Lists["Announcements"];
                        annoucementsList.ContentTypesEnabled = true;
                        annoucementsList.ContentTypes.Add(myContentType);
                        annoucementsList.Update();
                    }
                }
            }
        }
コード例 #26
0
        public void AddFieldTo(SPContentType contentType, SPFieldCollection sourceFields, SPWeb parentWeb = null)
        {
            if (contentType != null && !contentType.Fields.ContainsField(this))
            {
                SPFieldLink link = null;
                if (sourceFields.ContainsField(this))
                {
                    link = new SPFieldLink(sourceFields.GetField(this));
                }
                else if (parentWeb.AvailableFields.ContainsField(this))
                {
                    link = new SPFieldLink(parentWeb.AvailableFields.GetField(this));
                }

                if (link != null)
                {
                    contentType.FieldLinks.Add(link);
                    contentType.Update();
                }
            }
        }
コード例 #27
0
        private static bool AddFieldToContentType(SPContentType contentType, SPField field, bool updateContentType, RequiredType isRequired)
        {
            // Create the field ref.
            SPFieldLink fieldOneLink = new SPFieldLink(field);

            if (contentType.FieldLinks[fieldOneLink.Id] == null)
            {
                // Set the RequiredType value on the Content Type
                switch (isRequired)
                {
                case RequiredType.Required:
                    fieldOneLink.Required = true;
                    break;

                case RequiredType.NotRequired:
                    fieldOneLink.Required = false;
                    break;

                case RequiredType.Inherit:
                default:
                    // Do nothing, it will inherit from the Field definition
                    break;
                }

                // Field is not in the content type so we add it.
                contentType.FieldLinks.Add(fieldOneLink);

                // Update the content type.
                if (updateContentType)
                {
                    contentType.Update(true);
                }

                return(true);
            }

            return(false);
        }
コード例 #28
0
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType newAnnouncement = spWeb
                    .ContentTypes
                    .Cast<SPContentType>()
                    .FirstOrDefault(c => c.Name == "New Announcements");
                if (newAnnouncement != null)
                {
                    newAnnouncement.Delete();
                }

                SPField newField = spWeb.Fields
                    .Cast<SPField>()
                    .FirstOrDefault(f => f.StaticName == "Team Project");
                if (newField != null)
                {
                    newField.Delete();
                }

                SPContentType myContentType =
                    new SPContentType(spWeb.ContentTypes["Announcement"],
                        spWeb.ContentTypes, "New Announcements");
                myContentType.Group = "Custom Content Types";

                spWeb.Fields.Add("Team Project", SPFieldType.Text, true);
                SPFieldLink projFeldLink = new SPFieldLink(spWeb.Fields["Team Project"]);
                myContentType.FieldLinks.Add(projFeldLink);

                SPFieldLink companyFieldLink = new SPFieldLink(spWeb.Fields["Company"]);
                myContentType.FieldLinks.Add(companyFieldLink);

                spWeb.ContentTypes.Add(myContentType);
                myContentType.Update();
            }
        }
コード例 #29
0
        /// <summary>
        /// Add specified field to content type (or update existing with specified props)
        /// </summary>
        /// <param name="pWeb"></param>
        /// <param name="pContentType"> </param>
        /// <param name="pField"></param>
        /// <param name="pRequired">should this field be required or not</param>
        /// <param name="pReadOnly"> </param>
        public static void AddFieldToContentType(SPWeb pWeb, SPContentType pContentType, SPField pField, bool pRequired, bool pReadOnly, string pDisplayName)
        {
            using (SPSite site = new SPSite(pWeb.Site.ID))
            {
                using (SPWeb rootWeb = site.OpenWeb(site.RootWeb.ID))
                {
                    rootWeb.AllowUnsafeUpdates = true;
                    SPFieldLink fieldLink;
                    if (!pContentType.Fields.Contains(pField.Id))
                    {
                        fieldLink = new SPFieldLink(pField);

                        pContentType.FieldLinks.Add(fieldLink);
                    }
                    else
                    {
                        fieldLink = pContentType.FieldLinks[pField.Id];
                    }

                    fieldLink.Required    = pRequired;
                    fieldLink.DisplayName = string.IsNullOrEmpty(pDisplayName) ? pField.Title : pDisplayName;

                    if (pRequired)
                    {
                        fieldLink.ReadOnly = false;
                    }
                    else
                    {
                        fieldLink.ReadOnly = pReadOnly;
                    }

                    SPContentType checkContentType = rootWeb.AvailableContentTypes[pContentType.Id];
                    pContentType.Update(null != checkContentType);
                    rootWeb.AllowUnsafeUpdates = false;
                }
            }
        }
コード例 #30
0
        public static SPContentType CreateContentType(SPContentType parentType, SPWeb web, string contentTypeName, string contentTypeGroup, IEnumerable<SPField> fields)
        {
            // Validation
            parentType.RequireNotNull("parentType");
            web.RequireNotNull("spContentTypeCollection");
            contentTypeName.RequireNotNullOrEmpty("contentTypeName");
            contentTypeGroup.RequireNotNullOrEmpty("contentTypeGroup");
            fields.RequireNotNull("fields");

            SPContentType contentType = web.AvailableContentTypes[contentTypeName];
            if (null != contentType)
            {
                return contentType;
            }

            contentType = new SPContentType(parentType, web.ContentTypes, contentTypeName);
            contentType = web.ContentTypes.Add(contentType);
            contentType.Group = contentTypeGroup;

            foreach (SPField field in fields)
            {
                SPFieldLink fieldLink = new SPFieldLink(field);
                contentType.FieldLinks.Add(fieldLink);
            }
            contentType.Update();

            return contentType;
        }
コード例 #31
0
        public static void AddFieldToContentType(SPContentType cType, IEnumerable<SPField> fields)
        {
            cType.RequireNotNull("cType");
            fields.RequireNotNull("field");

            foreach (SPField field in fields)
            {
                var matchingLinks = from SPFieldLink fl in cType.FieldLinks
                                    where fl.DisplayName.Equals(field.Title)
                                    select fl;
                if (!cType.Fields.Contains(field.Id) && matchingLinks.Count() == 0)
                {
                    SPFieldLink fieldLink = new SPFieldLink(field);
                    cType.FieldLinks.Add(fieldLink);
                }
            }

            cType.Update(true);
        }
コード例 #32
0
        private static bool AddFieldToContentType(SPContentType contentType, SPField field, bool updateContentType)
        {
            // Create the field ref.
            SPFieldLink fieldOneLink = new SPFieldLink(field);
            if (contentType.FieldLinks[fieldOneLink.Id] == null)
            {
                // Field is not in the content type so we add it.
                contentType.FieldLinks.Add(fieldOneLink);

                // Update the content type.
                if (updateContentType)
                {
                    contentType.Update(true);
                }

                return true;
            }

            return false;
        }
コード例 #33
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try {
                Global.Debug = "start";
                SPWeb web = properties.Feature.Parent as SPWeb;
                if (web == null)
                {
                }


                SPList listKundkort = web.Lists.TryGetList("Kundkort");
                Global.Debug = "Kundkort";
                SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter");
                Global.Debug = "Aktiviteter";

                if (!web.Properties.ContainsKey("activatedOnce"))
                {
                    web.Properties.Add("activatedOnce", "true");
                    web.Properties.Update();
                    Global.Debug = "set activatedOnce flag";

                    #region sätt default-kommun-värden
                    if (municipals.Count > 0)
                    {
                        Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000);
                    }
                    else
                    {
                        municipals.Add("uppsala", new Municipal {
                            AreaCode = "018", Name = "Uppsala", RegionLetter = "C"
                        });
                        municipals.Add("borlänge", new Municipal {
                            AreaCode = "0243", Name = "Borlänge", RegionLetter = "W"
                        });
                    }
                    Global.Debug = "added municipals";
                    #endregion

                    #region hämta listor
                    SPList listAgare = web.Lists.TryGetList("Ägare");
                    Global.Debug = "Ägare";
                    SPList listKontakter = web.Lists.TryGetList("Kontakter");
                    Global.Debug = "Kontakter";
                    SPList listAdresser = web.Lists.TryGetList("Adresser");
                    Global.Debug = "Adresser";
                    SPList listSidor = web.Lists.TryGetList("Webbplatssidor");
                    Global.Debug = "Webbplatssidor";
                    SPList listNyheter = web.Lists.TryGetList("Senaste nytt");
                    Global.Debug = "Senaste nytt";
                    //SPList listBlanketter = web.Lists.TryGetList("Blanketter");
                    SPList listGenvagar = web.Lists.TryGetList("Genvägar");
                    Global.Debug = "Genvägar";
                    SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar");
                    Global.Debug = "Gruppkopplingar";

                    SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar };
                    int      i     = 0;
                    foreach (SPList list in lists)
                    {
                        i++;
                        if (list == null)
                        {
                            Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000);
                        }
                    }
                    #endregion

                    if (listSidor != null)
                    {
                        #region startsida
                        string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatBasicWikiLayout();
                        Global.Debug     = "Skapa startsida";
                        SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage);

                        // Header
                        string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl;
                        _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hj&auml;rta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>");

                        #region Nyheter
                        ListViewWebPart wpAnnouncements = new ListViewWebPart();
                        wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper();
                        wpAnnouncements.ViewGuid = string.Empty;
                        Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements);
                        AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]");
                        #endregion

                        #region Genvägar
                        ListViewWebPart wpLinks = new ListViewWebPart();
                        wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper();
                        wpLinks.ViewGuid = string.Empty;
                        Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks);
                        AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]");
                        #endregion

                        startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        startsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Startsida skapad";
                        #endregion

                        #region lägg till försäljningsställe
                        string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Skapa nybutiksida";
                        SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage);

                        // Header
                        _wikiFullContent = _wikiFullContent.Replace("[[COL1]]",
                                                                    @"<h1>Sida för att lägga till nya försäljningsställen</h1>
<h2>STEG 1 - Lägg till ägare</h2>
[[WP1]]
<h2>STEG 2 - Lägg till adressuppgifter</h2>
[[WP2]]
<h2>STEG 3 - Lägg till kontaktperson</h2>
[[WP3]]
<h2>STEG&#160;4 - Lägg till försäljningsstället</h2>
[[WP4]]");

                        Global.Debug = "wpAgare";
                        XsltListViewWebPart wpAgare = new XsltListViewWebPart();
                        wpAgare.ChromeType = PartChromeType.None;
                        wpAgare.ListName   = listAgare.ID.ToString("B").ToUpper();
                        wpAgare.ViewGuid   = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAgare.Toolbar    = "Standard";
                        Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare);
                        AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]");

                        Global.Debug = "wpAdresser";
                        XsltListViewWebPart wpAdresser = new XsltListViewWebPart();
                        wpAdresser.ChromeType = PartChromeType.None;
                        wpAdresser.ListName   = listAdresser.ID.ToString("B").ToUpper();
                        wpAdresser.ViewGuid   = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAdresser.Toolbar    = "Standard";
                        Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser);
                        AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]");

                        Global.Debug = "wpKontakter";
                        XsltListViewWebPart wpKontakter = new XsltListViewWebPart();
                        wpKontakter.ChromeType = PartChromeType.None;
                        wpKontakter.ListName   = listKontakter.ID.ToString("B").ToUpper();
                        wpKontakter.ViewGuid   = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKontakter.Toolbar    = "Standard";
                        Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter);
                        AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]");

                        Global.Debug = "wpKundkort";
                        XsltListViewWebPart wpKundkort = new XsltListViewWebPart();
                        wpKundkort.ChromeType = PartChromeType.None;
                        wpKundkort.ListName   = listKundkort.ID.ToString("B").ToUpper();
                        wpKundkort.ViewGuid   = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKundkort.Toolbar    = "Standard";
                        Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort);
                        AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]");

                        nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        nybutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";

                        #endregion

                        #region mitt försäljningsställe
                        string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Skapa minbutiksida";
                        SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpMinButik";
                        MinButikWP wpMinButik = new MinButikWP();
                        wpMinButik.ChromeType = PartChromeType.None;
                        wpMinButik.Adresser   = "Adresser";
                        wpMinButik.Agare      = "Ägare";
                        wpMinButik.Kontakter  = "Kontakter";
                        wpMinButik.Kundkort   = "Kundkort";
                        Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik);
                        AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]");

                        minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        minbutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";
                        #endregion

                        #region skapa tillsynsrapport
                        //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout
                        //_wikiFullContent = FormatSimpleWikiLayout();
                        //Global.Debug = "Skapa tillsynsrapport";
                        //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage);

                        //Global.Debug = "wpTillsyn";
                        //TillsynWP wpTillsyn = new TillsynWP();
                        //wpTillsyn.ChromeType = PartChromeType.None;
                        //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn);
                        //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]");

                        //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        //skapatillsynsida.Item.UpdateOverwriteVersion();
                        //Global.Debug = "Skapatillsynsida skapad";
                        #endregion

                        #region inställningar
                        string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Inställningar";
                        SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpSettings";
                        SettingsWP wpSettings = new SettingsWP();
                        wpSettings.ChromeType = PartChromeType.None;
                        Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings);
                        AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]");

                        installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        installningarsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Installningarsida skapad";
                        #endregion
                    }

                    #region debugdata

                    Global.Debug = "ägare";
                    SPListItem item = listAgare.AddItem();
                    item["Title"] = "TESTÄGARE AB";
                    item.Update();

                    try {
                        Global.Debug      = "kontakt";
                        item              = listKontakter.AddItem();
                        item["Title"]     = "Testsson";
                        item["FirstName"] = "Test";
                        item["Email"]     = "*****@*****.**";
                        item.Update();

                        item              = listKontakter.AddItem();
                        item["Title"]     = "Jansson";
                        item["FirstName"] = "Peter";
                        item["Email"]     = "*****@*****.**";
                        item.Update();
                    }
                    catch (Exception ex) {
                        Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
                    }

                    Global.Debug  = "adress";
                    item          = listAdresser.AddItem();
                    item["Title"] = "Testgatan 13b";
                    item.Update();

                    #endregion

                    #region nyhet
                    Global.Debug  = "nyhet";
                    item          = listNyheter.AddItem();
                    item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här";
                    item["Body"]  = @"Hej!

Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial.

" + web.Title + " kommun";
                    item.Update();
                    #endregion

                    #region länkar
                    Global.Debug  = "länkar";
                    item          = listGenvagar.AddItem();
                    Global.Debug  = "Blanketter";
                    item["Title"] = "Blanketter";
                    item["URL"]   = web.ServerRelativeUrl + "/Blanketter, Blanketter";
                    item.Update();
                    item          = listGenvagar.AddItem();
                    Global.Debug  = "Utbildningsmaterial";
                    item["Title"] = "Utbildningsmaterial";
                    item["URL"]   = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial";
                    item.Update();
                    #endregion

                    #region sätt kundnummeregenskaper
                    Global.Debug = "löpnummer";
                    web.Properties.Add("lopnummer", "1000");
                    Global.Debug = "prefixformel";
                    web.Properties.Add("prefixFormula", "%B%R-%N");
                    Global.Debug = "listAdresserGUID";
                    web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString());
                    Global.Debug = "listAgareGUID";
                    web.Properties.Add("listAgareGUID", listAgare.ID.ToString());
                    Global.Debug = "gruppkopplingar";
                    web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString());
                    try {
                        Municipal m = municipals[web.Title.ToLower()];
                        web.Properties.Add("municipalAreaCode", m.AreaCode);
                        web.Properties.Add("municipalRegionLetter", m.RegionLetter);
                    }
                    catch { }
                    Global.Debug = "properties";
                    web.Properties.Update();
                    #endregion
                }
                else
                {
                    Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000);
                }

                #region modify template global
                Global.Debug = "ensure empty working directory";
                DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun");
                string        webid     = web.Url.Replace("http://", "").Replace('/', '_');
                string        dirname   = @"workdir_" + webid;
                Global.Debug = "dir: " + dirname;
                DirectoryInfo diWorkDir = diFeature.CreateSubdirectory(dirname);

                if (!diWorkDir.Exists)
                {
                    diWorkDir.Create();
                }

                XNamespace xsf  = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition";
                XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions";
                XNamespace xd   = "http://schemas.microsoft.com/office/infopath/2003";

                #endregion

                #region modify template tillsyn
                {
                    Global.Debug = "deleting files";
                    foreach (FileInfo fi in diWorkDir.GetFiles())
                    {
                        fi.Delete();
                    }

                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn";
                    string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "get content type";
                    SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName];

                    Global.Debug = "modify manifest";
                    XDocument doc            = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf");
                    var       xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var       q1             = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                                               where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                                               select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Tillsyn/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}";
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value    = ctTillsyn.Id.ToString();
                    doc.Save(diWorkDir.FullName + @"\manifest.xsf");

                    Global.Debug = "modify view1";
                    XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl");
                    foreach (var d in doc2.Descendants("object"))
                    {
                        d.Attribute(xd + "server").Value = web.Url + "/";
                    }
                    doc2.Save(diWorkDir.FullName + @"\view1.xsl");

                    Global.Debug = "repack";
                    string   directive    = "directives_inspection_" + webid + ".txt";
                    string   cabinet      = "template_inspection_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                    {
                        fiDirectives.Delete();
                    }
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDir.GetFiles())
                        {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute        = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName         = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments        = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists)
                    {
                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Tillsyn/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"]   = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"];
                        folder.Properties["_ipfs_solutionName"]    = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else
                    {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }

                    //Global.Debug = "set default forms";
                    //// create our own array since it will be modified (which would throw an exception)
                    //var forms = new SPForm[listAktiviteter.Forms.Count];
                    //int j = 0;
                    //foreach (SPForm form in listAktiviteter.Forms) {
                    //    forms[j] = form;
                    //    j++;
                    //}
                    //foreach (var form in forms) {
                    //    SPFile page = web.GetFile(form.Url);
                    //    SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    //    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) {
                    //        if (wp is BrowserFormWebPart) {
                    //            BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject;
                    //            bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Tillsyn/");
                    //            limitedWebPartManager.SaveChanges(bfwp);

                    //            switch (form.Type) {
                    //                case PAGETYPE.PAGE_NEWFORM:
                    //                    listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //                case PAGETYPE.PAGE_EDITFORM:
                    //                    listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //                case PAGETYPE.PAGE_DISPLAYFORM:
                    //                    listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //            }
                    //        }
                    //    }
                    //}
                }
                #endregion

                #region modify template permit
                {
                    Global.Debug = "delete";
                    foreach (FileInfo fi in diWorkDir.GetFiles())
                    {
                        fi.Delete();
                    }

                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    string filename = diFeature.FullName + @"\givepermit.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "get content type";
                    SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName];

                    Global.Debug = "modify manifest";
                    XDocument doc            = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf");
                    var       xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var       q1             = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                                               where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                                               select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Ge%20försäljningstillstånd/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}";
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value    = ctPermit.Id.ToString();
                    doc.Save(diWorkDir.FullName + @"\manifest.xsf");

                    //Global.Debug = "modify view1";
                    //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl");
                    //foreach (var d in doc2.Descendants("object")) {
                    //    d.Attribute(xd + "server").Value = web.Url + "/";
                    //}
                    //doc2.Save(diWorkDir.FullName + @"\view1.xsl");

                    Global.Debug = "repack";
                    string   directive    = "directives_permit_" + webid + ".txt";
                    string   cabinet      = "template_permit_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                    {
                        fiDirectives.Delete();
                    }
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDir.GetFiles())
                        {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute        = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName         = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments        = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists)
                    {
                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Ge försäljningstillstånd/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"]   = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"];
                        folder.Properties["_ipfs_solutionName"]    = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else
                    {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }
                }
                #endregion

                #region set default forms
                Global.Debug = "set default forms";
                foreach (SPContentType ct in listAktiviteter.ContentTypes)
                {
                    switch (ct.Name)
                    {
                    case "Tillsyn":
                    case "Ge försäljningstillstånd":
                        ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx";
                        ct.EditFormUrl    = "~list/" + ct.Name + "/editifs.aspx";
                        ct.NewFormUrl     = "~list/" + ct.Name + "/newifs.aspx";
                        ct.Update();
                        break;

                    default:
                        ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty;
                        ct.Update();
                        break;
                    }
                }

                // create our own array since it will be modified (which would throw an exception)
                var forms = new SPForm[listAktiviteter.Forms.Count];
                int j     = 0;
                foreach (SPForm form in listAktiviteter.Forms)
                {
                    forms[j] = form;
                    j++;
                }
                foreach (var form in forms)
                {
                    SPFile page = web.GetFile(form.Url);
                    SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts)
                    {
                        if (wp is BrowserFormWebPart)
                        {
                            BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject;
                            //bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Ge försäljningstillstånd/");
                            //limitedWebPartManager.SaveChanges(bfwp);
                            string[] aLocation   = form.Url.Split('/');
                            string   contenttype = aLocation[aLocation.Length - 2];
                            bfwp.FormLocation = "~list/" + contenttype + "/template.xsn";
                            limitedWebPartManager.SaveChanges(bfwp);

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine();
                            sb.Append("BrowserFormWebPart FormLocation: ");
                            sb.AppendLine(bfwp.FormLocation);
                            sb.Append("BrowserFormWebPart Title: ");
                            sb.AppendLine(bfwp.Title);
                            sb.Append("BrowserFormWebPart ID: ");
                            sb.AppendLine(bfwp.ID);
                            sb.Append("Form URL: ");
                            sb.AppendLine(form.Url);
                            sb.Append("Form TemplateName: ");
                            sb.AppendLine(form.TemplateName);
                            sb.Append("Form ID: ");
                            sb.AppendLine(form.ID.ToString());
                            sb.Append("Form ServerRelativeUrl: ");
                            sb.AppendLine(form.ServerRelativeUrl);
                            sb.AppendLine("BrowserFormWebPart Schema: ");
                            sb.AppendLine();
                            sb.AppendLine(form.SchemaXml);


                            Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000);

                            //switch (form.Type) {
                            //    case PAGETYPE.PAGE_NEWFORM:
                            //        listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //    case PAGETYPE.PAGE_EDITFORM:
                            //        listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //    case PAGETYPE.PAGE_DISPLAYFORM:
                            //        listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //}
                        }
                    }
                }

                #endregion

                #region cleanup

                Global.Debug = "cleanup";
                diWorkDir.Delete(true);
                foreach (FileInfo fi in diFeature.GetFiles("template*.xsn"))
                {
                    fi.Delete();
                }
                foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn"))
                {
                    fi.Delete();
                }

                #endregion

                #region stäng av required på rubrik
                SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                Global.WriteLog("listKundkort Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000);
                title.Required       = false;
                title.ShowInNewForm  = false;
                title.ShowInEditForm = false;
                title.Update();

                //title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                //Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000);
                //title.Required = false;
                //title.ShowInNewForm = false;
                //title.ShowInEditForm = false;
                //title.Update();

                foreach (SPContentType ct in listAktiviteter.ContentTypes)
                {
                    SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                    flTitle.Required = false;
                    flTitle.Hidden   = true;
                    ct.Update();
                }
                #endregion

                Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001);
            }
            catch (Exception ex) {
                Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
            }
        } // feature activated
コード例 #34
0
        public void AddFieldTo(SPContentType contentType, SPFieldCollection sourceFields, SPWeb parentWeb = null)
        {
            if (contentType != null && !contentType.Fields.ContainsField(this))
            {
                SPFieldLink link = null;
                if (sourceFields.ContainsField(this))
                    link = new SPFieldLink(sourceFields.GetField(this));
                else if (parentWeb.AvailableFields.ContainsField(this))
                    link = new SPFieldLink(parentWeb.AvailableFields.GetField(this));

                if (link != null)
                {
                    contentType.FieldLinks.Add(link);
                    contentType.Update();
                }
            }
        }
コード例 #35
0
        private void CreateContentTypes(SPWeb web)
        {
            //Create the EntityPart ContentType.
            var documentStoreEntityPartContentTypeId          = new SPContentTypeId(Constants.DocumentStoreEntityPartContentTypeId);
            var documentStoreEntityPartContentTypeBestMatchId =
                web.ContentTypes.BestMatch(documentStoreEntityPartContentTypeId);
            var documentStoreEntityPartContentType = web.ContentTypes[documentStoreEntityPartContentTypeBestMatchId];

            if (documentStoreEntityPartContentType == null)
            {
                documentStoreEntityPartContentType = new SPContentType(documentStoreEntityPartContentTypeId, web.ContentTypes, "Document Store Entity Part")
                {
                    Group       = "Document Store Content Types",
                    Description = "Represents additional data that is contained within a Document Store Entity."
                };

                //Add field links.
                var categoryField     = web.AvailableFields[Constants.CategoryFieldId];
                var categoryFieldLink = new SPFieldLink(categoryField)
                {
                    DisplayName       = "Category",
                    ShowInDisplayForm = true,
                    ReadOnly          = false
                };

                documentStoreEntityPartContentType.FieldLinks.Add(categoryFieldLink);

                var commentField     = web.AvailableFields[Constants.CommentFieldId];
                var commentFieldLink = new SPFieldLink(commentField)
                {
                    DisplayName       = "Comments",
                    ShowInDisplayForm = true,
                    ReadOnly          = false
                };
                documentStoreEntityPartContentType.FieldLinks.Add(commentFieldLink);

                var documentEntityGuidField     = web.AvailableFields[Constants.DocumentEntityGuidFieldId];
                var documentEntityGuidFieldLink = new SPFieldLink(documentEntityGuidField)
                {
                    DisplayName       = "DocumentEntityGuid",
                    ShowInDisplayForm = false,
                    ReadOnly          = true,
                    Required          = false
                };
                documentStoreEntityPartContentType.FieldLinks.Add(documentEntityGuidFieldLink);

                web.ContentTypes.Add(documentStoreEntityPartContentType);
                documentStoreEntityPartContentType.Update(true);
            }

            //Create the Document Store Attachment ContentType.
            var documentStoreAttachmentContentTypeId          = new SPContentTypeId(Constants.DocumentStoreEntityAttachmentContentTypeId);
            var documentStoreAttachmentContentTypeBestMatchId =
                web.ContentTypes.BestMatch(documentStoreAttachmentContentTypeId);
            var documentStoreAttachmentContentType = web.ContentTypes[documentStoreAttachmentContentTypeBestMatchId];

            if (documentStoreAttachmentContentType == null)
            {
                documentStoreAttachmentContentType = new SPContentType(documentStoreAttachmentContentTypeId, web.ContentTypes, "Document Store Attachment")
                {
                    Group       = "Document Store Content Types",
                    Description = "Represents a document that is contained within a Document Store Entity."
                };

                //Add field links.
                var categoryField     = web.AvailableFields[Constants.CategoryFieldId];
                var categoryFieldLink = new SPFieldLink(categoryField)
                {
                    DisplayName       = "Category",
                    ShowInDisplayForm = true,
                    ReadOnly          = false
                };
                documentStoreAttachmentContentType.FieldLinks.Add(categoryFieldLink);

                var commentField     = web.AvailableFields[Constants.CommentFieldId];
                var commentFieldLink = new SPFieldLink(commentField)
                {
                    DisplayName       = "Comments",
                    ShowInDisplayForm = true,
                    ReadOnly          = false
                };
                documentStoreAttachmentContentType.FieldLinks.Add(commentFieldLink);

                var pathField     = web.AvailableFields[Constants.AttachmentPathFieldId];
                var pathFieldLink = new SPFieldLink(pathField)
                {
                    DisplayName       = "Path",
                    ShowInDisplayForm = true,
                    ReadOnly          = false
                };
                documentStoreAttachmentContentType.FieldLinks.Add(pathFieldLink);

                var documentEntityGuidField     = web.AvailableFields[Constants.DocumentEntityGuidFieldId];
                var documentEntityGuidFieldLink = new SPFieldLink(documentEntityGuidField)
                {
                    DisplayName       = "DocumentEntityGuid",
                    ShowInDisplayForm = false,
                    ReadOnly          = true,
                    Required          = false
                };
                documentStoreAttachmentContentType.FieldLinks.Add(documentEntityGuidFieldLink);

                web.ContentTypes.Add(documentStoreAttachmentContentType);
                documentStoreAttachmentContentType.Update(true);
            }

            //Finally, create the DocumentStoreEntity ContentType which subclasses Document Set.
            var documentStoreEntityContentTypeId          = new SPContentTypeId(Constants.DocumentStoreEntityContentTypeId);
            var documentStoreEntityContentTypeBestMatchId = web.ContentTypes.BestMatch(documentStoreEntityContentTypeId);
            var documentStoreEntityContentType            = web.ContentTypes[documentStoreEntityContentTypeBestMatchId];

            if (documentStoreEntityContentType == null)
            {
                documentStoreEntityContentType = new SPContentType(documentStoreEntityContentTypeId,
                                                                   web.ContentTypes, "Document Store Entity")
                {
                    Group       = "Document Store Content Types",
                    Description =
                        "Represents a document, attachments and associated metadata in a NoSql/Document-oriented database style model."
                };

                //Add field links.
                var namespaceField     = web.AvailableFields[Constants.NamespaceFieldId];
                var namespaceFieldLink = new SPFieldLink(namespaceField);
                documentStoreEntityContentType.FieldLinks.Add(namespaceFieldLink);

                //TODO: Finish this...
                web.ContentTypes.Add(documentStoreEntityContentType);

                var documentStoreEntityTemplate = DocumentSetTemplate.GetDocumentSetTemplate(documentStoreEntityContentType);
                documentStoreEntityTemplate.AllowedContentTypes.Add(documentStoreEntityPartContentTypeId);
            }
        }
コード例 #36
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = spWeb.ContentTypes[ContentTypeID];
            if (ct == null){
                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            if (!ct.Fields.Contains(SiteColumns.AssignmentName)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.AssignmentName]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.AssignmentDueDate)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.AssignmentDueDate]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.IsAssignmentComplete)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.IsAssignmentComplete]);
                ct.FieldLinks.Add(field);
            }

            //if (!ct.Fields.Contains(SiteColumns.ClassName)){
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.ClassName]);
            //    ct.FieldLinks.Add(field);
            //}

            if (!ct.Fields.Contains(SiteColumns.LetterGrade)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.LetterGrade]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Submissions)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Submissions]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.AssignmentDescription)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.AssignmentDescription]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.HomeworkAssignmentPointsRecievied)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.HomeworkAssignmentPointsRecievied]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.HomeworkAssignmentPointsAllowed)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.HomeworkAssignmentPointsAllowed]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Class)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Class]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Teacher))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Teacher]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Student))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }
            ct.Update(true);
        }
コード例 #37
0
        /// <summary>
        /// This Method Adds the Field to Content Tyee(s)
        /// </summary>
        /// <param name="Web">SPWeb</param>
        /// <param name="ColumnName">string</param>
        /// <param name="ContentTypes">string</param>
        private void AddColumnToContentTypes(SPWeb Web, string ColumnName, string ContentTypes)
        {
            ArrayList alFields = new ArrayList();
            int Position = 0;
            string[] _attributes;
            char[] commaSep = { ',' };
            SPField lookupColumn = Web.Fields.GetField(ColumnName);
            string contentTypeNames = ContentTypes.Replace("\"", "").Substring(ContentTypes.IndexOf('=') + 1);
            if (lookupColumn != null)
            {
                foreach (string contentTypeName in contentTypeNames.Split(commaSep, StringSplitOptions.RemoveEmptyEntries))
                {
                    _attributes = contentTypeName.Split('|');
                    Position = Convert.ToInt32(_attributes[2]);

                    SPContentType ObjContentTypes = Web.ContentTypes[_attributes[0]];
                    if (ObjContentTypes != null)
                    {
                        if (ObjContentTypes.FieldLinks[lookupColumn.Id] == null)
                        {
                            SPFieldLink _flLookUpColumn = new SPFieldLink(lookupColumn);
                            _flLookUpColumn.DisplayName = _attributes[1];
                            ObjContentTypes.FieldLinks.Add(_flLookUpColumn);
                            ObjContentTypes.Update(true);

                            //ReOrdering Site Column in the ContentType
                            //alFields.Clear();

                            //foreach (SPField field in ObjContentTypes.Fields)
                            //{
                            //    if (field.InternalName != "ContentType")
                            //    {
                            //        if (field.InternalName == lookupColumn.InternalName)
                            //        {
                            //            alFields.Insert(Position, field.InternalName);
                            //        }
                            //        else
                            //        {
                            //            alFields.Add(field.InternalName);
                            //        }
                            //    }
                            //}
                            //ObjContentTypes.FieldLinks.Reorder(alFields.ToArray(typeof(string)) as string[]);
                            //ObjContentTypes.Update(true);
                        }
                    }
                }
            }
        }
コード例 #38
0
 public ArtDevContentType AddFieldLink(ArtDevField field)
 {
     this.sPFields.Add(field.field);
     this.link = new SPFieldLink(field.field);
     return(this);
 }
コード例 #39
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite curSite;
            SPWeb  curWeb;

            properties.GetSiteAndWeb(out curSite, out curWeb);
            if (curSite != null && curWeb != null)
            {
                try
                {
                    #region Configure Doc Id Prefix
                    string prefix = "CCCM";
                    if (curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX))
                    {
                        prefix = curSite.RootWeb.Properties[eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX];
                    }

                    if (!curWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX))
                    {
                        curWeb.Properties.Add(eCaseConstants.PropertyBagKeys.ECASE_DOC_ID_PREFIX, prefix);
                        curWeb.Properties.Update();
                    }
                    #endregion

                    #region Configure Workflows to Associate
                    string workflowNames = eCaseConstants.PropertyBagDefaultValues.DEFAULT_WORKFLOW_NAMES;
                    if (!curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE))
                    {
                        curSite.RootWeb.Properties.Add(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE, workflowNames);
                        curSite.RootWeb.Properties.Update();
                    }
                    #endregion

                    // Activate Case Site Components feature at RootWeb if not already activated
                    try { curSite.Features.Add(eCaseConstants.FeatureIds.CASE_SITE_COMPONENTS); }
                    catch (System.Data.DuplicateNameException x)
                    {
                        Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}",
                                                           eCaseConstants.FeatureIds.CASE_SITE_COMPONENTS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb);
                    }

                    // Activate Standard Site Collection Features if not already activated
                    try { curSite.Features.Add(eCaseConstants.FeatureIds.LEGACY_WORKFLOWS); }
                    catch (System.Data.DuplicateNameException x)
                    {
                        Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}",
                                                           eCaseConstants.FeatureIds.WORKFLOWS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb);
                    }

                    // Activate 2010 Workflows feature if not already activated
                    try { curSite.Features.Add(eCaseConstants.FeatureIds.WORKFLOWS); }
                    catch (System.Data.DuplicateNameException x)
                    {
                        Logger.Instance.Info(string.Format("CaseWebComponentsEventReceiver.FeatureActivated: {0} already activated at {1}",
                                                           eCaseConstants.FeatureIds.WORKFLOWS.ToString(), curSite.Url), x, DiagnosticsCategories.eCaseWeb);
                    }

                    // Associate workflows from our property bag
                    if (curSite.RootWeb.Properties.ContainsKey(eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE))
                    {
                        var workFlows = curSite.RootWeb.Properties[eCaseConstants.PropertyBagKeys.ECASE_WORKFLOWS_TO_ASSOCIATE].Split('|');
                        //ActivateWorkflowFeatures(workFlows, curSite);
                        AssociateWithWorkFlows(workFlows, curSite, curWeb);
                    }

                    #region Create RelatedLegalIssues Lookup Site Column
                    SPFieldLookup relatedLegalIssuesLookup = null;
                    if (curWeb.Fields.ContainsFieldWithStaticName("RelLglIssues"))
                    {
                        relatedLegalIssuesLookup = curWeb.Fields.GetFieldByInternalName("RelLglIssues") as SPFieldLookup;
                    }
                    else
                    {
                        SPList legalIssuesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.LEGAL_ISSUES);
                        curWeb.Fields.AddLookup("RelLglIssues", legalIssuesList.ID, curWeb.ID, false);
                        relatedLegalIssuesLookup                     = curWeb.Fields["RelLglIssues"] as SPFieldLookup;
                        relatedLegalIssuesLookup.LookupField         = legalIssuesList.Fields[eCaseConstants.FieldGuids.OOTB_TITLE].InternalName;
                        relatedLegalIssuesLookup.AllowMultipleValues = true;
                        relatedLegalIssuesLookup.Group               = "eCases Site Columns";
                        relatedLegalIssuesLookup.Title               = "Legal Issues";
                        relatedLegalIssuesLookup.Update();
                    }
                    #endregion

                    int autoRefreshInterval = 60;
                    #region Referral Documents
                    SPList        caseDocsList    = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.REFERRAL_DOCUMENTS);
                    SPContentType caseDocCt       = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.CASE_DOCUMENT];
                    SPContentType caseDocCtChild  = caseDocsList.ContentTypes["Case Document"];
                    bool          caseDocsCtIsNew = (caseDocCtChild == null);
                    if (caseDocsCtIsNew)
                    {
                        caseDocCtChild = new SPContentType(caseDocCt, curWeb.ContentTypes, "Case Document");
                    }
                    SPFieldLink relatedLegalIssuesFLink = new SPFieldLink(relatedLegalIssuesLookup);
                    if (caseDocCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null)
                    {
                        caseDocCtChild.FieldLinks.Add(relatedLegalIssuesFLink);
                    }
                    if (caseDocsCtIsNew)
                    {
                        caseDocsList.ContentTypes.Add(caseDocCtChild);
                        caseDocsList.Update();
                    }

                    // Enable AJAX
                    using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(caseDocsList.DefaultViewUrl, PersonalizationScope.Shared))
                    {
                        XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart;
                        xsltListViewWp.AutoRefresh         = true;
                        xsltListViewWp.AutoRefreshInterval = autoRefreshInterval;
                        mgr.SaveChanges(xsltListViewWp);
                    }
                    #endregion

                    #region Investigation Documents
                    SPList        relatedDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.INVESTIGATION_DOCUMENTS);
                    SPContentType relDocCt        = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.INVESTIGATION_DOCUMENT];
                    SPContentType relDocCtChild   = relatedDocsList.ContentTypes["Related Document"];
                    bool          relDocCtIsNew   = (relDocCtChild == null);
                    if (relDocCtIsNew)
                    {
                        relDocCtChild = new SPContentType(relDocCt, curWeb.ContentTypes, "Related Document");
                    }
                    if (relDocCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null)
                    {
                        relDocCtChild.FieldLinks.Add(relatedLegalIssuesFLink);
                    }
                    if (relDocCtIsNew)
                    {
                        relatedDocsList.ContentTypes.Add(relDocCtChild);
                        relatedDocsList.Update();
                    }

                    // Enable AJAX
                    using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(relatedDocsList.DefaultViewUrl, PersonalizationScope.Shared))
                    {
                        XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart;
                        xsltListViewWp.AutoRefresh         = true;
                        xsltListViewWp.AutoRefreshInterval = autoRefreshInterval;
                        mgr.SaveChanges(xsltListViewWp);
                    }
                    #endregion

                    #region SDO Documents
                    SPList        finWorkProdDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.SDO_DOCUMENTS);
                    SPContentType finWorkProdCt       = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.SDO_DOCUMENT];
                    SPContentType finWorkProdCtChild  = finWorkProdDocsList.ContentTypes["Finished Work Product"];
                    bool          finWorkProdCtIsNew  = (finWorkProdCtChild == null);
                    if (finWorkProdCtIsNew)
                    {
                        finWorkProdCtChild = new SPContentType(finWorkProdCt, curWeb.ContentTypes, "Finished Work Product");
                    }
                    if (finWorkProdCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null)
                    {
                        finWorkProdCtChild.FieldLinks.Add(relatedLegalIssuesFLink);
                    }
                    if (finWorkProdCtIsNew)
                    {
                        finWorkProdDocsList.ContentTypes.Add(finWorkProdCtChild);
                        finWorkProdDocsList.Update();
                    }

                    // Enable AJAX
                    using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(finWorkProdDocsList.DefaultViewUrl, PersonalizationScope.Shared))
                    {
                        XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart;
                        xsltListViewWp.AutoRefresh         = true;
                        xsltListViewWp.AutoRefreshInterval = autoRefreshInterval;
                        mgr.SaveChanges(xsltListViewWp);
                    }
                    #endregion

                    #region Share With External User
                    SPList        shareExternalUserDocsList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.SHARE_WITH_EXTERNAL_USERS);
                    SPContentType shareExternalUserCt       = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.SHARE_WITH_EXTERNAL_USER];
                    SPContentType shareExternalUserCtChild  = shareExternalUserDocsList.ContentTypes["ShareWithExternalUser"];
                    bool          shareExternalUserCtIsNew  = (shareExternalUserCtChild == null);
                    if (shareExternalUserCtIsNew)
                    {
                        shareExternalUserCtChild = new SPContentType(shareExternalUserCt, curWeb.ContentTypes, "ShareWithExternalUser");
                    }
                    if (shareExternalUserCtChild.FieldLinks[relatedLegalIssuesFLink.Name] == null)
                    {
                        shareExternalUserCtChild.FieldLinks.Add(relatedLegalIssuesFLink);
                    }
                    if (shareExternalUserCtIsNew)
                    {
                        shareExternalUserDocsList.ContentTypes.Add(shareExternalUserCtChild);
                        shareExternalUserDocsList.Update();
                    }

                    // Enable AJAX
                    using (SPLimitedWebPartManager mgr = curWeb.GetLimitedWebPartManager(shareExternalUserDocsList.DefaultViewUrl, PersonalizationScope.Shared))
                    {
                        XsltListViewWebPart xsltListViewWp = mgr.WebParts[0] as XsltListViewWebPart;
                        xsltListViewWp.AutoRefresh         = true;
                        xsltListViewWp.AutoRefreshInterval = autoRefreshInterval;
                        mgr.SaveChanges(xsltListViewWp);
                    }
                    #endregion

                    #region Related Dates -- NEVER GOT DONE PROPERLY, BUT DOES FUNCTION FOR THESE LISTS
                    //SPContentType relDatesCt = curSite.RootWeb.ContentTypes[eCaseConstants.ContentTypeIds.RELATED_DATES];
                    //SPContentType relDatesCtChild = new SPContentType(relDatesCt, curWeb.ContentTypes, "Related Date");
                    //relDatesCtChild.FieldLinks.Add(relatedLegalIssuesFLink);

                    //SPList caseRelatedDatesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.CASE_RELATED_DATES);
                    //SPContentTypeId ootbEvent = new SPContentTypeId("0x0102");
                    //caseRelatedDatesList.ContentTypes.Add(relDatesCtChild);
                    ////caseRelatedDatesList.ContentTypes.Delete(ootbEvent);
                    //caseRelatedDatesList.Update();

                    //SPList matterRelatedDatesList = curWeb.GetListByInternalName(eCaseConstants.ListInternalNames.MATTER_RELATED_DATES);
                    //matterRelatedDatesList.ContentTypes.Add(relDatesCtChild);
                    ////matterRelatedDatesList.ContentTypes.Delete(ootbEvent);
                    //matterRelatedDatesList.Update();
                    #endregion

                    // Use Custom Logo for Site
                    curWeb.SiteLogoUrl = curSite.RootWeb.Url + "/Style%20Library/images/ecase-logo.png";

                    // Push all new content types to the SPWeb collection
                    curWeb.Update();
                }
                catch (Exception x)
                {
                    Logger.Instance.Error("CaseWebComponents FeatureActivation Failure", x, DiagnosticsCategories.eCaseWeb);
                    throw x;
                }
            }
            else // Something is very wrong -- lets throw
            {
                string obj;
                if (curSite == null)
                {
                    obj = "SPSite";
                }
                else
                {
                    obj = "SPWeb";
                }

                string exceptionMsg = string.Format("Feature activation did not complete successfully.  Unable to find {0} object", obj);
                throw new Exception(exceptionMsg);
            }
        }
コード例 #40
0
ファイル: Utility.cs プロジェクト: iburykin/SFPU-Branding
 public static void AddFieldToContentType(SPWeb web, SPContentTypeId contentTypeId, SPField field)
 {
     SPContentType contentType = web.ContentTypes[contentTypeId];
     if (contentType == null) return;
     if (contentType.Fields.ContainsField(field.Title)) return;
     SPFieldLink fieldLink = new SPFieldLink(field);
     contentType.FieldLinks.Add(fieldLink);
     contentType.Update();
 }
コード例 #41
0
 public ArtDevContentType GetFieldLink(Guid guid)
 {
     this.link = this.type.FieldLinks[guid];
     return(this);
 }
コード例 #42
0
 /// <summary>
 /// Fields the exist.
 /// </summary>
 /// <param name="contentType">Type of the content.</param>
 /// <param name="fieldLink">The field link.</param>
 /// <returns></returns>
 private static bool FieldExist(SPContentType contentType, SPFieldLink fieldLink)
 {
     try
     {
         //will throw exception on missing fields
         return contentType.Fields[fieldLink.Id] != null;
     }
     catch (Exception)
     {
         return false;
     }
 }
コード例 #43
0
        private static bool AddFieldToContentType(SPContentType contentType, SPField field, bool updateContentType, RequiredType isRequired)
        {
            // Create the field ref.
            SPFieldLink fieldOneLink = new SPFieldLink(field);
            if (contentType.FieldLinks[fieldOneLink.Id] == null)
            {
                // Set the RequiredType value on the Content Type
                switch (isRequired)
                {
                    case RequiredType.Required:
                        fieldOneLink.Required = true;
                        break;
                    case RequiredType.NotRequired:
                        fieldOneLink.Required = false;
                        break;
                    case RequiredType.Inherit:
                    default:
                        // Do nothing, it will inherit from the Field definition
                        break;
                }

                // Field is not in the content type so we add it.
                contentType.FieldLinks.Add(fieldOneLink);

                // Update the content type.
                if (updateContentType)
                {
                    contentType.Update(true);
                }

                return true;
            }

            return false;
        }
コード例 #44
0
 /// <summary>
 /// Add Column Site of Content Type
 /// </summary>
 /// <param name="name">name of column</param>
 /// <returns></returns>
 public bool AddColumn(string name)
 {
     try
     {
         
         var contentType = Web.ContentTypes[Name];
         var field = GetField(name, Web);
         var fieldLink = new SPFieldLink(field);
         if (contentType.FieldLinks[fieldLink.Id] == null)
         {
             contentType.FieldLinks.Add(fieldLink);
         }
         contentType.Update(true);
         
     }
     catch (Exception exception)
     {
         Logger.Error(string.Concat("Add Column ContentType: ", exception.Message));
         return false;
     }
     return true;
 }
コード例 #45
0
        private void UpdateMetaFields()
        {
            try
            {
                GetMetaFields();

                SPContext.Current.Site.CatchAccessDeniedException = false;
                //SPWebCollection webs = SPContext.Current.Site.AllWebs;
                SPWeb web = SPContext.Current.Web;
                //foreach (SPWeb web in webs)
                //{
                try
                {
                    if (web.DoesUserHavePermissions((SPBasePermissions.ManageLists | SPBasePermissions.ManageWeb)))
                    {
                        web.AllowUnsafeUpdates = true;
                        web.Update();

                        GetPublishingTypes(web);

                        foreach (SPContentType content in publishingtypes)
                        {
                            foreach (SPField oField in metafields)
                            {
                                if (!content.Fields.Contains(oField.Id))
                                {
                                    string fieldname = SharePointWebControls.GetFieldName(oField);
                                    try
                                    {
                                        SPFieldLink fieldRef = new SPFieldLink(oField);
                                        fieldRef.DisplayName       = fieldname;
                                        fieldRef.Required          = false;
                                        fieldRef.ShowInDisplayForm = false;
                                        fieldRef.Hidden            = true;

                                        content.FieldLinks.Add(fieldRef);
                                        content.Update();
                                    }
                                    catch { };
                                }
                            }
                        }

                        SPListCollection lists = web.Lists;
                        //foreach (SPList list in web.Lists)
                        for (int i = 0; i < lists.Count; i++)
                        {
                            GetPublishingTypes(lists[i]);
                            foreach (SPContentType content in publishingtypes)
                            {
                                foreach (SPField oField in metafields)
                                {
                                    if (!content.Fields.Contains(oField.Id))
                                    {
                                        string fieldname = SharePointWebControls.GetFieldName(oField);
                                        try
                                        {
                                            SPFieldLink fieldRef = new SPFieldLink(oField);
                                            fieldRef.DisplayName       = fieldname;
                                            fieldRef.Required          = false;
                                            fieldRef.ShowInDisplayForm = false;
                                            fieldRef.Hidden            = true;

                                            content.FieldLinks.Add(fieldRef);
                                            content.Update();
                                        }
                                        catch { };
                                    }
                                }
                            }
                            lists[i].Update();
                        }

                        //web.AllowUnsafeUpdates = false;
                        //SPUtility.ValidateFormDigest();
                        //web.Update();
                    }
                }
                catch (Exception ex)
                {
                    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                }
                finally
                {
                    SPContext.Current.Site.CatchAccessDeniedException = true;
                    web.AllowUnsafeUpdates = false;
                }

                //}
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }
            finally
            {
                SPContext.Current.Site.CatchAccessDeniedException = true;
            }
        }
コード例 #46
0
        void btn_Update_Click(object sender, EventArgs e)
        {
            GetMetaFields();

            SPWebCollection webs = SPContext.Current.Site.AllWebs;

            foreach (SPWeb web in webs)
            {
                web.AllowUnsafeUpdates = true;
                web.Update();

                GetPublishingTypes(web);

                foreach (SPContentType content in publishingtypes)
                {
                    foreach (SPField oField in metafields)
                    {
                        if (!content.Fields.Contains(oField.Id))
                        {
                            string fieldname = SharePointWebControls.GetFieldName(oField);
                            try
                            {
                                SPFieldLink fieldRef = new SPFieldLink(oField);
                                fieldRef.DisplayName       = fieldname;
                                fieldRef.Required          = false;
                                fieldRef.ShowInDisplayForm = false;
                                fieldRef.Hidden            = true;

                                content.FieldLinks.Add(fieldRef);
                                content.Update();
                            }
                            catch { };
                        }
                    }
                }

                SPListCollection lists = web.Lists;
                //foreach (SPList list in web.Lists)
                for (int i = 0; i < lists.Count; i++)
                {
                    GetPublishingTypes(lists[i]);
                    foreach (SPContentType content in publishingtypes)
                    {
                        foreach (SPField oField in metafields)
                        {
                            if (!content.Fields.Contains(oField.Id))
                            {
                                string fieldname = SharePointWebControls.GetFieldName(oField);
                                try
                                {
                                    SPFieldLink fieldRef = new SPFieldLink(oField);
                                    fieldRef.DisplayName       = fieldname;
                                    fieldRef.Required          = false;
                                    fieldRef.ShowInDisplayForm = false;
                                    fieldRef.Hidden            = true;

                                    content.FieldLinks.Add(fieldRef);
                                    content.Update();
                                }
                                catch { };
                            }
                        }
                    }
                    lists[i].Update();
                }

                web.AllowUnsafeUpdates = false;
                web.Update();
            }
        }
コード例 #47
0
        private static void CreateAContentType()
        {
            SPList listFields;
            SPWeb myWeb;
            SPSite myDemoSite = new SPSite("http://abcuniversity");

            Console.WriteLine("Talking to SharePoint, Don't Go Anywhere.");

            myWeb = myDemoSite.OpenWeb();
            listFields = myWeb.Lists.TryGetList("CustomizableList");

            List<SPField> fieldsForContentType = new List<SPField>();
            string[] fieldsIWantToAdd = {"AnnualSalary", "SportType", "CurrentStatus"};
            foreach(SPField field in listFields.Fields)
            {
                //Console.WriteLine("Field name: {0}, \nField ID: {1}\nField Group: {2}\n",
                    //field.StaticName, field.Id.ToString(),field.Group);

                //3 differencet ways of adding fields
                //-1- Adding field directly to list using ADD()
                string newFieldA = null, newFieldB = null, newFieldC = null;
                if(listFields.Fields.ContainsField("CurrentTeam") == false)
                {
                    Console.WriteLine("Adding CurrentTeam...");
                    newFieldA = listFields.Fields.Add("CurrentTeam", SPFieldType.Text, false);
                    Console.WriteLine("Added CurrentTeam column to list");
                }
                else
                {
                    Console.WriteLine("Added CurrentTeam column to list.");
                }

                //-and2- Adding the same field to site columns ausing SPField object and target list.
                if (listFields.Fields.ContainsField("PlayerPosition") == false)
                {
                    SPField addANewField = listFields.Fields.CreateNewField("Text", "PlayerPosition");
                    addANewField.Description = "This position, will vary by sport.";

                    //Add it to the Web first... We should probably do the duplication here, too...
                    myWeb.Fields.Add(addANewField);
                    newFieldB = listFields.Fields.Add(addANewField);
                    Console.WriteLine("PlayerPosition column added to the list...");

                }
                else
                {
                    Console.WriteLine("Added PlayerPosition column to list.");
                }
                
                //-and3!- //Using System.Collections to create and add choice field
                if(listFields.Fields.ContainsField("MyPeronalField") == false)
                {
                    System.Collections.Specialized.StringCollection choices = new System.Collections.Specialized.StringCollection();
                    choices.AddRange(new string[] {"Healthy","Out","Likely","Probable"});
                    //Add("DisplayName",FieldType,Required,CompactName,choicelist
                    newFieldC = listFields.Fields.Add("MyPeronalField", SPFieldType.Choice, false, false, choices);
                    Console.WriteLine("MyPeronalField field added to the list...");

                }
                else
                {
                    Console.WriteLine("MyPeronalField not added, already part of the list...");
                }



                /*//If its one of the fields we're interested in, add it to our collection
                if(fieldsIWantToAdd.Contains(field.StaticName))
                {
                    fieldsForContentType.Add(field);
                }*/



            }//end foreach

            SPContentTypeCollection allMyContent = myWeb.ContentTypes;
            SPContentType newContentType = new SPContentType(
                    allMyContent["item"], allMyContent, "TestContentType");
            allMyContent.Add(newContentType);

            string newField1 = myWeb.Fields.Add("AnnualSalary", SPFieldType.Number, false);
            SPFieldLink newField1Link = new SPFieldLink(myWeb.Fields.GetField(newField1));
            newContentType.FieldLinks.Add(newField1Link);

            string newField2 = myWeb.Fields.Add("CurrentStatus", SPFieldType.Text, false);
            SPFieldLink newField2Link = new SPFieldLink(myWeb.Fields.GetField(newField2));
            newContentType.FieldLinks.Add(newField2Link);

            string newField3 = myWeb.Fields.Add("SportType", SPFieldType.Text, false);
            SPFieldLink newField3Link = new SPFieldLink(myWeb.Fields.GetField(newField3));
            newContentType.FieldLinks.Add(newField3Link);

            //newContentType.Update();

        }
コード例 #48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Declare Fields

            var site = SPContext.Current.Site;
            var web  = site.RootWeb;
            // Get the SPFieldCollection for the root web.
            var fields = web.Fields;
            // Add a new date field.
            var fieldExpiryDate = new SPFieldDateTime(fields, SPFieldType.DateTime.ToString(), "Expiry Date")
            {
                StaticName    = "ExpiryDate",
                DisplayFormat = SPDateTimeFieldFormatType.DateOnly,
                Group         = "Contoso Columns",
                Required      = true
            };

            fieldExpiryDate.Update();
            fields.Add(fieldExpiryDate);

            // Add a new choice field.
            var fieldProductionType = new SPFieldChoice(fields, SPFieldType.Choice.ToString(), "Production Type")
            {
                StaticName = "ProductionType"
            };

            fieldProductionType.Choices.Add("Research");
            fieldProductionType.Choices.Add("Prototype");
            fieldProductionType.Choices.Add("Trial");
            fieldProductionType.Choices.Add("Release");
            fieldProductionType.Group    = "Contoso Columns";
            fieldProductionType.Required = true;
            fieldProductionType.Update();
            fields.Add(fieldProductionType);

            // Declare Content Types

            // Get the ID of the parent content type.
            var parentId = SPBuiltInContentTypeId.Document;
            // Create the Invoice content type.
            var ctInvoice = new SPContentType(parentId, web.ContentTypes, "Invoice");
            // Create field links.
            var fldClientName         = fields.GetField("ClientName");
            var fldPaymentDueDate     = fields.GetField("PaymentDueDate");
            var fldAmount             = fields.GetField("Amount");
            var fldLinkClientName     = new SPFieldLink(fldClientName);
            var fldLinkPaymentDueDate = new SPFieldLink(fldPaymentDueDate);
            var fldLinkAmount         = new SPFieldLink(fldAmount);

            // Add the field links to the content type.
            ctInvoice.FieldLinks.Add(fldLinkClientName);
            ctInvoice.FieldLinks.Add(fldLinkPaymentDueDate);
            ctInvoice.FieldLinks.Add(fldLinkAmount);
            // Persist the changes to the content database.
            ctInvoice.Update();
            // Add the content type to the collection.
            web.ContentTypes.Add(ctInvoice);
            web.Dispose();

            // Bind Content Type

            // Get the list.
            var list = web.GetList("Invoices");
            // Get the site content type.
            var ct = web.AvailableContentTypes["Invoice"];

            // Enable content types on the list.
            list.ContentTypesEnabled = true;
            // Add the content type to the list.
            list.ContentTypes.Add(ct);
            // Persist the changes to the database.
            list.Update();

            //Set Document Template

            ct.DocumentTemplate = "SiteAssets/MyTemplate.dotx";
            ct.Update();

            //Set Workflow Template

            SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByName("InvoiceWorkflow", web.Locale);

            // Create a new workflow association.
            SPWorkflowAssociation association = SPWorkflowAssociation.CreateWebContentTypeAssociation(template, "Process Invoice", "Invoice Tasks", "Process Invoice History");

            if (ct.WorkflowAssociations.GetAssociationByName("Process Invoice", web.Locale) == null)
            {
                ct.WorkflowAssociations.Add(association);
                ct.UpdateWorkflowAssociationsOnChildren(false, true, true, false);
            }
        }