示例#1
0
        private void ConsistantLookup(SPWeb web, SPList list)
        {
            try
            {
                SPFieldLookup lookupField = (SPFieldLookup)list.Fields["Parent"];

                if (string.IsNullOrEmpty(lookupField.LookupList))
                {
                    if (lookupField.LookupWebId != web.ID)
                    {
                        lookupField.LookupWebId = web.ID;
                    }
                    if (lookupField.LookupList != list.ID.ToString())
                    {
                        lookupField.LookupList = list.ID.ToString();
                    }
                }
                else
                {
                    string schema = lookupField.SchemaXml;
                    schema = ReplaceXmlAttributeValue(schema, "List", list.ID.ToString());
                    schema = ReplaceXmlAttributeValue(schema, "WebId", web.ID.ToString());
                    lookupField.SchemaXml = schema;
                }
                lookupField.Update(true);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                //ex.ToString();
            }
        }
        public static void EnsureLookUpField(this SPList list, string fieldName, string lookupListName, string lookUpFieldName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!list.Fields.ContainsField(fieldName))
                    {
                        var lookupListID = list.ParentWeb.Lists.TryGetList(lookupListName).ID;
                        var field        = list.Fields.AddLookup(fieldName, lookupListID, false);

                        var listLook = list.ParentWeb.TryGetList(lookupListName);

                        var lookUp = new SPFieldLookup(list.Fields, field);

                        lookUp.LookupField = listLook.TryGetField(lookUpFieldName).InternalName;
                        lookUp.Indexed     = true;
                        lookUp.Update();
                        list.Update();
                    }
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
示例#3
0
        /// <summary>
        /// Usage:

        ///    SPFieldLookup field = (SPFieldLookup)site.RootWeb.Fields[MyId];
        ///    field.UpdateLookupReferences(newWeb, newList)indexOfAttributeName ;
        /// </summary>
        /// <param name="lookupField"></param>
        /// <param name="web"></param>
        /// <param name="list"></param>
        public static void UpdateLookupReferences(this SPFieldLookup lookupField, SPWeb web, SPList list)
        {
            try
            {
                web.AllowUnsafeUpdates = true;

                if (string.IsNullOrEmpty(lookupField.LookupList))
                {
                    lookupField.LookupWebId = web.ID;
                    lookupField.LookupList  = list.ID.ToString();
                }
                else
                {
                    //lookupField.SchemaXml =
                    //    lookupField.SchemaXml
                    //        .ReplaceXmlAttributeValue("List", list.ID.ToString())
                    //        .ReplaceXmlAttributeValue("WebId", web.ID.ToString());

                    lookupField.SchemaXml =
                        lookupField.SchemaXml
                        .EnsureXmlAttribute("List", list.ID.ToString())
                        .EnsureXmlAttribute("WebId", web.ID.ToString());
                }

                lookupField.Update(true);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
示例#4
0
        public static void UpdateLookupReferences(this SPFieldLookup lookupField, SPList lookupList, string lookupName)
        {
            if (string.IsNullOrEmpty(lookupField.LookupList))
            {
                lookupField.LookupWebId = lookupList.ParentWeb.ID;
                lookupField.LookupList  = lookupList.ID.ToString();

                if (!string.IsNullOrEmpty(lookupName))
                {
                    lookupField.LookupField = lookupName;
                }
            }
            else
            {
                XElement fieldSchema = XElement.Parse(lookupField.SchemaXml);

                ChangeAttribute(fieldSchema, "WebId", lookupList.ParentWeb.ID);
                ChangeAttribute(fieldSchema, "List", lookupList.ID);

                if (!string.IsNullOrEmpty(lookupName))
                {
                    ChangeAttribute(fieldSchema, "ShowField", lookupName);
                }

                lookupField.SchemaXml = fieldSchema.ToString(SaveOptions.DisableFormatting);
            }

            lookupField.Update(true);
        }
        private void ConsistantLookup(SPList navigation)
        {
            SPFieldLookup lookupField = (SPFieldLookup)navigation.Fields["Parent"];

            if (string.IsNullOrEmpty(lookupField.LookupList))
            {
                if (lookupField.LookupWebId != navigation.ParentWeb.ID)
                {
                    lookupField.LookupWebId = navigation.ParentWeb.ID;
                }
                if (lookupField.LookupList != navigation.ID.ToString())
                {
                    lookupField.LookupList = navigation.ID.ToString();
                }
            }
            else
            {
                string schema = lookupField.SchemaXml;
                schema = ReplaceXmlAttributeValue(schema, "List", navigation.ID.ToString());
                schema = ReplaceXmlAttributeValue(schema, "WebId", navigation.ID.ToString());
                lookupField.SchemaXml = schema;
            }

            lookupField.Update(true);
        }
示例#6
0
        public override void OnAdded(SPAddFieldOptions op)
        {
            using (new EnterExitLogger("CCSCascadedLookupField:OnAdded function"))
            {
                base.OnAdded(op);
                Update();

                if (!string.IsNullOrEmpty(AdditionalFields))
                {
                    string[] AdditionalFieldsArray = AdditionalFields.Split(new string[] { ";#" }, StringSplitOptions.None);
                    if (AdditionalFieldsArray.Length > 1)
                    {
                        for (int i = 0; i < AdditionalFieldsArray.Length - 1; i += 2)
                        {
                            if (!this.ParentList.Fields.ContainsField(this.Title + " : " + AdditionalFieldsArray[i]))
                            {
                                //create a new field
                                string        depLookUp      = this.ParentList.Fields.AddDependentLookup(this.Title + " : " + AdditionalFieldsArray[i], this.Id);
                                SPFieldLookup fieldDepLookup = (SPFieldLookup)this.ParentList.Fields.GetFieldByInternalName(depLookUp);

                                if (fieldDepLookup != null)
                                {
                                    fieldDepLookup.LookupWebId = this.LookupWebId;
                                    fieldDepLookup.LookupField = AdditionalFieldsArray[i + 1];
                                    fieldDepLookup.Update();
                                }
                            }
                        }
                    }
                }
            }
        }
示例#7
0
        /// <summary>
        /// 如果活动列表不存在,自动创建
        /// </summary>
        private SPList CreateActivityList(Guid siteID, Guid webID, string lstTitle, string desc, string lookupListTitle)
        {
            SPList retList = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPWeb oWebsite = new SPSite(siteID).AllWebs[webID])
                {
                    oWebsite.AllowUnsafeUpdates = true;
                    try
                    {
                        oWebsite.Lists.Add(lstTitle, desc, SPListTemplateType.GenericList);

                        SPList list = oWebsite.Lists[lstTitle];

                        SPField myField = list.Fields.GetFieldByInternalName("Title");
                        myField.Title   = "活动名称";
                        myField.Update();

                        list.Fields.Add("活动类型", SPFieldType.Text, false);
                        list.Fields.Add("活动地点", SPFieldType.Text, false);
                        list.Fields.Add("活动对象", SPFieldType.Text, false);
                        list.Fields.Add("开始时间", SPFieldType.DateTime, false);
                        list.Fields.Add("持续时长", SPFieldType.Integer, false);
                        list.Fields.Add("执行者", SPFieldType.User, false);
                        list.Fields.Add("活动描述", SPFieldType.Text, false);
                        list.Fields.Add("作品地址", SPFieldType.Text, false);

                        string fieldName  = "计划ID";                                       //新增的Lookup类型字段的名字
                        SPList lookupList = oWebsite.Lists[lookupListTitle];              //设置这个Lookup类型字段要从哪个List中去取值
                        Guid lookupGuid   = new Guid(lookupList.ID.ToString());           // 取得这个Lookup数据源List的Guid
                        list.Fields.AddLookup(fieldName, lookupGuid, false);              //把上面取得的参数引入到AddLookup方法中,从而创建一个Lookup字段
                        SPFieldLookup splookup = list.Fields[fieldName] as SPFieldLookup; //绑定数据List到Lookup字段
                        splookup.LookupField   = "Title";
                        splookup.Update();

                        SPView defaultView = list.Views[0];

                        defaultView.ViewFields.Add(list.Fields["活动地点"]);
                        defaultView.ViewFields.Add(list.Fields["活动类型"]);
                        defaultView.ViewFields.Add(list.Fields["活动对象"]);
                        defaultView.ViewFields.Add(list.Fields["开始时间"]);
                        defaultView.ViewFields.Add(list.Fields["持续时长"]);
                        defaultView.ViewFields.Add(list.Fields["执行者"]);
                        defaultView.ViewFields.Add(list.Fields["活动描述"]);
                        defaultView.ViewFields.Add(list.Fields["作品地址"]);
                        defaultView.ViewFields.Add(list.Fields["计划ID"]);
                        defaultView.Update();
                        list.Update();
                        retList = list;
                    }
                    catch
                    {
                    }
                    oWebsite.AllowUnsafeUpdates = false;
                }
            });
            return(retList);
        }
        private void RestrictDeleteOnLookupField(SPWeb web, string listUrl, Guid fieldGuid)
        {
            SPList        list        = web.GetList(GetListUrl(web.ServerRelativeUrl, listUrl));
            SPField       field       = list.Fields[fieldGuid];
            SPFieldLookup fieldLookup = (SPFieldLookup)field;

            fieldLookup.Indexed = true;
            fieldLookup.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;
            fieldLookup.Update();
        }
示例#9
0
        internal void EnsureAdditionalFields(string fields, string unchecked_fields)
        {
            base.ParentList.Update();

            SPWeb  w    = SPContext.Current.Site.OpenWeb(this.LookupWebId);
            SPList list = w.Lists[new Guid(this.LookupList)];

            if (fields.Length > 0)
            {
                foreach (string str2 in fields.Split(';'))
                {
                    string str3 = this.Title + ":" + list.Fields[new Guid(str2)].Title;
                    if (str3.Length > 0x20)
                    {
                        str3 = str3.Substring(0, 0x20);
                    }

                    SPList list3 = base.ParentList;
                    if (!list3.Fields.ContainsField(str3))
                    {
                        list3.Fields.AddLookup(str3, new Guid(this.LookupList), false);
                    }
                    SPFieldLookup lookup2 = (SPFieldLookup)list3.Fields[str3];
                    lookup2.Title         = str3;
                    lookup2.LookupField   = str2;
                    lookup2.LookupWebId   = this.LookupWebId;
                    lookup2.ReadOnlyField = false;
                    lookup2.UnlimitedLengthInDocumentLibrary = base.UnlimitedLengthInDocumentLibrary;
                    lookup2.AllowMultipleValues = this.AllowMultipleValues;
                    lookup2.ShowInDisplayForm   = true;
                    lookup2.ShowInListSettings  = true;
                    lookup2.ShowInViewForms     = true;
                    lookup2.ShowInNewForm       = false;
                    lookup2.ShowInEditForm      = false;
                    lookup2.Update();
                }
            }
            if (unchecked_fields.Length > 0)
            {
                foreach (string str2 in unchecked_fields.Split(';'))
                {
                    string str3 = this.Title + ":" + list.Fields[new Guid(str2)].Title;
                    if (str3.Length > 0x20)
                    {
                        str3 = str3.Substring(0, 0x20);
                    }

                    SPList list3 = base.ParentList;
                    if (list3.Fields.ContainsField(str3))
                    {
                        list3.Fields[str3].Delete();
                    }
                }
            }
        }
示例#10
0
        static void Main(string[] args)
        {
            string personListName = "Person";

            string[] jobs   = { "Developer", "Admin", "Organization" };
            string[] skills = { "C#", "TypeScript", "React" };

            SPSite col = new SPSite("http://SP2016");
            SPWeb  web = col.RootWeb;

            SPList list = web.Lists.TryGetList(personListName);

            if (list == null)
            {
                var skillslist = addListWithItems(web, "Skills", "A skills List", skills);
                var joblist    = addListWithItems(web, "Jobs", "A job List", jobs);

                Guid id = web.Lists.Add(personListName, "A Person List", SPListTemplateType.GenericList);
                list = web.Lists.TryGetList(personListName);

                var           jobCol    = list.Fields.AddLookup("Jobs", joblist.ID, true);
                SPFieldLookup jobLookup = (SPFieldLookup)list.Fields[jobCol];
                jobLookup.LookupField = joblist.Fields["Title"].InternalName;
                jobLookup.Title       = "Job";
                jobLookup.Update();
                list.Update();

                var           skillCol    = list.Fields.AddLookup("Skills", skillslist.ID, true);
                SPFieldLookup skillLookup = (SPFieldLookup)list.Fields[skillCol];
                skillLookup.LookupField         = skillslist.Fields["Title"].InternalName;
                skillLookup.Title               = "Skills";
                skillLookup.AllowMultipleValues = true;
                skillLookup.Update();
                list.Update();

                var person = list.Items.Add();
                person["Title"] = "Bob der Baumeister";
                person["Job"]   = new SPFieldLookupValue(1, jobs[0]);
                var sks = new SPFieldLookupValueCollection
                {
                    new SPFieldLookupValue(1, skills[0]),
                    new SPFieldLookupValue(3, skills[2])
                };
                person["Skills"] = sks;
                person.Update();
            }

            foreach (SPListItem item in list.Items)
            {
                SPFieldLookupValue job          = new SPFieldLookupValue(item["Job"].ToString());
                string             skillsString = GetSkills(item);
                Console.WriteLine("{0} works as a {1} with skills {2}", item["Title"], job.LookupValue, skillsString);
            }
        }
示例#11
0
        // 取消对以下方法的注释,以便处理激活某个功能后引发的事件。

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //SPSite site = (SPSite)properties.Feature.Parent;
            using (SPWeb web = (SPWeb)properties.Feature.Parent)//site.RootWeb;
            {
                List <string> fields = new List <string>();
                foreach (SPField field in web.Fields)
                {
                    if (field.Group.Equals("Custom Lookup"))
                    {
                        fields.Add(field.InternalName);
                    }
                }

                foreach (string fieldName in fields)
                {
                    SPField   field       = web.Fields.GetField(fieldName);
                    XDocument fieldSchema = XDocument.Parse(field.SchemaXml);
                    XElement  root        = fieldSchema.Root;
                    if (root.Attribute("List") != null)
                    {
                        // 得到List对应的url
                        string listurl = root.Attribute("List").Value;

                        SPFolder      listFolder  = web.GetFolder(listurl);
                        SPFieldLookup lookupField = field as SPFieldLookup;
                        Guid          g           = Guid.Empty;
                        if (!Guid.TryParse(lookupField.LookupList, out g))
                        {
                            try
                            {
                                Type       t     = typeof(SPField);
                                MethodInfo mInfo = t.GetMethod("SetFieldAttributeValue", BindingFlags.NonPublic | BindingFlags.Instance);
                                mInfo.Invoke(lookupField, new object[] { "List", "" });

                                //mInfo.Invoke(lookupField, new object[] { "SourceID", web.ID.ToString() });
                                //lookupField.LookupList = listFolder.ParentListId.ToString();
                                lookupField.Update();
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }

                InitSPList(web);
            }
        }
示例#12
0
 public static void UpdateTargetList(this SPFieldLookup field, string targetListId)
 {
     try
     {
         if (!field.SchemaXml.Contains(targetListId))
         {
             field.SchemaXml = ReplaceXmlAttributeValue(field.SchemaXml, "List", targetListId);
             field.Update();
         }
     }
     catch {
         Utility.LogInfo("The field : " + field.Title + " doesn't exit in target list id" + targetListId, "AIA.Intranet.Common");
         /*field is not existed*/
     }
 }
        static void Main(string[] args)
        {
            string lookupFieldName = "RelatedField";

            using (SPSite site = new SPSite("http://sharepointserve"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPListCollection lists        = web.Lists;
                    Guid             SourceListId = lists.Add("Parent List",
                                                              "",
                                                              SPListTemplateType.GenericList);
                    Console.WriteLine("Parent List Done...");
                    Guid TargetListId = lists.Add("Child List",
                                                  "",
                                                  SPListTemplateType.GenericList);
                    Console.WriteLine("Child List Done...");
                    SPList            SourceList = lists[SourceListId];
                    SPList            TargetList = lists[TargetListId];
                    SPFieldCollection Fields     = TargetList.Fields;
                    Fields.AddLookup(lookupFieldName, SourceList.ID, true);
                    Console.WriteLine("Lookup Field Created");
                    SPFieldLookup NewLookupField = Fields[lookupFieldName] as SPFieldLookup;
                    NewLookupField.Indexed     = true;
                    NewLookupField.LookupField = "Title";
                    NewLookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;
                    NewLookupField.Update();
                    Console.WriteLine("Lookup field integrity enforced");
                    SPListItem NewSourceItem = SourceList.Items.Add();
                    NewSourceItem["Title"] = "Parent Data";
                    NewSourceItem.Update();
                    Console.WriteLine("Source listitem created");
                    SPListItem NewTargetItem = TargetList.Items.Add();
                    NewTargetItem["Title"]         = "Child Data";
                    NewTargetItem[lookupFieldName] = new SPFieldLookupValue(1, "Source Data");
                    NewTargetItem.Update();
                    Console.WriteLine("Parent listitem created");
                    TargetList.Update();
                    SourceList.Update();
                }
            }
            Console.ReadLine();
        }
示例#14
0
        static SPList CreateProductList(SPWeb web, SPList lstCategories, SPList lstSuppliers)
        {
            SPList list = CreateList(web, "Products");

            list.Fields.Add("ProductName", SPFieldType.Text, true);
            list.Fields.Add("QuantityPerUnit", SPFieldType.Text, false);
            list.Fields.Add("UnitPrice", SPFieldType.Currency, false);
            list.Fields.Add("UnitsInStock", SPFieldType.Number, false);
            list.Fields.Add("UnitsOnOrder", SPFieldType.Number, false);
            list.Fields.Add("ReorderLevel", SPFieldType.Number, false);
            list.Fields.Add("Discontinued", SPFieldType.Boolean, false);
            list.Fields.AddLookup("Category", lstCategories.ID, false);
            list.Fields.AddLookup("Supplier", lstSuppliers.ID, false);

            list.Update();

            SPFieldLookup category = new SPFieldLookup(list.Fields, "Category");
            category.LookupField = "CategoryName";
            category.Update();

            SPFieldLookup supplier = new SPFieldLookup(list.Fields, "Supplier");
            supplier.LookupField = "CompanyName";
            supplier.Update();

            list.Update();

            StringCollection fields = new StringCollection();
            fields.Add("ProductName");
            fields.Add("QuantityPerUnit");
            fields.Add("UnitPrice");
            fields.Add("UnitsInStock");
            fields.Add("UnitsOnOrder");
            fields.Add("ReorderLevel");
            fields.Add("Discontinued");
            fields.Add("Category");
            fields.Add("Supplier");

            SPView view = list.Views.Add("My view", fields, list.DefaultView.Query, list.DefaultView.RowLimit, list.DefaultView.Paged, true);
            view.Update();

            return list;
        }
示例#15
0
        protected void AddLookupFieldFromListOnSameWeb(String FieldName, ListDefinition LookUpListDef, String LookUpFieldName, Boolean Required)
        {
            SPList LookupList = null;

            try
            {
                LookupList = List.ParentWeb.Lists[LookUpListDef.Title];
            }
            catch (ArgumentOutOfRangeException)
            {
                throw new ArgumentOutOfRangeException("Cannot create lookup column " + FieldName + " on " + List.Title + ": " + LookUpListDef.Title + " list not found on " + List.ParentWeb.Url);
            }

            String FieldInternalName = List.Fields.AddLookup(FieldName, LookupList.ID, Required);

            SPFieldLookup LookupField = (SPFieldLookup)List.Fields.GetFieldByInternalName(FieldInternalName);

            LookupField.LookupField = LookupList.Fields[LookUpFieldName].InternalName;
            LookupField.Update();
        }
示例#16
0
        public string EnsureDependentLookup(ref SPList list, string parentFieldInternalName, string dependentFieldInternalName, string dependentFieldDisplayName, string lookupField, bool retry = true)
        {
            string  createdInternalName = null;
            SPField parentField         = list.Fields.TryGetFieldByStaticName(parentFieldInternalName);

            if (parentField != null)
            {
                //EnsureInternalFieldNameSchema(ref dependentFieldInternalName, dependentFieldDisplayName);
                try
                {
                    SPFieldLookup dependentField = (SPFieldLookup)list.Fields.TryGetFieldByStaticName(dependentFieldInternalName);
                    if (dependentField == null)
                    {
                        string depFieldInternalName = list.Fields.AddDependentLookup(dependentFieldInternalName, parentField.Id);
                        dependentField = (SPFieldLookup)list.Fields.GetFieldByInternalName(depFieldInternalName);
                    }
                    if (dependentField != null)
                    {
                        dependentField.Title       = dependentFieldDisplayName;
                        dependentField.LookupField = lookupField;
                        dependentField.Update();
                        createdInternalName = dependentField.InternalName;
                    }
                }
                catch (System.IO.FileNotFoundException fnfEx)
                {
                    if (retry)
                    {
                        list.Update();
                        EnsureDependentLookup(ref list, parentFieldInternalName, dependentFieldInternalName, dependentFieldDisplayName, lookupField, false);
                    }
                    else
                    {
                        throw fnfEx;
                    }
                }
            }
            return(createdInternalName);
        }
示例#17
0
        private void ConsistantLookup(SPItemEventProperties properties)
        {
            SPFieldLookup lookupField = (SPFieldLookup)properties.List.Fields["Parent"];

            if (string.IsNullOrEmpty(lookupField.LookupList))
            {
                if (lookupField.LookupWebId != properties.Web.ID)
                {
                    lookupField.LookupWebId = properties.Web.ID;
                }
                if (lookupField.LookupList != properties.ListId.ToString())
                {
                    lookupField.LookupList = properties.List.ID.ToString();
                }
            }
            else
            {
                string schema = lookupField.SchemaXml;
                schema = ReplaceXmlAttributeValue(schema, "List", properties.List.ID.ToString());
                schema = ReplaceXmlAttributeValue(schema, "WebId", properties.Web.ID.ToString());
                lookupField.SchemaXml = schema;
            }
            lookupField.Update(true);
        }
示例#18
0
        private void GetLookupLists(out SPList child, out SPList parent)
        {
            //
            // Child list.
            //
            child = Test.Create <LookupChild>(site.RootWeb);

            //
            // Parent list.
            //
            parent = Test.CreateList <LookupParent>(site.RootWeb);
            parent.Fields.AddLookup("Child", child.ID, false);
            parent.Update();
            SPFieldLookup lookup = new SPFieldLookup(parent.Fields, "Child");

            lookup.LookupField = "Title";
            lookup.Update();
            parent.Update();

            //
            // Add child items.
            //
            SPListItem c = child.Items.Add();

            c["Title"]  = "Child 1";
            c["Number"] = 1;
            c.Update();
            c           = child.Items.Add();
            c["Title"]  = "Child 2";
            c["Number"] = 2;
            c.Update();
            c           = child.Items.Add();
            c["Title"]  = "Child 3";
            c["Number"] = 3;
            c.Update();

            //
            // Add parent items.
            //
            SPListItem p = parent.Items.Add();

            p["Title"] = "Parent 11";
            p["Child"] = "1;#Child 1";
            p.Update();
            p          = parent.Items.Add();
            p["Title"] = "Parent 12";
            p["Child"] = "1;#Child 1";
            p.Update();
            p          = parent.Items.Add();
            p["Title"] = "Parent 21";
            p["Child"] = "2;#Child 2";
            p.Update();
            p          = parent.Items.Add();
            p["Title"] = "Parent 22";
            p["Child"] = "2;#Child 2";
            p.Update();
            p          = parent.Items.Add();
            p["Title"] = "Parent 31";
            p["Child"] = "3;#Child 3";
            p.Update();
            p          = parent.Items.Add();
            p["Title"] = "Parent 32";
            p["Child"] = "3;#Child 3";
            p.Update();
        }
示例#19
0
        public static void AddColForSortToList(string siteUrl)
        {
            if (!string.IsNullOrEmpty(siteUrl))
            {
                string        colName            = "ColForSort";
                List <string> listNameCollection = new List <string>()
                {
                    "Change Shift Management", "Leave Of Absence For Overtime Management", "Vehicle Management", "Leave Management"
                };                                                                                                                                                                        //"Overtime Management", "Overtime Employee Details",
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Console.Write("Processing...");
                        using (SPSite spSite = new SPSite(siteUrl))
                        {
                            using (SPWeb spWeb = spSite.RootWeb)
                            {
                                #region CalculatedField
                                foreach (var listName in listNameCollection)
                                {
                                    SPList spList = spWeb.Lists.TryGetList(listName);
                                    if (spList != null)
                                    {
                                        Console.WriteLine();
                                        Console.Write("List Name: {0}", listName);

                                        spWeb.AllowUnsafeUpdates = true;
                                        if (spList.Fields.ContainsField(colName) == false)
                                        {
                                            spList.Fields.Add(colName, SPFieldType.Calculated, false);

                                            SPField spField = spList.Fields.TryGetFieldByStaticName(colName);
                                            if (spField != null)
                                            {
                                                SPFieldCalculated calculatedField = spField as SPFieldCalculated;
                                                calculatedField.OutputType        = SPFieldType.Number;
                                                calculatedField.DisplayFormat     = SPNumberFormatTypes.NoDecimal;
                                                calculatedField.Formula           = "=IF([Approval Status]=\"Approved\",INT(\"7\"),IF([Approval Status]=\"Rejected\",INT(\"8\"),IF([Approval Status]=\"Cancelled\",INT(\"9\"),INT(\"0\"))))";
                                                calculatedField.Update();
                                                Console.Write(" -> Done");
                                            }
                                            else
                                            {
                                                Console.Write(" -> Failed");
                                            }
                                        }
                                        else
                                        {
                                            Console.Write(" -> Existed");
                                        }
                                        spWeb.AllowUnsafeUpdates = false;
                                    }
                                    else
                                    {
                                        Console.WriteLine();
                                        Console.Write("Cannot find list: {0}", listName);
                                    }
                                }
                                #endregion

                                #region Create ColForSort for Overtime Management List
                                string overtimeManagementListName = "Overtime Management";
                                Console.WriteLine();
                                Console.Write("List Name: {0}", overtimeManagementListName);
                                SPList overtimeManagementList = spWeb.Lists.TryGetList(overtimeManagementListName);
                                if (overtimeManagementList != null)
                                {
                                    if (overtimeManagementList.Fields.ContainsField(colName) == false)
                                    {
                                        spWeb.AllowUnsafeUpdates = true;

                                        overtimeManagementList.Fields.Add(colName, SPFieldType.Number, false);
                                        SPField spField = overtimeManagementList.Fields.TryGetFieldByStaticName(colName);
                                        if (spField != null)
                                        {
                                            SPFieldNumber spFieldNumber = spField as SPFieldNumber;
                                            spFieldNumber.DisplayFormat = SPNumberFormatTypes.NoDecimal;
                                            spFieldNumber.Update();
                                            Console.Write(" -> Done");
                                        }
                                        else
                                        {
                                            Console.Write(" -> Failed");
                                        }

                                        spWeb.AllowUnsafeUpdates = false;
                                    }
                                    else
                                    {
                                        Console.Write(" -> Existed");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine();
                                    Console.Write("Cannot find list: {0}", overtimeManagementListName);
                                }
                                #endregion

                                #region Create CalculateField ColForSort for Overtime Employee Details list
                                string overtimeDetailsListName = "Overtime Employee Details";
                                Console.WriteLine();
                                Console.Write("List Name: {0}", overtimeDetailsListName);
                                SPList overtimeDetailsList = spWeb.Lists.TryGetList(overtimeDetailsListName);
                                SPList overtimeList        = spWeb.Lists.TryGetList("Overtime Management");
                                if (overtimeDetailsList != null && overtimeList != null)
                                {
                                    if (overtimeDetailsList.Fields.ContainsField(colName) == false && overtimeList.Fields.ContainsField(colName) == true)
                                    {
                                        spWeb.AllowUnsafeUpdates = true;

                                        overtimeDetailsList.Fields.AddDependentLookup(colName, new Guid("{878e2996-150c-4e63-b632-ba90dec566a0}"));
                                        SPField spField = overtimeDetailsList.Fields.TryGetFieldByStaticName(colName);
                                        if (spField != null)
                                        {
                                            SPFieldLookup spFieldLookup = spField as SPFieldLookup;
                                            spFieldLookup.LookupField   = colName;
                                            spFieldLookup.Update();
                                            Console.Write(" -> Done");
                                        }
                                        else
                                        {
                                            Console.Write(" -> Failed");
                                        }

                                        spWeb.AllowUnsafeUpdates = false;
                                    }
                                    else
                                    {
                                        Console.Write(" -> Existed");
                                    }
                                }
                                #endregion
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Error: {0}", ex.Message));
                }
                Console.WriteLine();
                //Console.Write("Press any key to exit...");
                //Console.Read();
            }
            else
            {
                Console.Write("Troll?");
                Console.Read();
            }
        }
示例#20
0
        public override bool Perform()
        {
            storeurl = CoreFunctions.getFarmSetting("workenginestore");

            solutions = (SPDocumentLibrary)base.SPWeb.Site.GetCatalog(SPListTemplateType.ListTemplateCatalog);

            LogMessage("Activating List Features");

            SPSite.Features.Add(new Guid("e08e676e-81fb-497e-9590-9d1c2673b85c"), true);


            //==============================================================
            LogMessage("Removing old settings list");

            try
            {
                SPList settings = SPWeb.Lists.TryGetList("EPM Live Settings");

                if (settings != null)
                {
                    settings.Delete();
                }
            }
            catch (Exception ex)
            {
                LogMessage("", ex.Message, 3);
            }

            //==============================================================

            LogMessage("Downloading and Installing List Templates");

            DownloadAndInstallList("Departments", "Departments", "Departments");
            DownloadAndInstallList("HolidaySchedules", "HolidaySchedules", "Holiday Schedules");
            DownloadAndInstallList("Holidays", "Holidays", "Holidays");

            if (base.bIsPfe)
            {
                DownloadAndInstallList("EPM Live Settings", "pfe epm live settings", "EPM Live Settings");
            }
            else
            {
                DownloadAndInstallList("EPM Live Settings", "epm live settings", "EPM Live Settings");
            }

            DownloadAndInstallList("Roles", "Roles", "Roles");
            DownloadAndInstallList("WorkHours", "WorkHours", "Work Hours");
            DownloadAndInstallList("Time Off", "TimeOff", "Time Off");
            //==============================================================


            LogMessage("Checking Holidays Lookup");

            SPList oHolidays         = SPWeb.Lists.TryGetList("Holidays");
            SPList oHolidaySchedules = SPWeb.Lists.TryGetList("Holiday Schedules");
            SPList oResourcePool     = SPWeb.Lists.TryGetList("Resources");

            if (oHolidays == null)
            {
                LogMessage("", "Holidays list missing", 3);
            }
            else if (oHolidaySchedules == null)
            {
                LogMessage("", "Holiday Schedules list missing", 3);
            }
            else
            {
                SPField oField = null;
                try
                {
                    oField = oHolidays.Fields.GetFieldByInternalName("HolidaySchedule");
                }
                catch { }

                if (oField == null)
                {
                    LogMessage("\tCreating Holidays Lookup");

                    oField       = oHolidays.Fields.GetFieldByInternalName(oHolidays.Fields.AddLookup("HolidaySchedule", oHolidaySchedules.ID, true));
                    oField.Title = "Holiday Schedule";
                    oField.Update();

                    var spFieldLookup = (SPFieldLookup)oField;
                    spFieldLookup.LookupField = "Title";
                    spFieldLookup.Update();
                }
                else
                {
                    LogMessage("\tUpdating Holidays Lookup");

                    SPFieldLookup oLookup = (SPFieldLookup)oField;
                    if (new Guid(oLookup.LookupList) != oHolidaySchedules.ID)
                    {
                        oField.Delete();
                        oHolidays.Update();
                        oField       = oHolidays.Fields.GetFieldByInternalName(oHolidays.Fields.AddLookup("HolidaySchedule", oHolidaySchedules.ID, true));
                        oField.Title = "Holiday Schedule";
                        oField.Update();

                        var spFieldLookup = (SPFieldLookup)oField;
                        spFieldLookup.LookupField = "Title";
                        spFieldLookup.Update();
                    }
                }

                oHolidays.Update();
            }

            //Fixing Department Lookup

            SPList oDepartments = SPWeb.Lists.TryGetList("Departments");

            if (oDepartments == null)
            {
                LogMessage("", "Departments list missing", 3);
            }
            else
            {
                LogMessage("Departments list lookups");

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("RBS");
                    if (new Guid(lookup.LookupList) != oDepartments.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("RBS", oDepartments.ID, false);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("RBS");



                        lookup.LookupField = "DisplayName";
                        lookup.Title       = "Parent Department";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField RBS");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field RBS: " + ex.Message, 3);
                }

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Managers");
                    if (new Guid(lookup.LookupList) != oResourcePool.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("Managers", oResourcePool.ID, true);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Managers");



                        lookup.LookupField = "Title";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField Managers");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field Managers: " + ex.Message, 3);
                }

                try
                {
                    SPFieldLookup lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Executives");
                    if (new Guid(lookup.LookupList) != oResourcePool.ID)
                    {
                        bool bSealed = lookup.Sealed;
                        if (bSealed)
                        {
                            lookup.Sealed = false;
                            lookup.Update();
                        }
                        lookup.AllowDeletion = true;
                        lookup.Update();
                        lookup.Delete();

                        oDepartments.Fields.AddLookup("Executives", oResourcePool.ID, false);

                        lookup = (SPFieldLookup)oDepartments.Fields.GetFieldByInternalName("Executives");

                        lookup.LookupField = "Title";
                        lookup.Update();

                        if (bSealed)
                        {
                            lookup.Sealed = true;
                            lookup.Update();
                        }

                        LogMessage("\tField Executives");
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", "Field Executives: " + ex.Message, 3);
                }
            }


            LogMessage("Processing Time Off Temp Data");

            SPList oNonWork = SPWeb.Lists.TryGetList("Non Work");
            SPList oTimeOff = SPWeb.Lists.TryGetList("Time Off");

            if (oNonWork == null)
            {
                LogMessage("", "Non Work list missing", 3);
            }
            else if (oTimeOff == null)
            {
                LogMessage("", "Time Off list missing", 3);
            }
            else
            {
                if (!oTimeOff.Fields.ContainsFieldWithInternalName("TempType"))
                {
                    oTimeOff.Fields.Add("TempType", SPFieldType.Text, false);
                    oTimeOff.Update();

                    try
                    {
                        SPField oField = oTimeOff.Fields.GetFieldByInternalName("TempType");
                        oField.ShowInDisplayForm = false;
                        oField.ShowInEditForm    = false;
                        oField.ShowInNewForm     = false;
                        oField.Update();
                    }
                    catch { }
                }

                SPField oTimeOffType = null;
                try
                {
                    oTimeOffType = oTimeOff.Fields.GetFieldByInternalName("TimeOffType");
                }
                catch { }

                if (oTimeOffType != null && oTimeOffType.Type == SPFieldType.Choice)
                {
                    LogMessage("\tProcessing Temp Items");

                    foreach (SPListItem li in oTimeOff.Items)
                    {
                        try
                        {
                            li["TempType"] = li[oTimeOffType.Id].ToString();
                            li.Update();
                        }
                        catch (Exception ex)
                        {
                            LogMessage("\t", li.Title + ": " + ex.Message, 3);
                        }
                    }
                }

                SPField oWorkDetail = null;
                try
                {
                    oWorkDetail = oTimeOff.Fields.GetFieldByInternalName("WorkDetail");
                }
                catch { }

                if (oWorkDetail == null)
                {
                    try
                    {
                        oTimeOff.Fields.AddFieldAsXml(@"<Field Type=""DaysHoursBreakdownField"" DisplayName=""WorkDetail"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" StaticName=""WorkDetail"" Name=""WorkDetail"" ><Customization><ArrayOfProperty><Property><Name>StartDateField</Name><Value xmlns:q1=""http://www.w3.org/2001/XMLSchema"" p4:type=""q1:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">StartDate</Value></Property><Property><Name>FinishDateField</Name><Value xmlns:q2=""http://www.w3.org/2001/XMLSchema"" p4:type=""q2:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">DueDate</Value></Property><Property><Name>HoursField</Name><Value xmlns:q3=""http://www.w3.org/2001/XMLSchema"" p4:type=""q3:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Work</Value></Property><Property><Name>HolidaySchedulesField</Name><Value xmlns:q4=""http://www.w3.org/2001/XMLSchema"" p4:type=""q4:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">HolidaySchedule</Value></Property><Property><Name>ResourcePoolList</Name><Value xmlns:q5=""http://www.w3.org/2001/XMLSchema"" p4:type=""q5:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Resources</Value></Property><Property><Name>WorkHoursList</Name><Value xmlns:q6=""http://www.w3.org/2001/XMLSchema"" p4:type=""q6:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Work Hours</Value></Property><Property><Name>HolidaysList</Name><Value xmlns:q7=""http://www.w3.org/2001/XMLSchema"" p4:type=""q7:string"" xmlns:p4=""http://www.w3.org/2001/XMLSchema-instance"">Holidays</Value></Property></ArrayOfProperty></Customization></Field>");
                        SPField oField = oTimeOff.Fields.GetFieldByInternalName("WorkDetail");
                        oField.Title = "Work Detail";
                        oField.Update();

                        LogMessage("\tAdd Work Detail Field");
                    }
                    catch (Exception ex)
                    {
                        LogMessage("", "Add Work Detail: " + ex.Message, 3);
                    }
                }
            }

            try
            {
                if (!oResourcePool.Fields.ContainsFieldWithInternalName("EXTID"))
                {
                    oResourcePool.Fields.Add("EXTID", SPFieldType.Text, false);
                    SPField oField = oResourcePool.Fields.GetFieldByInternalName("EXTID");
                    oField.Hidden = true;
                    oField.Update();

                    LogMessage("Add EXTID Field to Resources");
                }
            }
            catch (Exception ex)
            {
                LogMessage("", "Add EXTID Field to Resources: " + ex.Message, 3);
            }

            //Process dept event

            LogMessage("Processing Department Events");

            try
            {
                bool badding   = false;
                bool bupdating = false;
                bool bdeleted  = false;

                string sClass    = "EPMLiveCore.DepartmentEvent";
                string sAssembly = "EPM Live Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5";

                foreach (SPEventReceiverDefinition e in oDepartments.EventReceivers)
                {
                    if (e.Assembly == sAssembly && e.Class == sClass)
                    {
                        if (e.Type == SPEventReceiverType.ItemAdding)
                        {
                            badding = true;
                        }
                        else if (e.Type == SPEventReceiverType.ItemUpdating)
                        {
                            bupdating = true;
                        }
                        else if (e.Type == SPEventReceiverType.ItemDeleted)
                        {
                            bdeleted = true;
                        }
                    }
                }

                if (!badding)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemAdding, sAssembly, sClass);
                    oDepartments.Update();
                }

                if (!bupdating)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemUpdating, sAssembly, sClass);
                    oDepartments.Update();
                }
                if (!bdeleted)
                {
                    oDepartments.EventReceivers.Add(SPEventReceiverType.ItemDeleted, sAssembly, sClass);
                    oDepartments.Delete();
                }
            }
            catch (Exception ex)
            {
                LogMessage("", ex.Message, 3);
            }

            LogMessage("Mapping Reporting lists.");

            var       reportData = new ReportData(SPSite.ID);
            DataTable dbMappings = reportData.GetDbMappings();

            if (!dbMappings.Select(string.Format("SiteId = '{0}'", SPSite.ID)).Any())
            {
                LogMessage("", "Reporting is not configured.", 2);
            }
            else
            {
                try
                {
                    var reportBiz = new ReportBiz(SPSite.ID, SPSite.WebApplication.Id);

                    reportBiz.GetDatabaseMappings();

                    foreach (var list in new[] { "Work Hours", "Holiday Schedules", "Holidays", "Time Off" })
                    {
                        try
                        {
                            LogMessage("Mapping " + list + " list to Reporting.");

                            SPList spList = SPWeb.Lists[list];

                            ListBiz listBiz = reportBiz.CreateListBiz(spList.ID);

                            if (string.IsNullOrEmpty(listBiz.ListName))
                            {
                                reportBiz.CreateListBiz(spList.ID);
                                LogMessage("", "Mapped successfully.", 1);
                            }
                            else
                            {
                                LogMessage("", "Already mapped.", 2);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMessage("", ex.Message, 3);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("", ex.Message, 3);
                }
            }

            return(true);
        }
        public void OnSaveChange(SPField field, bool isNewField)
        {
            using (new EnterExitLogger("CCSCascadedLookupFieldEditor:OnSaveChange function"))
            {
                try
                {

                    CCSCascadedLookupField ccscascadeField = field as CCSCascadedLookupField;
                    if (ccscascadeField != null)
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate
                            {
                                using (SPWeb selWeb = SPContext.Current.Site.OpenWeb(new Guid(ddlWeb.SelectedItem.Value)))
                                {
                                    ccscascadeField.LookupWebId = selWeb.ID;
                                    Utils.LogManager.write("ccscascadeField.LookupWebId: " + selWeb.ID.ToString());
                                }
                            });

                        ccscascadeField.LookupList = (ddlList.SelectedItem != null ? ddlList.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.LookupList: " + ddlList.SelectedItem.Value);

                        ccscascadeField.LookupField = (ddlColumn.SelectedItem != null ? ddlColumn.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.LookupField: " + ddlColumn.SelectedItem.Value);

                        ccscascadeField.SourceWebID = ddlWeb.SelectedItem.Value;
                        Utils.LogManager.write("ccscascadeField.SourceWebID: " + ddlWeb.SelectedItem.Value);

                        ccscascadeField.LookupFieldListName = (ddlList.SelectedItem != null ? ddlList.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.LookupFieldListName: " + (ddlList.SelectedItem != null ? ddlList.SelectedItem.Value : ""));
                        
                        ccscascadeField.LookupFieldName = (ddlColumn.SelectedItem != null ? ddlColumn.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.LookupFieldName: " + (ddlColumn.SelectedItem != null ? ddlColumn.SelectedItem.Value : ""));
                        
                        ccscascadeField.ParentLinkedColumnName = (ddlParentColumn.SelectedItem != null ? ddlParentColumn.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.ParentLinkedColumnName: " + (ddlParentColumn.SelectedItem != null ? ddlParentColumn.SelectedItem.Value : ""));

                        ccscascadeField.AllowMultipleValues = cbxAllowMultiple.Checked;
                        Utils.LogManager.write("ccscascadeField.AllowMultipleValues: " + cbxAllowMultiple.Checked.ToString());
                        
                        ccscascadeField.AdvancedSetting = cbxAdvanceSettings.Checked;
                        Utils.LogManager.write("ccscascadeField.AdvancedSetting: " + cbxAdvanceSettings.Checked.ToString());
                        
                        ccscascadeField.View = (ddlView.SelectedItem != null ? ddlView.SelectedItem.Value : "");
                        Utils.LogManager.write("ccscascadeField.View: " + (ddlView.SelectedItem != null ? ddlView.SelectedItem.Value : ""));
                        
                        ccscascadeField.LinkToParent = cbxLinkParent.Checked;
                        Utils.LogManager.write("ccscascadeField.LinkToParent: " + cbxLinkParent.Checked.ToString());
                        
                        ccscascadeField.ShowAllOnEmpty = cbxShowallParentEmpty.Checked;
                        Utils.LogManager.write("ccscascadeField.ShowAllOnEmpty: " + cbxShowallParentEmpty.Checked.ToString());
                        
                        ccscascadeField.AllowNewEntry = cbxAllowNewValues.Checked;
                        Utils.LogManager.write("ccscascadeField.AllowNewEntry: " + cbxAllowNewValues.Checked.ToString());
                        
                        ccscascadeField.UseNewForm = cbxUseNewForm.Checked;
                        Utils.LogManager.write("ccscascadeField.UseNewForm: " + cbxUseNewForm.Checked.ToString());

                        ccscascadeField.SortByView = cbxSortByView.Checked;
                        Utils.LogManager.write("ccscascadeField.SortByView: " + cbxSortByView.Checked.ToString());
                        
                        ccscascadeField.AllowAutocomplete = false;
                        Utils.LogManager.write("ccscascadeField.AllowAutocomplete: False");

                        if (cbxRelationshipBehavior.Enabled && cbxRelationshipBehavior.Checked)
                        {
                            if (rbRestrictDelete.Enabled && rbRestrictDelete.Checked)
                            {
                                ccscascadeField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;
                                Utils.LogManager.write("ccscascadeField.RelationshipDeleteBehavior: Restrict");
                            }
                            else if (rbCascadeDelete.Enabled && rbCascadeDelete.Checked)
                            {
                                ccscascadeField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Cascade;
                                Utils.LogManager.write("ccscascadeField.RelationshipDeleteBehavior: Cascade");
                            }
                            else
                            {
                                ccscascadeField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.None;
                                Utils.LogManager.write("ccscascadeField.RelationshipDeleteBehavior: None");
                            }
                        }
                        else
                        {
                            ccscascadeField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.None;
                            Utils.LogManager.write("ccscascadeField.RelationshipDeleteBehavior: None");
                        }

                        ccscascadeField.AdditionalFilters = GetAdditonalFilters();
                        Utils.LogManager.write("ccscascadeField.AdditionalFilters: " + ccscascadeField.AdditionalFilters);

                        if (isNewField)
                        {
                            ccscascadeField.AdditionalFields = GetAdditonalFields();
                            Utils.LogManager.write("ccscascadeField.AdditionalFields: " + ccscascadeField.AdditionalFields);
                        }
                        else
                        {
                            ccscascadeField.AdditionalFields = "";
                            if (cblAdditionalFields.Items != null && cblAdditionalFields.Items.Count > 0)
                            {
                                foreach (ListItem li in cblAdditionalFields.Items)
                                {
                                    if (li.Selected)
                                    {
                                        if (!ccscascadeField.ParentList.Fields.ContainsField(ccscascadeField.Title + " : " + li.Text))
                                        {
                                            //create a new field
                                            Utils.LogManager.write("Creating AddintionField Name: " + ccscascadeField.Title + " : " + li.Text);
                                            string depLookUp = ccscascadeField.ParentList.Fields.AddDependentLookup(ccscascadeField.Title + " : " + li.Text, ccscascadeField.Id);
                                            SPFieldLookup fieldDepLookup = (SPFieldLookup)ccscascadeField.ParentList.Fields.GetFieldByInternalName(depLookUp);

                                            if (fieldDepLookup != null)
                                            {
                                                fieldDepLookup.LookupWebId = ccscascadeField.LookupWebId;
                                                fieldDepLookup.LookupField = li.Value;
                                                fieldDepLookup.Update();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (ccscascadeField.ParentList.Fields.ContainsField(ccscascadeField.Title + " : " + li.Text))
                                        {
                                            //delete field if exist
                                            Utils.LogManager.write("Deleting AddintionField Name: " + ccscascadeField.Title + " : " + li.Text);
                                            ccscascadeField.ParentList.Fields.GetField(ccscascadeField.Title + " : " + li.Text).Delete();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.LogManager.write("Exception Occurs in OnSaveChanges Function. \r\nError Message: " + ex.Message + "\r\nStack Trace: " + ex.StackTrace, "error");
                }
            }
        }
示例#22
0
        //Create Site Columns
        public void CreateSiteColumns()
        {
            using (SPWeb oSPWeb = oSPSite.RootWeb)
            {
                try
                {
                    //if (!oSPWeb.Fields.ContainsField("Codigo"))
                    //{

                    //Codigo de Documento
                    string      codigoField = oSPWeb.Fields.Add("Codigo", SPFieldType.Text, false);
                    SPFieldText Codigo      = (SPFieldText)oSPWeb.Fields.GetFieldByInternalName(codigoField);
                    Codigo.Group = groupColumn;
                    Codigo.Update();
                    //}

                    //if (!oSPWeb.Fields.ContainsField("Referencia"))
                    //{
                    string      referenciaField = oSPWeb.Fields.Add("Referencia", SPFieldType.Text, false);
                    SPFieldText Referencia      = (SPFieldText)oSPWeb.Fields.GetFieldByInternalName(referenciaField);
                    Referencia.Group = groupColumn;
                    Referencia.Update();
                    //}

                    //if (!oSPWeb.Fields.ContainsField("Comentario")) {
                    string      comentarioField = oSPWeb.Fields.Add("Comentario", SPFieldType.Text, false);
                    SPFieldText Comentario      = (SPFieldText)oSPWeb.Fields.GetFieldByInternalName(comentarioField);
                    Comentario.Group = groupColumn;
                    Comentario.Update();
                    //}


                    //if (!oSPWeb.Fields.ContainsField("Remitente"))
                    //{
                    string      remitenteField = oSPWeb.Fields.Add("Remitente", SPFieldType.Text, false);
                    SPFieldText Remitente      = (SPFieldText)oSPWeb.Fields.GetFieldByInternalName(remitenteField);
                    Remitente.Group = groupColumn;
                    Remitente.Update();

                    //}

                    //if (!oSPWeb.Fields.ContainsField("Factura")) {
                    string        facturaField = oSPWeb.Fields.Add("Factura", SPFieldType.Number, false);
                    SPFieldNumber Factura      = (SPFieldNumber)oSPWeb.Fields.GetFieldByInternalName(facturaField);
                    Factura.Group = groupColumn;
                    Factura.Update();
                    //}


                    //if (!oSPWeb.Fields.ContainsField("Fecha Receopcion")) {
                    string          fechaRecepcionField = oSPWeb.Fields.Add("Fecha Recepcion", SPFieldType.DateTime, true);
                    SPFieldDateTime FechaRecepcion      = (SPFieldDateTime)oSPWeb.Fields.GetFieldByInternalName(fechaRecepcionField);
                    FechaRecepcion.Group = groupColumn;
                    FechaRecepcion.Update();

                    //}

                    //Method 3 using Field schema
                    //if (!oSPWeb.Fields.ContainsField("Nota"))
                    //{
                    string notaField          = oSPWeb.Fields.Add("Nota", SPFieldType.Note, false);
                    SPFieldMultiLineText Nota = (SPFieldMultiLineText)oSPWeb.Fields.GetFieldByInternalName(notaField);
                    Nota.Group = groupColumn;
                    Nota.Update();
                    //}

                    //if (!oSPWeb.Fields.ContainsField("Gerencias"))
                    //{

                    // Lookup Column
                    SPList gerenciasList = oSPWeb.Lists.TryGetList("Gerencias");

                    string        GerenciaField  = oSPWeb.Fields.AddLookup("Gerencia", gerenciasList.ID, true);
                    SPFieldLookup gerenciaLookup = (SPFieldLookup)oSPWeb.Fields.GetFieldByInternalName(GerenciaField);

                    gerenciaLookup.Group       = groupColumn;
                    gerenciaLookup.LookupField = "Title";
                    gerenciaLookup.Update();
                    //}

                    SPList listas = oSPWeb.Lists.TryGetList("Listas");
                    //if (!oSPWeb.Fields.ContainsField("Nivel Prioridad"))
                    //{

                    string        nivelPrioridadField  = oSPWeb.Fields.AddLookup("Nivel Prioridad", listas.ID, true);
                    SPFieldLookup nivelPrioridadLookup = (SPFieldLookup)oSPWeb.Fields.GetFieldByInternalName(nivelPrioridadField);
                    nivelPrioridadLookup.Group       = groupColumn;
                    nivelPrioridadLookup.LookupField = "Title";
                    nivelPrioridadLookup.Update();
                    //}

                    //if (!oSPWeb.Fields.ContainsField("Clasificacion"))
                    //{

                    string        clasificacionField  = oSPWeb.Fields.AddLookup("Clasificacion", listas.ID, true);
                    SPFieldLookup clasificacionLookup = (SPFieldLookup)oSPWeb.Fields.GetFieldByInternalName(clasificacionField);
                    clasificacionLookup.Group       = groupColumn;
                    clasificacionLookup.LookupField = "Title";
                    clasificacionLookup.Update();
                    //}

                    //if (!oSPWeb.Fields.ContainsField("Estado"))
                    //{

                    string        estadoField  = oSPWeb.Fields.AddLookup("Estado", listas.ID, false);
                    SPFieldLookup estadoLookup = (SPFieldLookup)oSPWeb.Fields.GetFieldByInternalName(estadoField);
                    estadoLookup.Group       = groupColumn;
                    estadoLookup.LookupField = "Title";
                    estadoLookup.Update();
                    //}
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
示例#23
0
        public override bool Perform()
        {
            LogMessage("Processing Time Off Data");

            SPList oNonWork = SPWeb.Lists.TryGetList("Non Work");
            SPList oTimeOff = SPWeb.Lists.TryGetList("Time Off");

            if (oNonWork == null)
            {
                LogMessage("", "Non Work list missing", 3);
            }
            else if (oTimeOff == null)
            {
                LogMessage("", "Time Off list missing", 3);
            }
            else
            {
                SPField oTimeOffType = null;
                try
                {
                    oTimeOffType = oTimeOff.Fields.GetFieldByInternalName("TimeOffType");
                }
                catch (Exception ex)
                {
                    LogMessage("", ex.Message, 3);
                    return(true);
                }

                if (oTimeOffType.Type == SPFieldType.Choice)
                {
                    if (oTimeOffType.Sealed)
                    {
                        oTimeOffType.Sealed = false;
                        oTimeOffType.Update();
                    }
                    oTimeOffType.AllowDeletion = true;
                    oTimeOffType.Update();
                    oTimeOffType.Delete();

                    oTimeOff.Fields.AddLookup("TimeOffType", oNonWork.ID, true);
                    SPFieldLookup oTimeOffTypeL = (SPFieldLookup)oTimeOff.Fields.GetFieldByInternalName("TimeOffType");
                    oTimeOffTypeL.LookupField = "Title";
                    oTimeOffTypeL.Sealed      = true;
                    oTimeOffTypeL.Title       = "Time Off Type";
                    oTimeOffTypeL.Update();

                    try
                    {
                        oTimeOffType = oTimeOff.Fields.GetFieldByInternalName("TimeOffType");
                    }
                    catch { }
                }

                if (oTimeOffType.Type == SPFieldType.Lookup)
                {
                    DataTable dt = oNonWork.Items.GetDataTable();

                    foreach (SPListItem li in oTimeOff.Items)
                    {
                        try
                        {
                            DataRow[] dr = dt.Select("Title='" + li["TempType"].ToString() + "'");

                            if (dr.Length > 0)
                            {
                                SPFieldLookupValue lv = new SPFieldLookupValue(int.Parse(dr[0]["ID"].ToString()), li["TempType"].ToString());

                                li[oTimeOffType.Id] = lv;
                                li.Update();

                                LogMessage("\tUpdate: " + li.Title);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMessage("\t", "Update: " + li.Title + ": " + ex.Message, 3);
                        }
                    }
                }
            }

            return(true);
        }
        void ConvertToCCSCascadedLookupField(SPFieldLookup field)
        {
            using (new EnterExitLogger("CCSCascadedLookupFieldEditor:ConvertToCCSCascadedLookupField function"))
            {
                XmlDocument doc = new XmlDocument();
                Utils.LogManager.write("Before SPFieldLookup xmlScema: " + field.SchemaXml);
                
                doc.LoadXml(field.SchemaXml);

                //Creating Attributes

                CreateAttribute(doc, "Type", "CCSCascadedLookup");

                CreateAttribute(doc, "WebId", field.LookupWebId.ToString());

                CreateAttribute(doc, "SourceWebID", field.LookupWebId.ToString());

                CreateAttribute(doc, "LookupFieldListName", field.LookupList);

                CreateAttribute(doc, "LookupFieldName", field.LookupField);

                CreateAttribute(doc, "ParentLinkedColumnName", "");

                CreateAttribute(doc, "AllowMultipleValues", "");

                CreateAttribute(doc, "AdvancedSetting", "True");

                CreateAttribute(doc, "View", "");

                CreateAttribute(doc, "LinkToParent", "False");

                CreateAttribute(doc, "ShowAllOnEmpty", "False");

                CreateAttribute(doc, "AllowNewEntry", "False");

                CreateAttribute(doc, "UseNewForm", "False");

                CreateAttribute(doc, "SortByView", "False");

                CreateAttribute(doc, "AllowAutocomplete", "False");

                CreateAttribute(doc, "AdditionalFields", "");

                CreateAttribute(doc, "AdditionalFilters", "");


                doc.DocumentElement.InnerXml = "<Customization><ArrayOfProperty>" +
                           "<Property><Name>SourceWebID</Name></Property>" +
                           "<Property><Name>LookupFieldListName</Name></Property>" +
                           "<Property><Name>LookupFieldName</Name></Property>" +
                           "<Property><Name>ParentLinkedColumnName</Name></Property>" +
                           "<Property><Name>AllowMultipleValues</Name></Property>" +
                           "<Property><Name>AdvancedSetting</Name></Property>" +
                           "<Property><Name>View</Name></Property>" +
                           "<Property><Name>LinkToParent</Name></Property>" +
                           "<Property><Name>ShowAllOnEmpty</Name></Property>" +
                           "<Property><Name>AllowNewEntry</Name></Property>" +
                           "<Property><Name>UseNewForm</Name></Property>" +
                           "<Property><Name>AdditionalFields</Name></Property>" +
                           "<Property><Name>SortByView</Name></Property>" +
                           "<Property><Name>AllowAutocomplete</Name></Property>" +
                           "<Property><Name>AdditionalFilters</Name></Property>" +
                           "</ArrayOfProperty></Customization>";


                field.SchemaXml = doc.OuterXml;

                Utils.LogManager.write("After SPFieldLookup xmlScema: " + field.SchemaXml);

                field.Update();
            }
        }
示例#25
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb  web  = (SPWeb)properties.Feature.Parent;
            SPSite site = web.Site;

            web.AllowUnsafeUpdates = true;
            Lists listRoot = GetListsInfo(properties);

            foreach (List listInfo in listRoot.Items)
            {
                SPList tempList = null;
                if (listInfo.name != null)
                {
                    listName = listInfo.name.Trim();
                }
                else
                {
                    throw new Exception(Constants.LIST_NAME_ERROR);
                }
                descName = listInfo.description;
                if (CheckList(web, listName))
                {
                    tempList = web.Lists[web.Lists.Add(listName, descName, SPListTemplateType.GenericList)];
                }
                else
                {
                    tempList = web.Lists[listName];
                }
                if (tempList != null)
                {
                    foreach (Field fields in listInfo.Fields)
                    {
                        SPFieldType fldType = SPFieldType.Text;
                        ClearFlags();

                        if (fields.name != null)
                        {
                            fieldname = fields.name.Trim();
                        }
                        else
                        {
                            throw new Exception(Constants.FIELD_NAME_ERROR + listName);
                        }

                        if (fields.datatype != null)
                        {
                            fieldtype = fields.datatype.Trim();
                        }

                        if (fields.required != null)
                        {
                            required = fields.required.Trim();
                        }

                        if (fields.defaultvalue != null)
                        {
                            defaultValue = fields.defaultvalue.Trim();
                        }

                        if (fields.textformat != null)
                        {
                            textFormat = fields.textformat.Trim();
                        }

                        if (fields.displaychoicesusing != null)
                        {
                            displayChoicesUsing = fields.displaychoicesusing.Trim();
                        }

                        if (fields.lookuplist != null)
                        {
                            lookupList = fields.lookuplist.Trim();
                        }

                        if (fields.lookupfield != null)
                        {
                            lookupfield = fields.lookupfield.Trim();
                        }

                        switch (fieldtype.ToLower())
                        {
                        case Constants.SINGLE_LINE_TEXT_TYPE:
                            fldType = SPFieldType.Text;
                            break;

                        case Constants.MULTIPLE_LINE_TEXT_TYPE:
                            fldType = SPFieldType.Note;
                            break;

                        case Constants.DATETIME_TYPE:
                            fldType = SPFieldType.DateTime;
                            break;

                        case Constants.NUMBER_TYPE:
                            fldType = SPFieldType.Number;
                            break;

                        case Constants.CURRENCY_TYPE:
                            fldType = SPFieldType.Currency;
                            break;

                        case Constants.YESNO_TYPE:
                            fldType = SPFieldType.Boolean;
                            break;

                        case Constants.PERSON_GROUP_TYPE:
                            fldType = SPFieldType.User;
                            break;

                        case Constants.HYPERLINK_PICTURE_TYPE:
                            fldType = SPFieldType.URL;
                            break;

                        case Constants.CHOICE_TYPE:
                            if (displayChoicesUsing.ToLower().Trim().Equals(Constants.MULTICHECKBOX))
                            {
                                fldType = SPFieldType.MultiChoice;
                            }
                            else
                            {
                                fldType = SPFieldType.Choice;
                            }
                            break;

                        case Constants.LOOKUP_TYPE:
                            fldType = SPFieldType.Lookup;
                            break;
                        }

                        SPField field = tempList.Fields.CreateNewField(fldType.ToString(), fieldname);
                        field.DefaultValue = defaultValue;
                        field.Description  = fielddesc;
                        field.Required     = (required.ToLower().Trim().Equals(Constants.YES) ? true : false);

                        if (!tempList.Fields.ContainsField(fieldname))
                        {
                            tempList.Fields.Add(field);
                        }

                        if ((tempList.Fields[fieldname] as SPFieldText) != null)
                        {
                            int maxLength;
                            int.TryParse(maxCount, out maxLength);
                            var fldText = tempList.Fields[fieldname] as SPFieldText;

                            if (fldText != null && maxLength > 0)
                            {
                                fldText.MaxLength = maxLength;
                                fldText.Update();
                                tempList.Update();
                            }

                            continue;
                        }

                        if ((tempList.Fields[fieldname] as SPFieldMultiLineText) != null)
                        {
                            int noOfLines;
                            int.TryParse(NoOfLines, out noOfLines);
                            SPFieldMultiLineText fldMultiText = tempList.Fields[fieldname] as SPFieldMultiLineText;
                            fldMultiText.NumberOfLines = (noOfLines > 0) ? noOfLines : fldMultiText.NumberOfLines;
                            fldMultiText.RichText      = (textFormat.ToLower().Trim().Equals(Constants.RICHTEXT)) ? true : false;
                            fldMultiText.Update();
                            tempList.Update();

                            continue;
                        }

                        if ((tempList.Fields[fieldname] as SPFieldBoolean) != null)
                        {
                            SPFieldBoolean fldBoolean = (tempList.Fields[fieldname]) as SPFieldBoolean;
                            // useful in future
                            tempList.Update();

                            continue;
                        }

                        if ((tempList.Fields[fieldname] as SPFieldUser) != null)
                        {
                            SPFieldUser fldUser = tempList.Fields[fieldname] as SPFieldUser;
                            // useful in future
                            tempList.Update();

                            continue;
                        }

                        if (tempList.Fields[fieldname] as SPFieldMultiChoice != null)
                        {
                            SPFieldMultiChoice fldMultiChoice = tempList.Fields[fieldname] as SPFieldMultiChoice;

                            foreach (Choice choiceNodes in fields.Choices)
                            {
                                fldMultiChoice.Choices.Add(choiceNodes.Value);
                            }
                            fldMultiChoice.Update();
                            tempList.Update();

                            continue;
                        }

                        if ((tempList.Fields[fieldname] as SPFieldChoice) != null)
                        {
                            SPFieldChoice fldChoice = tempList.Fields[fieldname] as SPFieldChoice;

                            if (displayChoicesUsing.ToLower().Trim().Equals(Constants.DROPDOWNMENU))
                            {
                                fldChoice.EditFormat = SPChoiceFormatType.Dropdown;
                            }

                            if (displayChoicesUsing.ToLower().Trim().Equals(Constants.RADIOBUTTONS))
                            {
                                fldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
                            }

                            // Add the choices
                            foreach (Choice choiceNodes in fields.Choices)
                            {
                                fldChoice.Choices.Add(choiceNodes.Value);
                            }
                            fldChoice.Update();
                            tempList.Update();

                            continue;
                        }

                        if ((tempList.Fields[fieldname] as SPFieldLookup) != null)
                        {
                            SPFieldLookup fldLookup  = tempList.Fields[fieldname] as SPFieldLookup;
                            SPList        parentList = web.Lists[lookupList];
                            fldLookup.LookupList  = parentList.ID.ToString();
                            fldLookup.LookupField = parentList.Fields[lookupfield].InternalName;
                            fldLookup.Update();
                            tempList.Update();

                            continue;
                        }
                    }
                }
            }
            web.Update();
            web.AllowUnsafeUpdates = true;
        }
        private void AddDependentLookups()
        {
            lock (this)
            {
                if (TempDependentLookups == null)
                {
                    return;
                }

                List <string> dependentFieldNames       = TempDependentLookups;
                List <string> actualDependentFieldNames = this.GetDependentLookupInternalNames();


                foreach (string actualDependentFieldName in actualDependentFieldNames)
                {
                    SPFieldLookup actualDependentLookup = (SPFieldLookup)fields.GetFieldByInternalName(actualDependentFieldName);

                    if (!dependentFieldNames.Contains(actualDependentLookup.LookupField))
                    {
                        // if site column then remove a references to the site column from all site columns
                        if (ParentList == null)
                        {
                            foreach (SPWeb web in fields.Web.Site.AllWebs)
                            {
                                // fresh site/web is needed because content type update concurrency issue
                                using (SPSite freshSite = new SPSite(web.Site.ID))
                                {
                                    using (SPWeb freshWeb = freshSite.OpenWeb(web.ID))
                                    {
                                        List <SPContentType> contentTypesToUpdate = new List <SPContentType>();

                                        foreach (SPContentType contentType in freshWeb.ContentTypes)
                                        {
                                            if (contentType.FieldLinks[actualDependentLookup.Id] != null)
                                            {
                                                contentType.FieldLinks.Delete(actualDependentLookup.Id);
                                                if (contentTypesToUpdate.Where(c => c.Id == contentType.Id).Count() == 0)
                                                {
                                                    contentTypesToUpdate.Add(contentType);
                                                }
                                            }
                                        }

                                        foreach (SPContentType spContentType in contentTypesToUpdate)
                                        {
                                            spContentType.Update(true);
                                        }
                                    }
                                }

                                web.Dispose();
                            }
                        }


                        fields.Delete(actualDependentFieldName);
                    }
                }

                using (SPWeb lookupWeb = fields.Web.Site.OpenWeb(this.LookupWebId))
                {
                    SPList lookupList = lookupWeb.Lists[new Guid(this.LookupList)];

                    foreach (string fieldName in dependentFieldNames)
                    {
                        SPFieldLookup alreadyExistingDependentLookupField =
                            fields.OfType <SPFieldLookup>().Where(
                                f =>
                                f.PrimaryFieldId == this.Id.ToString() &&
                                f.LookupField == fieldName)
                            .FirstOrDefault();

                        if (alreadyExistingDependentLookupField == null)
                        {
                            SPField fieldInLookupList =
                                (SPField)lookupList.Fields.GetFieldByInternalName(fieldName);

                            string projectedFieldName =
                                fields.AddDependentLookup(
                                    this.Title + ":" + fieldInLookupList.Title,
                                    this.Id);

                            SPFieldLookup projectedField =
                                (SPFieldLookup)fields.GetFieldByInternalName(projectedFieldName);
                            projectedField.LookupField = fieldInLookupList.InternalName;

                            projectedField.Update(true);
                        }
                    }
                }
            }
        }
示例#27
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);
            }
        }