/// <summary>
        /// Converts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>
        /// The converted value.
        /// </returns>
        public override object Convert(object value, DataRowConversionArguments arguments)
        {
            var lookupValue = value as SPFieldLookupValue;

            if (value == DBNull.Value)
            {
                return null;
            }

            if (lookupValue == null)
            {
                var stringValue = value as string;
                if (!string.IsNullOrEmpty(stringValue))
                {
                    lookupValue = new SPFieldLookupValue(stringValue);
                }
            }

            if (lookupValue != null)
            {
                var lookupField = new SPFieldLookup(arguments.FieldCollection, arguments.ValueKey);

                if (lookupField.LookupWebId == Guid.Empty || lookupField.LookupWebId == arguments.Web.ID)
                {
                    return GetLookupFieldValue(arguments.Web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId);
                }

                using (var web = arguments.Web.Site.OpenWeb(lookupField.LookupWebId))
                {
                    return GetLookupFieldValue(web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId);
                }
            }

            return null;
        }
        /// <summary>
        /// 获取一周的数据,按时间和优先级排序
        /// 开始日期作为查询条件,只选原子任务时行分配,排除操作等于所有的
        /// </summary>
        /// <returns></returns>
        private SPListItemCollection GetTasks()
        {
            string fldName             = "Task";//查阅项的字段名称,通过这个字段找父表的数据
            SPListItemCollection items = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Site.ID)) //找到网站集
                {
                    using (SPWeb spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        SPList spList = spWeb.Lists.TryGetList(webObj.SchedulelList);
                        if (spList != null)
                        {
                            SPFieldLookup task = spList.Fields.GetFieldByInternalName(fldName) as SPFieldLookup;
                            SPList taskList    = spWeb.Lists[new Guid(task.LookupList)];
                            SPQuery qry        = new SPQuery();
                            DateTime dtStart   = webObj.StartDate;
                            qry.ViewFields     = "<FieldRef Name='Title' /><FieldRef Name = 'StartDate' /><FieldRef Name = 'DueDate' /><FieldRef Name = 'EstimatedDuring' /><FieldRef Name = 'Action' />< FieldRef Name = 'AssignedTo' />";
                            qry.Query          = @"<Where><And><Neq>
         <FieldRef Name='Action' />
         <Value Type='Text'>所有</Value>
      </Neq><Or><And><Geq><FieldRef Name='StartDate' /><Value Type='DateTime'>"
                                                 + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(dtStart.ToShortDateString()))
                                                 + "</Value></Geq><Lt><FieldRef Name = 'StartDate' /><Value Type = 'DateTime'> "
                                                 + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(dtStart.AddDays(webObj.days).ToShortDateString()))
                                                 + " </Value></Lt></And><And><Geq><FieldRef Name='DueDate' /><Value Type='DateTime'>"
                                                 + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(dtStart.ToShortDateString()))
                                                 + "</Value></Geq><Lt><FieldRef Name = 'DueDate' /><Value Type = 'DateTime'> "
                                                 + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(dtStart.AddDays(webObj.days).ToShortDateString()))
                                                 + " </Value></Lt></And></Or></And></Where><OrderBy><FieldRef Name='StartDate' /><FieldRef Name='Priority' /></OrderBy>";
                            SPListItemCollection listItems = taskList.GetItems(qry);
                            if (listItems.Count > 0)
                            {
                                items = listItems;
                            }
                        }
                    }
                }
            });
            return(items);
        }
Beispiel #3
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;
        }
Beispiel #4
0
        private static ArrayList iGetAssociatedLists(SPList list)
        {
            ArrayList a = new ArrayList();

            foreach (SPList cList in list.ParentWeb.Lists)
            {
                try
                {
                    foreach (SPField field in cList.Fields)
                    {
                        if (field.Type == SPFieldType.Lookup)
                        {
                            SPFieldLookup fl = (SPFieldLookup)field;

                            if (fl.LookupList.ToLower() == "{" + list.ID.ToString().ToLower() + "}")
                            {
                                EPMLiveCore.GridGanttSettings gSets = (EPMLiveCore.GridGanttSettings)EPMLiveCore.Infrastructure.CacheStore.Current.Get("GGS", "GridSettings-" + cList.ID.ToString(), () =>
                                {
                                    return(new EPMLiveCore.GridGanttSettings(cList));
                                }).Value;

                                if (gSets.AssociatedItems)
                                {
                                    AssociatedListInfo lInfo = new AssociatedListInfo();

                                    lInfo.icon        = cList.ImageUrl;
                                    lInfo.LinkedField = field.InternalName;
                                    lInfo.ListId      = cList.ID;
                                    lInfo.Title       = cList.Title;

                                    a.Add(lInfo);
                                }
                                break;
                            }
                        }
                    }
                }
                catch { }
            }

            return(a);
        }
Beispiel #5
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();
        }
Beispiel #6
0
 public string GetAdditionalFields()
 {
     using (new EnterExitLogger("CCSCascadedLookupField:GetAdditionalFields function"))
     {
         string additionalFieldsString = "";
         if (this != null && this.ParentList != null)
         {
             for (int i = 0; i < this.ParentList.Fields.Count; i++)
             {
                 SPFieldLookup field = this.ParentList.Fields[i] as SPFieldLookup;
                 if (field != null && field.IsDependentLookup && field.PrimaryFieldId != null && field.PrimaryFieldId.Equals(this.Id.ToString(), StringComparison.InvariantCultureIgnoreCase))
                 {
                     additionalFieldsString = additionalFieldsString + ";#" + field.LookupField;
                 }
             }
         }
         Utils.LogManager.write("AdditionalFieldsString : " + additionalFieldsString);
         return(additionalFieldsString);
     }
 }
Beispiel #7
0
        static void TestLookupFields(SPWeb spWeb)
        {
            SPList
            //list = spWeb.Lists["Внутрішні документи"];
            //list = spWeb.Lists["Підрозділ організації"];
                list = spWeb.Lists["Рух вхідних документів"];

            SPListItem
                item = list.Items[0];

            string
                fieldName = "dn_ct_Recipient";

            SPField
            //field = item.Fields.GetFieldByInternalName("dn_ct_AuthorExecutor");
            //field = item.Fields["Автор-виконавець"];
                field = item.Fields.GetFieldByInternalName(fieldName);

            object tmpObject = item[fieldName];

            SPField            spField            = item[fieldName] as SPField;
            SPFieldLookup      spFieldLookup      = item[fieldName] as SPFieldLookup;
            SPFieldLookupValue spFieldLookupValue = item[fieldName] as SPFieldLookupValue;
            SPFieldUser        spFieldUser        = item[fieldName] as SPFieldUser;
            SPFieldUserValue   spFieldUserValue   = item[fieldName] as SPFieldUserValue;

            if ((spFieldUserValue = field.GetFieldValue(tmpObject.ToString()) as SPFieldUserValue) != null)
            {
                Console.WriteLine("LookupId: {0}", spFieldUserValue.LookupId);
            }

            SPFieldUserValueCollection spFieldUserValueCollection = item[fieldName] as SPFieldUserValueCollection;

            if ((spFieldUserValueCollection = field.GetFieldValue(tmpObject.ToString()) as SPFieldUserValueCollection) != null)
            {
                foreach (SPFieldUserValue _spFieldUserValue_ in spFieldUserValueCollection)
                {
                    Console.WriteLine("LookupId: {0}, LookupValue: {1}, User.ID: {2}, User.Name: {3}", _spFieldUserValue_.LookupId, _spFieldUserValue_.LookupValue, _spFieldUserValue_.User.ID, _spFieldUserValue_.User.Name);
                }
            }
        }
Beispiel #8
0
        private void SetupShims(bool canRead)
        {
            var fields = new SPFieldLookup[1];

            fields[0] = new ShimSPFieldLookup()
            {
                LookupListGet = () => Guid.Empty.ToString()
            };

            ShimSPField.AllInstances.TypeGet = _ => SPFieldType.Lookup;
            ShimSPBaseCollection.AllInstances.GetEnumerator = _ => fields.GetEnumerator();
            ShimCoreFunctions.getConfigSettingSPWebString   = (_, __) => DummyString;
            ShimCoreFunctions.getConnectionStringGuid       = _ => string.Empty;
            ShimSPFieldLookupValue.AllInstances.LookupIdGet = _ => 0;
            ShimSPFieldLookupValue.ConstructorString        = (_, __) => new ShimSPFieldLookupValue();
            ShimSPSecurity.RunWithElevatedPrivilegesSPSecurityCodeToRunElevated = codeToRun => codeToRun();

            ShimSqlConnection.AllInstances.Open = _ =>
            {
                _isConnectionOpenedCalled = true;
            };
            ShimSqlCommand.AllInstances.ExecuteNonQuery = _ =>
            {
                _isExecuteNonQueryCallCount++;
                return(0);
            };
            ShimSqlCommand.AllInstances.ExecuteReader = _ =>
            {
                _isExecuteNonQueryCallCount++;
                return(new ShimSqlDataReader());
            };
            ShimSqlConnection.AllInstances.DisposeBoolean = (_, __) =>
            {
                _isConnectionDisposeCalled = true;
            };
            ShimSqlCommand.AllInstances.DisposeBoolean = (_, __) =>
            {
                _sqlCommandDisposeCallCount++;
            };
            ShimSqlDataReader.AllInstances.Read = _ => canRead;
        }
Beispiel #9
0
        private void GetAvailableValues(SPFieldLookup f, ListBox ddl)
        {
            var lookupWeb = SPContext.Current.Web;

            SPList lookupList = lookupWeb.Lists[new Guid(f.LookupList)];
            string caml       = @"<Where><IsNull><FieldRef Name='ParentName' /></IsNull></Where><OrderBy><FieldRef Name='Title' /></OrderBy>";
            var    query      = new SPQuery()
            {
                Query = caml
            };
            var items = lookupList.GetItems(query);

            if (items != null && items.Count > 0)
            {
                foreach (SPListItem item in items)
                {
                    ddl.Items.Add(new ListItem(item[f.LookupField].ToString(), item.ID.ToString()));
                    GetAvailableValues(lookupList, f.LookupField, ddl, item.ID.ToString());
                }
            }
        }
Beispiel #10
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);
        }
        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);
        }
Beispiel #12
0
        public ArtDevField CreateFieldLookup(string Name, string ListUrl, string WebUrl = null)
        {
            SPList list = null; SPFieldLookup Field = null;

            if (WebUrl == null)
            {
                list  = this.Web().GetList(ListUrl);
                Field = NewOrRefLookup(Name, list);
            }
            else
            {
                using (SPSite site = new SPSite(this.site.Url))
                {
                    using (SPWeb web = site.OpenWeb(WebUrl))
                    {
                        list  = web.GetList(ListUrl);
                        Field = NewOrRefLookup(Name, list, web);
                    }
                }
            }
            ArtDevField ArtDevField = new ArtDevField(Field);

            return(ArtDevField);
        }
Beispiel #13
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;
                }
            }
        }
 private Dictionary<string, string> getLookupValues(SPFieldLookup fieldLookup)
 {
     Dictionary<string, string> ret = new Dictionary<string, string>();
     if (string.Compare(fieldLookup.LookupList, "Self") == 0 || string.IsNullOrEmpty(fieldLookup.LookupList))
     {
         return ret;
     }
     else
         using (SPWeb web = SPContext.Current.Site.OpenWeb(fieldLookup.LookupWebId))
         {
             SPList list = web.Lists[new Guid(fieldLookup.LookupList)];
             foreach (SPListItem item in list.Items)
                 if (item[fieldLookup.LookupField]!=null)
                     ret.Add(item.ID.ToString(), item[fieldLookup.LookupField].ToString());
         }
     return ret;
 }
Beispiel #15
0
        private void SleepT()

        {
            //lblMsg.Text = "正在进行,请稍等……";
            string       fldType       = "ActivityType"; //活动类型内部字段名
            string       fldCustAction = "CustAction";   //活动操作内部 字段名称
            string       fldAction     = "Action";       //操作内部字段名称
            string       siteUrl       = "http://localhost";
            string       webUrl        = txtSubWeb.Text;
            StreamWriter w             = new StreamWriter("c:\\action.txt", false);

            using (SPSite spSite = new SPSite(siteUrl)) //找到网站集
            {
                using (SPWeb spWeb = spSite.OpenWeb(webUrl))
                {
                    SPList lstAssistant = spWeb.Lists.TryGetList(txtListName.Text);
                    if (lstAssistant == null)
                    {
                        return;
                    }
                    SPFieldLookup fld                   = lstAssistant.Fields.GetFieldByInternalName(fldCustAction) as SPFieldLookup; //活动操作
                    string        fldActionTitle        = lstAssistant.Fields.GetFieldByInternalName(fldAction).Title;                //操作,后来的用活动操作替换了
                    string        fldTypeTitle          = lstAssistant.Fields.GetFieldByInternalName(fldType).Title;                  //活动类型,活动操作对应的类型
                    string        lstID                 = fld.LookupList;
                    SPList        lstType               = spWeb.Lists[new Guid(lstID)];                                               //查阅项所在的列表
                    string        fldActionTypeDispName = "";                                                                         //获取查阅项表中的类别字段显示名称,即活动操作的上级
                    foreach (SPField fldType1 in lstType.Fields)
                    {
                        if (fldType1.Type == SPFieldType.Lookup && !fldType1.Hidden)
                        {
                            fldActionTypeDispName = fldType1.Title;
                            break;
                        }
                    }
                    SPListItem itemType = null;
                    string     txtAction;
                    string     actiType;
                    int        i = 1;
                    SPListItem item;
                    this.Text = lstAssistant.ItemCount.ToString();
                    for (int j = int.Parse(txtStart.Text); j < lstAssistant.ItemCount; j++)//遍历所有的活动记录each (SPListItem item in lstAssistant.Items)
                    {
                        item = lstAssistant.Items[j];
                        if (item[fld.Title] == null)//进行填充
                        {
                            if (item[fldActionTitle] == null)
                            {
                                continue;
                            }
                            txtAction = item[fldActionTitle].ToString();
                            SPQuery qry = new SPQuery();
                            qry = new SPQuery();
                            //qry.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='Title' />";
                            qry.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + txtAction +
                                        "</Value></Eq></Where>";

                            SPListItemCollection myItems = lstType.GetItems(qry);
                            if (myItems.Count > 0)
                            {
                                itemType        = myItems[0];
                                item[fld.Title] = itemType.ID;
                            }
                            else
                            {
                                w.Write(txtAction);
                            }
                        }
                        else
                        {
                            SPFieldLookupValue custID = item[fld.Title] as SPFieldLookupValue;//获取自定义字段的值
                            if (custID == null)
                            {
                                custID = (item[fld.Title] as SPFieldLookupValueCollection)[0];
                            }

                            try
                            {
                                itemType = lstType.GetItemById(custID.LookupId);//查阅项数据行
                            }
                            catch (Exception ex)
                            {
                                w.Write("itemIDitem.ID" + " :lookupID: " + custID.LookupId + ":value:" + custID.LookupValue);
                                itemType = null;
                            }
                        }
                        if (itemType != null)
                        {
                            actiType           = GetActivityType(itemType, fldActionTypeDispName);
                            item[fldTypeTitle] = actiType;
                            item.SystemUpdate();
                        }
                        System.Threading.Thread.Sleep(1);          //没什么意思,单纯的执行延时
                        i = j + 1;
                        SetTextMessage(i, lstAssistant.ItemCount); // 100 * i / lstAssistant.ItemCount );

                        w.WriteLine(i.ToString());
                    }
                }
            }
            w.Close();
            w.Dispose();
        }
 public static string GetRelationshipDeleteBehavior(this SPFieldLookup field)
 {
     return(field.RelationshipDeleteBehavior.ToString());
 }
        /// <summary>
        /// Invoke on Feature Activation
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSite site = properties.Feature.Parent as SPSite;
                jobTitle = jobTitle + site.Url.ToString();
                // Delete Existing Timer Job If Installed
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name.Equals(jobTitle, StringComparison.InvariantCultureIgnoreCase))
                    {
                        job.Delete();
                    }
                }


                AlertJobdefinition objArchivalJob = new AlertJobdefinition(jobTitle, site.WebApplication);

                SPMinuteSchedule schedule = new SPMinuteSchedule();

                if (schedule != null)
                {
                    schedule.BeginSecond = 0;
                    schedule.EndSecond   = 59;
                    schedule.Interval    = 30;

                    objArchivalJob.Properties.Add(WebSiteURL_KeyName, site.Url);
                    objArchivalJob.Schedule = schedule;
                    objArchivalJob.Update();
                }

                //Creating Hidden List1
                SPWeb            web   = site.OpenWeb();
                SPListCollection lists = web.Lists;
                lists.Add("CCSAdvancedAlertsList", "CrowCanyon Advanced Alerts List", SPListTemplateType.GenericList);
                SPList newList = web.Lists["CCSAdvancedAlertsList"];
                newList.Fields.Add("WebID", SPFieldType.Text, false);
                newList.Fields.Add("ListID", SPFieldType.Text, false);
                newList.Fields.Add("ItemID", SPFieldType.Text, false);
                newList.Fields.Add("WhenToSend", SPFieldType.Choice, false);

                SPFieldChoice WhenToSendChoiceCol = (SPFieldChoice)newList.Fields["WhenToSend"];
                string[]      strdata             = new string[3];
                strdata[0] = "Immediate";
                strdata[1] = "Daily";
                strdata[2] = "Weekely";
                WhenToSendChoiceCol.Choices.Add(strdata[0]);
                WhenToSendChoiceCol.Choices.Add(strdata[1]);
                WhenToSendChoiceCol.Choices.Add(strdata[2]);
                WhenToSendChoiceCol.Update();
                newList.Fields.Add("DetailInfo", SPFieldType.Note, false);
                newList.Fields.Add("Owner", SPFieldType.User, false);
                newList.Fields.Add("EventType", SPFieldType.Choice, false);

                SPFieldChoice EventTypeChoiceCol = (SPFieldChoice)newList.Fields["EventType"];
                string[]      strdata1           = new string[4];
                strdata1[0] = "ItemAdded";
                strdata1[1] = "ItemUpdated";
                strdata1[2] = "ItemDeleted";
                strdata1[3] = "DateColumn";
                EventTypeChoiceCol.Choices.Add(strdata1[0]);
                EventTypeChoiceCol.Choices.Add(strdata1[1]);
                EventTypeChoiceCol.Choices.Add(strdata1[2]);
                EventTypeChoiceCol.Choices.Add(strdata1[3]);
                EventTypeChoiceCol.Update();
                newList.Fields.Add("SendDay", SPFieldType.Choice, false);

                SPFieldChoice SendDayChoiceCol = (SPFieldChoice)newList.Fields["SendDay"];
                string[]      strdata2         = new string[7];
                strdata2[0] = "1";
                strdata2[1] = "2";
                strdata2[2] = "3";
                strdata2[3] = "4";
                strdata2[4] = "5";
                strdata2[5] = "6";
                strdata2[6] = "7";
                SendDayChoiceCol.Choices.Add(strdata2[0]);
                SendDayChoiceCol.Choices.Add(strdata2[1]);
                SendDayChoiceCol.Choices.Add(strdata2[2]);
                SendDayChoiceCol.Choices.Add(strdata2[3]);
                SendDayChoiceCol.Choices.Add(strdata2[4]);
                SendDayChoiceCol.Choices.Add(strdata2[5]);
                SendDayChoiceCol.Choices.Add(strdata2[6]);
                SendDayChoiceCol.Update();
                newList.Fields.Add("SendHour", SPFieldType.Choice, false);

                SPFieldChoice SendHourChoiceCol = (SPFieldChoice)newList.Fields["SendHour"];
                string[]      strdata3          = new string[24];
                strdata3[0]  = "0";
                strdata3[1]  = "1";
                strdata3[2]  = "2";
                strdata3[3]  = "3";
                strdata3[4]  = "4";
                strdata3[5]  = "5";
                strdata3[6]  = "6";
                strdata3[7]  = "7";
                strdata3[8]  = "8";
                strdata3[9]  = "9";
                strdata3[10] = "10";
                strdata3[11] = "11";
                strdata3[12] = "12";
                strdata3[13] = "13";
                strdata3[14] = "14";
                strdata3[15] = "15";
                strdata3[16] = "16";
                strdata3[17] = "17";
                strdata3[18] = "18";
                strdata3[19] = "19";
                strdata3[20] = "20";
                strdata3[21] = "21";
                strdata3[22] = "22";
                strdata3[23] = "23";
                SendHourChoiceCol.Choices.Add(strdata3[0]);
                SendHourChoiceCol.Choices.Add(strdata3[1]);
                SendHourChoiceCol.Choices.Add(strdata3[2]);
                SendHourChoiceCol.Choices.Add(strdata3[3]);
                SendHourChoiceCol.Choices.Add(strdata3[4]);
                SendHourChoiceCol.Choices.Add(strdata3[5]);
                SendHourChoiceCol.Choices.Add(strdata3[6]);
                SendHourChoiceCol.Choices.Add(strdata3[7]);
                SendHourChoiceCol.Choices.Add(strdata3[8]);
                SendHourChoiceCol.Choices.Add(strdata3[9]);
                SendHourChoiceCol.Choices.Add(strdata3[10]);
                SendHourChoiceCol.Choices.Add(strdata3[11]);
                SendHourChoiceCol.Choices.Add(strdata3[12]);
                SendHourChoiceCol.Choices.Add(strdata3[13]);
                SendHourChoiceCol.Choices.Add(strdata3[14]);
                SendHourChoiceCol.Choices.Add(strdata3[15]);
                SendHourChoiceCol.Choices.Add(strdata3[16]);
                SendHourChoiceCol.Choices.Add(strdata3[17]);
                SendHourChoiceCol.Choices.Add(strdata3[18]);
                SendHourChoiceCol.Choices.Add(strdata3[19]);
                SendHourChoiceCol.Choices.Add(strdata3[20]);
                SendHourChoiceCol.Choices.Add(strdata3[21]);
                SendHourChoiceCol.Choices.Add(strdata3[22]);
                SendHourChoiceCol.Choices.Add(strdata3[23]);
                SendHourChoiceCol.Update();
                SPView view = newList.DefaultView;
                view.ViewFields.Add("WebID");
                view.ViewFields.Add("ListID");
                view.ViewFields.Add("ItemID");
                view.ViewFields.Add("WhenToSend");
                view.ViewFields.Add("DetailInfo");
                view.ViewFields.Add("Owner");
                view.ViewFields.Add("EventType");
                view.ViewFields.Add("SendDay");
                view.ViewFields.Add("SendHour");
                view.Update();
                newList.Hidden = true;
                newList.Update();

                //Creating Hidden List2
                lists.Add("CCSAdvancedAlertsMailTemplates", "CrowCanyon Advanced Alerts Mail Templates", SPListTemplateType.GenericList);
                SPList newList2 = web.Lists["CCSAdvancedAlertsMailTemplates"];
                newList2.Fields.Add("InsertUpdatedFields", SPFieldType.Boolean, false);
                newList2.Fields.Add("HighLightUpdatedFields", SPFieldType.Boolean, false);
                newList2.Fields.Add("InsertAttachments", SPFieldType.Boolean, false);
                newList2.Fields.Add("Owner", SPFieldType.User, false);
                newList2.Fields.Add("Subject", SPFieldType.Text, false);
                newList2.Fields.Add("Body", SPFieldType.Note, false);
                SPView view2 = newList2.DefaultView;
                view2.ViewFields.Add("InsertUpdatedFields");
                view2.ViewFields.Add("HighLightUpdatedFields");
                view2.ViewFields.Add("InsertAttachments");
                view2.ViewFields.Add("Owner");
                view2.ViewFields.Add("Subject");
                view2.ViewFields.Add("Body");
                view2.Update();
                newList2.Hidden = true;
                newList2.Update();

                // Creating Hidden List3
                lists.Add("CCSAdvancedTemplateForAlert", "CrowCanyon Advanced Template for alert", SPListTemplateType.GenericList);
                SPList newList3 = web.Lists["CCSAdvancedTemplateForAlert"];
                newList3.Fields.AddLookup("Template", newList2.ID, false);
                SPFieldLookup lkp = (SPFieldLookup)newList3.Fields["Template"];
                lkp.LookupField = newList2.Fields["Title"].InternalName;
                newList3.Fields.Add("EventType", SPFieldType.Choice, false);

                SPFieldChoice EventTypeChoiceCol2 = (SPFieldChoice)newList3.Fields["EventType"];
                string[]      strdata4            = new string[4];
                strdata4[0] = "ItemAdded";
                strdata4[1] = "ItemUpdated";
                strdata4[2] = "ItemDeleted";
                strdata4[3] = "DateColumn";
                EventTypeChoiceCol2.Choices.Add(strdata4[0]);
                EventTypeChoiceCol2.Choices.Add(strdata4[1]);
                EventTypeChoiceCol2.Choices.Add(strdata4[2]);
                EventTypeChoiceCol2.Choices.Add(strdata4[3]);
                EventTypeChoiceCol2.Update();
                newList3.Fields.Add("InsertUpdatedFields", SPFieldType.Boolean, false);
                newList3.Fields.Add("HighLightUpdatedFields", SPFieldType.Boolean, false);
                newList3.Fields.Add("InsertAttachments", SPFieldType.Boolean, false);
                newList3.Fields.AddLookup("Alert", newList.ID, false);
                SPFieldLookup lkp2 = (SPFieldLookup)newList3.Fields["Alert"];
                lkp2.LookupField = newList.Fields["Title"].InternalName;
                newList3.Update();
                SPView view3 = newList3.DefaultView;
                view3.ViewFields.Add("Template");
                view3.ViewFields.Add("EventType");
                view3.ViewFields.Add("InsertUpdatedFields");
                view3.ViewFields.Add("HighLightUpdatedFields");
                view3.ViewFields.Add("InsertAttachments");
                view3.ViewFields.Add("Alert");
                view3.Update();
                newList3.Hidden = true;
                newList3.Update();

                //Creating Hidden List 4
                lists.Add("CCSAdvancedDelayedAlerts", "CrowCanyon Advanced Delayed Alerts", SPListTemplateType.GenericList);
                SPList newList4 = web.Lists["CCSAdvancedDelayedAlerts"];
                newList4.Fields.Add("Subject", SPFieldType.Text, false);
                newList4.Fields.Add("Body", SPFieldType.Note, false);
                newList4.Fields.Add("EventType", SPFieldType.Choice, false);

                SPFieldChoice EventTypeChoiceCol3 = (SPFieldChoice)newList4.Fields["EventType"];
                string[]      strdata5            = new string[4];
                strdata5[0] = "ItemAdded";
                strdata5[1] = "ItemUpdated";
                strdata5[2] = "ItemDeleted";
                strdata5[3] = "DateColumn";
                EventTypeChoiceCol3.Choices.Add(strdata5[0]);
                EventTypeChoiceCol3.Choices.Add(strdata5[1]);
                EventTypeChoiceCol3.Choices.Add(strdata5[2]);
                EventTypeChoiceCol3.Choices.Add(strdata5[3]);
                EventTypeChoiceCol3.Update();
                newList4.Fields.AddLookup("Alert", newList.ID, false);
                SPFieldLookup lkp3 = (SPFieldLookup)newList4.Fields["Alert"];
                lkp3.LookupField = newList.Fields["Title"].InternalName;
                newList4.Fields.Add("ItemID", SPFieldType.Text, false);
                newList4.Update();
                SPView view4 = newList4.DefaultView;
                view4.ViewFields.Add("Subject");
                view4.ViewFields.Add("Body");
                view4.ViewFields.Add("EventType");
                view4.ViewFields.Add("Alert");
                view4.ViewFields.Add("ItemID");
                view4.Update();
                newList4.Hidden = true;
                newList4.Update();
            }
            catch (System.Exception Ex)
            {
            }
        }
Beispiel #18
0
        /// <summary>
        /// Gets the lookup value.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="spFieldLookup">The sp field lookup.</param>
        /// <param name="lookupValue">The lookup value.</param>
        /// <returns>
        /// Returns the SPFieldLookupValue instance of a lookup value.
        /// The ID value will be obtained using SPQuery.
        /// </returns>
        private SPFieldLookupValue GetLookupValue(Guid siteId, SPFieldLookup spFieldLookup, string lookupValue)
        {
            int    lookupId;
            string queryFormat =
                @"<Where>
                <Eq>
                    <FieldRef Name='{0}' />
                    <Value Type='Text'>{1}</Value>
                </Eq>
            </Where>";

            using (SPSite spSite = new SPSite(siteId))
                using (SPWeb spWeb = spSite.OpenWeb(spFieldLookup.LookupWebId))
                {
                    string queryText    = String.Format(CultureInfo.InvariantCulture, queryFormat, spFieldLookup.LookupField, lookupValue);
                    SPList lookupSPList = spWeb.Lists.GetList(new Guid(spFieldLookup.LookupList), false);

                    SPQuery spQuery = new SPQuery
                    {
                        ViewAttributes = "Scope=\"Recursive\"",
                        ViewFields     = "<FieldRef Name='ID'/>",
                        ViewFieldsOnly = true,
                        Query          = queryText
                    };

                    SPListItemCollection lookupSPListItems = lookupSPList.GetItems(spQuery);

                    if (lookupSPListItems.Count > 0)
                    {
                        lookupId = Convert.ToInt32(lookupSPListItems[0][SPBuiltInFieldId.ID], CultureInfo.InvariantCulture);
                        return(new SPFieldLookupValue(lookupId, lookupValue));
                    }
                    else
                    {
                        // when, as "lookup"-value, this function is passed the actual index ID,
                        // the following section will determine if an item with said ID exists in lookup list
                        if (int.TryParse(lookupValue, out lookupId))
                        {
                            queryFormat = @"<Where>
                                        <Eq>
                                            <FieldRef Name='ID' />
                                            <Value Type='Integer'>{0}</Value>
                                        </Eq>
                                        </Where>";
                            queryText   = String.Format(CultureInfo.InvariantCulture, queryFormat, lookupId);
                            spQuery     = new SPQuery
                            {
                                ViewAttributes = "Scope=\"Recursive\"",
                                ViewFields     =
                                    String.Format(
                                        CultureInfo.InvariantCulture, "<FieldRef Name='{0}'/>", spFieldLookup.LookupField),
                                ViewFieldsOnly = true,
                                Query          = queryText
                            };

                            lookupSPListItems = lookupSPList.GetItems(spQuery);

                            if (lookupSPListItems.Count > 0)
                            {
                                lookupValue = lookupSPListItems[0][spFieldLookup.LookupField] as string;
                                if (lookupValue != null)
                                {
                                    return(new SPFieldLookupValue(lookupId, lookupValue));
                                }
                            }
                        }
                        // no value found
                        return(null);
                    }
                }
        }
        private void ProcessLookupLists(XElement dataMapping, SPSite site, LogUtility logUtility, XElement fieldElement, SPFieldLookup lookupField, Guid webID, XElement contentType)
        {
            Guid listID = Guid.Empty;
            try
            {
                listID = new Guid(lookupField.LookupList);
            }
            catch (FormatException formatException)
            {
                logUtility.TraceDebugException(string.Format("Caught format Exception for field with id: {0} and title: {1}", lookupField.LookupField, lookupField.Title), GetType(), formatException);
            }

            if (!ListIDs.Contains(listID))
            {
                ListIDs.Add(listID);
                LookUpListProcess(dataMapping, site, logUtility, fieldElement, webID, listID, contentType);
            }
        }
Beispiel #20
0
        private void AddTypeAheadFieldControls(SPField fld)
        {
            if (mode == SPControlMode.New || mode == SPControlMode.Edit)
            {
                // this represents a comma separated list of lookup field internal names to modify
                EnhancedLookupConfigValuesHelper valueHelper = null;
                string            unprocessedModCandidates   = string.Empty;
                GridGanttSettings gSettings = new GridGanttSettings(this.list);

                try
                {
                    string rawValue = gSettings.Lookups;
                    //string rawValue = "Region^dropdown^none^none^xxx|State^autocomplete^Region^Region^xxx|City^autocomplete^State^State^xxx";
                    valueHelper = new EnhancedLookupConfigValuesHelper(rawValue);
                }
                catch { }

                if (valueHelper == null)
                {
                    return;
                }


                bool isEnhanced = valueHelper.ContainsKey(fld.InternalName);
                bool isParent   = valueHelper.IsParentField(fld.InternalName);

                if (!isEnhanced && !isParent)
                {
                    return;
                }

                LookupConfigData lookupData = valueHelper.GetFieldData(fld.InternalName);

                if (isParent && !isEnhanced)
                {
                    SPFieldLookup lookupFld = fld as SPFieldLookup;
                    if (!lookupFld.AllowMultipleValues)
                    {
                        CascadingLookupRenderControl ctrl = new CascadingLookupRenderControl();
                        if (lookupData == null)
                        {
                            lookupData          = new LookupConfigData();
                            lookupData.IsParent = true;
                        }
                        ctrl.LookupData  = lookupData;
                        ctrl.LookupField = lookupFld;

                        string customValue =
                            "<Data>" +
                            "<Param key=\"SPFieldType\">SPFieldUser</Param>" +
                            "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                            "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                            "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                            "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                            "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                            "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                            "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                            "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                            "<Param key=\"Required\">" + lookupFld.Required + "</Param>" +
                            GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                            "</Data>";

                        ctrl.CustomProperty = customValue;
                        FormField ff = this.GetFormFieldByField(fld);
                        if (ff != null)
                        {
                            ff.Parent.Controls.AddAfter(ff, ctrl);
                        }
                    }
                }
                else if (isParent && isEnhanced)
                {
                    if (lookupData.Type == GenericType)
                    {
                        #region INSERT EPMLIVE GENERIC PICKER CONTROL

                        picker = new GenericEntityEditor();
                        SPFieldLookup lookupFld = fld as SPFieldLookup;
                        picker.MultiSelect = lookupFld.AllowMultipleValues;

                        string customValue =
                            "<Data>" +
                            "<Param key=\"SPFieldType\"></Param>" +
                            "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                            "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                            "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                            "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                            "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                            "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                            "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                            "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                            GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                            "<Param key=\"Field\">" + lookupData.Field + "</Param>" +
                            "<Param key=\"ControlType\">" + lookupData.Type + "</Param>" +
                            "<Param key=\"Parent\">" + lookupData.Parent + "</Param>" +
                            "<Param key=\"ParentListField\">" + lookupData.ParentListField + "</Param>" +
                            "<Param key=\"Required\">" + lookupFld.Required.ToString() + "</Param>" +
                            "</Data>";

                        SPFieldLookupValueCollection lookupValCol = null;

                        if (mode == SPControlMode.New || (this.list.BaseTemplate == SPListTemplateType.DocumentLibrary && !string.IsNullOrEmpty(Page.Request[ModeParam]) && Page.Request[ModeParam] == Upload && mode == SPControlMode.Edit))
                        {
                            lookupValCol = GetQueryStringLookupVal(fld);
                        }
                        else
                        {
                            try
                            {
                                lookupValCol = new SPFieldLookupValueCollection(this.ListItem[lookupFld.Id].ToString());
                            }
                            catch { }
                        }

                        if (lookupValCol != null && lookupValCol.Count > 0)
                        {
                            ArrayList    alItems = new ArrayList();
                            PickerEntity entity;
                            foreach (SPFieldLookupValue v in lookupValCol)
                            {
                                entity             = new PickerEntity();
                                entity.Key         = v.LookupId.ToString();
                                entity.DisplayText = v.LookupValue;
                                entity.IsResolved  = true;
                                alItems.Add(entity);
                            }
                            picker.UpdateEntities(alItems);
                        }

                        picker.CustomProperty = customValue;

                        FormField ff = this.GetFormFieldByField(fld);
                        if (ff != null)
                        {
                            ff.Parent.Controls.AddAfter(ff, picker);
                        }

                        #endregion
                    }
                    else if (lookupData.Type == ModifiedType)
                    {
                        #region INSERT MODIFIED SP CONTROL

                        SPFieldLookup lookupFld = fld as SPFieldLookup;
                        if (!lookupFld.AllowMultipleValues)
                        {
                            CascadingLookupRenderControl cclrCtrl = new CascadingLookupRenderControl();
                            cclrCtrl.LookupData  = lookupData;
                            cclrCtrl.LookupField = lookupFld;

                            string customValue =
                                "<Data>" +
                                "<Param key=\"SPFieldType\">SPFieldUser</Param>" +
                                "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                                "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                                "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                                "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                                "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                                "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                                "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                                "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                                "<Param key=\"Required\">" + lookupFld.Required + "</Param>" +
                                GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                                "</Data>";

                            cclrCtrl.CustomProperty = customValue;

                            FormField ff = this.GetFormFieldByField(fld);
                            if (ff != null)
                            {
                                ff.Parent.Controls.AddAfter(ff, cclrCtrl);
                            }
                        }

                        #endregion
                    }
                }
                else if (!isParent && isEnhanced)
                {
                    if (lookupData.Type == GenericType)
                    {
                        #region INSERT EPMLIVE GENERIC PICKER CONTROL

                        picker = new GenericEntityEditor();
                        SPFieldLookup lookupFld = fld as SPFieldLookup;
                        picker.MultiSelect = lookupFld.AllowMultipleValues;

                        string customValue =
                            "<Data>" +
                            "<Param key=\"SPFieldType\">SPFieldUser</Param>" +
                            "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                            "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                            "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                            "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                            "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                            "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                            "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                            "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                            GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                            "<Param key=\"Field\">" + lookupData.Field + "</Param>" +
                            "<Param key=\"ControlType\">" + lookupData.Type + "</Param>" +
                            "<Param key=\"Parent\">" + lookupData.Parent + "</Param>" +
                            "<Param key=\"ParentListField\">" + lookupData.ParentListField + "</Param>" +
                            "<Param key=\"Required\">" + lookupFld.Required.ToString() + "</Param>" +
                            "</Data>";

                        SPFieldLookupValueCollection lookupValCol = null;

                        if (mode == SPControlMode.New || (this.list.BaseTemplate == SPListTemplateType.DocumentLibrary && !string.IsNullOrEmpty(Page.Request[ModeParam]) && Page.Request[ModeParam] == Upload && mode == SPControlMode.Edit))
                        {
                            lookupValCol = GetQueryStringLookupVal(fld);
                        }
                        else
                        {
                            try
                            {
                                lookupValCol = new SPFieldLookupValueCollection(this.ListItem[lookupFld.Id].ToString());
                            }
                            catch { }
                        }

                        if (lookupValCol != null && lookupValCol.Count > 0)
                        {
                            ArrayList    alItems = new ArrayList();
                            PickerEntity entity;
                            foreach (SPFieldLookupValue v in lookupValCol)
                            {
                                entity             = new PickerEntity();
                                entity.Key         = v.LookupId.ToString();
                                entity.DisplayText = v.LookupValue;
                                entity.IsResolved  = true;
                                alItems.Add(entity);
                            }
                            picker.UpdateEntities(alItems);
                        }

                        picker.CustomProperty = customValue;

                        FormField ff = this.GetFormFieldByField(fld);
                        if (ff != null)
                        {
                            ff.Parent.Controls.AddAfter(ff, picker);
                        }


                        #endregion
                    }
                    else if (lookupData.Type == ModifiedType)
                    {
                        #region INSERT MODIFIED SP CONTROL

                        SPFieldLookup lookupFld = fld as SPFieldLookup;
                        if (!lookupFld.AllowMultipleValues)
                        {
                            CascadingLookupRenderControl cclrCtrl = new CascadingLookupRenderControl();
                            cclrCtrl.LookupData  = lookupData;
                            cclrCtrl.LookupField = lookupFld;

                            string customValue =
                                "<Data>" +
                                "<Param key=\"SPFieldType\">SPFieldUser</Param>" +
                                "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                                "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                                "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                                "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                                "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                                "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                                "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                                "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                                "<Param key=\"Required\">" + lookupFld.Required + "</Param>" +
                                GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                                "</Data>";

                            cclrCtrl.CustomProperty = customValue;

                            FormField ff = this.GetFormFieldByField(fld);
                            if (ff != null)
                            {
                                ff.Parent.Controls.AddAfter(ff, cclrCtrl);
                            }
                        }
                        else
                        {
                            CascadingMultiLookupRenderControl cclrCtrl = new CascadingMultiLookupRenderControl();
                            cclrCtrl.LookupData  = lookupData;
                            cclrCtrl.LookupField = lookupFld;

                            string customValue =
                                "<Data>" +
                                "<Param key=\"SPFieldType\">SPFieldUser</Param>" +
                                "<Param key=\"ParentWebID\">" + lookupFld.ParentList.ParentWeb.ID.ToString() + "</Param>" +
                                "<Param key=\"LookupWebID\">" + lookupFld.LookupWebId.ToString() + "</Param>" +
                                "<Param key=\"LookupListID\">" + lookupFld.LookupList + "</Param>" +
                                "<Param key=\"LookupFieldInternalName\">" + lookupFld.LookupField + "</Param>" +
                                "<Param key=\"LookupFieldID\">" + lookupFld.Id + "</Param>" +
                                "<Param key=\"IsMultiSelect\">" + lookupFld.AllowMultipleValues.ToString() + "</Param>" +
                                "<Param key=\"ListID\">" + this.ListId.ToString() + "</Param>" +
                                "<Param key=\"ItemID\">" + this.ItemId.ToString() + "</Param>" +
                                "<Param key=\"Required\">" + lookupFld.Required + "</Param>" +
                                GenerateControlDataForLookupField(fld, lookupFld.AllowMultipleValues) +
                                "</Data>";

                            cclrCtrl.CustomProperty = customValue;

                            FormField ff = this.GetFormFieldByField(fld);
                            if (ff != null)
                            {
                                ff.Parent.Controls.AddAfter(ff, cclrCtrl);
                            }
                        }

                        #endregion
                    }
                }
            }
        }
Beispiel #21
0
        private string GetFieldValue(SPField field, SPListItemVersion version)
        {
            string      fieldValue = string.Empty;
            SPFieldType fieldType  = field.Type;

            switch (fieldType)
            {
            case SPFieldType.Lookup:
                SPFieldLookup newField = (SPFieldLookup)field;
                fieldValue = newField.GetFieldValueAsText(version[field.StaticName]);
                break;

            case SPFieldType.User:
                SPFieldUser newUser = (SPFieldUser)field;
                fieldValue = newUser.GetFieldValueAsText(version[field.StaticName]);
                break;

            case SPFieldType.ModStat:
                SPFieldModStat modStat = (SPFieldModStat)field;
                fieldValue = modStat.GetFieldValueAsText(version[field.StaticName]);
                break;

            case SPFieldType.URL:
                SPFieldUrl urlField = (SPFieldUrl)field;
                fieldValue = urlField.GetFieldValueAsHtml(version[field.StaticName]);
                break;

            case SPFieldType.DateTime:
                SPFieldDateTime newDateField = (SPFieldDateTime)field;
                if (!string.IsNullOrEmpty(newDateField.GetFieldValueAsText(version[field.StaticName])))
                {
                    if (newDateField.DisplayFormat == SPDateTimeFieldFormatType.DateTime)
                    {
                        fieldValue = DateTime.Parse(newDateField.GetFieldValueAsText(version[field.StaticName])).ToString();
                    }
                    else
                    {
                        fieldValue = DateTime.Parse(newDateField.GetFieldValueAsText(version[field.StaticName])).ToShortDateString();
                    }
                }
                break;

            case SPFieldType.Invalid:

                // http://sharepointnadeem.blogspot.com/2013/09/sharepoint-spfieldtype-is-invalid-for.html
                if (field.TypeAsString.Equals("TaxonomyFieldType") || field.TypeAsString.Equals("TaxonomyFieldTypeMulti"))
                {
                    TaxonomyField taxonomyField = field as TaxonomyField;
                    fieldValue = taxonomyField.GetFieldValueAsText(version[field.StaticName]);
                }
                else
                {
                    fieldValue = version[field.StaticName].ToString();
                }
                break;

            default:
                fieldValue = version[field.StaticName].ToString();
                break;
            }

            return(fieldValue);
        }
Beispiel #22
0
        private SPFieldLookupValueCollection GetQueryStringLookupVal(FormField currentFld)
        {
            if (string.IsNullOrEmpty(lookupField) || !currentFld.Field.InternalName.Equals(lookupField))
            {
                return(null);
            }

            SPFieldLookupValueCollection result = new SPFieldLookupValueCollection();
            // assume single lookup
            bool       valIsMulti = false;
            List <int> ids        = new List <int>();

            if (!string.IsNullOrEmpty(this.lookupValue))
            {
                valIsMulti = this.lookupValue.Contains(',');
                if (valIsMulti)
                {
                    string[] sIds = this.lookupValue.Split(',');
                    foreach (string s in sIds)
                    {
                        if (!string.IsNullOrEmpty(s.Trim()))
                        {
                            ids.Add(int.Parse(s));
                        }
                    }
                }
            }

            //List<FormField> formFields = this.GetFormFieldByType(typeof(SPFieldLookup));
            List <FormField> modCandidates = new List <FormField>()
            {
                currentFld
            };

            for (int index = 0; index < modCandidates.Count; index++)
            {
                SPField       spFld     = modCandidates[index].Field;
                SPFieldLookup lookupFld = modCandidates[index].Field as SPFieldLookup;
                bool          isMulti   = lookupFld.AllowMultipleValues;

                // insert single value to single lookup field
                if (!isMulti && !valIsMulti)
                {
                    int itemId;
                    if (int.TryParse(lookupValue.Trim(), out itemId))
                    {
                        result.Add(new SPFieldLookupValue(itemId, GetLookupItemValue(lookupFld, itemId)));
                    }
                }
                // insert multi lookup value to multi lookup field
                else if (isMulti && valIsMulti)
                {
                    foreach (int id in ids)
                    {
                        result.Add(new SPFieldLookupValue(id, GetLookupItemValue(lookupFld, id)));
                    }
                }
            }

            return(result);
        }
        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);
                        }
                    }
                }
            }
        }
        private Control generateLookupControl(Control control, SPFieldLookup fieldLookup, string displayValue)
        {
            Dictionary<string, string> lookupValues = getLookupValues(fieldLookup);
            if (fieldLookup.AllowMultipleValues == false)
            {
                DropDownList ddlValueLookup = new DropDownList();
                foreach (KeyValuePair<string, string> k in lookupValues)
                {
                    ddlValueLookup.Items.Add(new ListItem(k.Value, k.Key));
                }

                ddlValueLookup.Items.Insert(0, string.Empty);
                string[] arr = displayValue.Split(";#".ToCharArray());

                SetDropDownListValue(ddlValueLookup, arr[0]);
                control = ddlValueLookup;
            }
            else
            {
                CheckBoxList chkValueMultiLookup = new CheckBoxList();
                string[] arr = displayValue.Split(SEPARATOR.ToCharArray());

                foreach (KeyValuePair<string, string> k in lookupValues)
                {
                    ListItem item = new ListItem() {Value = k.Key, Text = k.Value, Selected = arr.Contains(k.Key + ";#" + k.Value) };
                    chkValueMultiLookup.Items.Add(item);
                }
                HtmlGenericControl div = new HtmlGenericControl("div");
                div.Attributes.Add("style", "overflow: auto;height:100px;width:100%;");
                div.Controls.Add(chkValueMultiLookup);

                control = div;
            }
            return control;
        }
Beispiel #25
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();
            }
        }
        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();
            }
        }
Beispiel #27
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);
        }
Beispiel #28
0
        private static string GetFieldType(SPField oField, out string senum, out string senumkeys, out string sFormat, out string sRange, SPWeb oWeb)
        {
            var currencyFormatDictionary = new Dictionary <int, string> {
                { 0, "$n" }, { 1, "n$" }, { 2, "$ n" }, { 3, "n $" }
            };

            senum     = "";
            senumkeys = "";
            sFormat   = "";
            sRange    = "";

            switch (oField.Type)
            {
            case SPFieldType.Boolean:
                return("Bool");

            case SPFieldType.DateTime:
                SPFieldDateTime oDTField   = (SPFieldDateTime)oField;
                string          dateFormat = GetExampleDateFormat(oWeb, "yyyy", "M", "d");
                sFormat = oDTField.GetProperty("Format").Equals("DateOnly") ? dateFormat : string.Format("{0} h:mm tt", dateFormat);
                return("Date");

            case SPFieldType.Currency:
                var currenvyCultureInfo           = new CultureInfo(((SPFieldCurrency)oField).CurrencyLocaleId);
                NumberFormatInfo numberFormatInfo = currenvyCultureInfo.NumberFormat;

                sFormat = currencyFormatDictionary[numberFormatInfo.CurrencyPositivePattern]
                          .Replace("$", numberFormatInfo.CurrencySymbol)
                          .Replace("n",
                                   string.Format(",0.{0}", new string('0', numberFormatInfo.CurrencyDecimalDigits)));
                return("Float");

            case SPFieldType.Note:
                SPFieldMultiLineText field = (SPFieldMultiLineText)oField;
                if (field.RichText)
                {
                    return("Html");
                }
                else
                {
                    return("Lines");
                }

            case SPFieldType.Number:
                string percentageSign = string.Empty;

                if (((SPFieldNumber)oField).ShowAsPercentage)
                {
                    //sFormat = "0\\%;0\\%;0\\%";
                    return("Float");
                }

                switch (((SPFieldNumber)oField).DisplayFormat)
                {
                case SPNumberFormatTypes.Automatic:
                    sFormat = ",#0.##########" + percentageSign;
                    break;

                case SPNumberFormatTypes.NoDecimal:
                    sFormat = ",#0" + percentageSign;
                    break;

                case SPNumberFormatTypes.OneDecimal:
                    sFormat = ",#0.0" + percentageSign;
                    break;

                case SPNumberFormatTypes.TwoDecimals:
                    sFormat = ",#0.00" + percentageSign;
                    break;

                case SPNumberFormatTypes.ThreeDecimals:
                    sFormat = ",#0.000" + percentageSign;
                    break;

                case SPNumberFormatTypes.FourDecimals:
                    sFormat = ",#0.0000" + percentageSign;
                    break;

                case SPNumberFormatTypes.FiveDecimals:
                    sFormat = ",#0.00000" + percentageSign;
                    break;
                }
                return("Float");

            case SPFieldType.Choice:
                SPFieldChoice oCField = (SPFieldChoice)oField;
                foreach (string sChoice in oCField.Choices)
                {
                    senum += ";" + sChoice;
                }
                return("Enum");

            case SPFieldType.Lookup:
                SPFieldLookup oLField = (SPFieldLookup)oField;
                if (oLField.AllowMultipleValues)
                {
                    sRange = "1";
                }

                SPList oLookupList = oWeb.Lists[new Guid(oLField.LookupList)];

                foreach (SPListItem li in oLookupList.Items)
                {
                    senum     += ";" + li.Title.Replace(";", "");
                    senumkeys += ";" + li.ID;
                }

                return("Enum");

            case SPFieldType.MultiChoice:
                SPFieldMultiChoice oMCField = (SPFieldMultiChoice)oField;
                foreach (string sChoice in oMCField.Choices)
                {
                    senum += ";" + sChoice;
                }
                sRange = "1";
                return("Enum");

            case SPFieldType.User:

                DataTable dtResources = EPMLiveCore.API.APITeam.GetResourcePool("<Pool><Columns>SimpleColumns</Columns></Pool>", oWeb);

                foreach (DataRow dr in dtResources.Rows)
                {
                    senum     += ";" + dr["Title"].ToString();
                    senumkeys += ";" + dr["SPID"].ToString();
                }

                SPFieldUser oUField = (SPFieldUser)oField;
                if (oUField.AllowMultipleValues)
                {
                    sRange = "1";
                }
                return("Enum");

            default:
                return("Text");
            }
        }
        /// <summary>
        /// Sets the lookup to a list.
        /// </summary>
        /// <param name="lookupField">The lookup field.</param>
        /// <param name="lookupList">The lookup list.</param>
        /// <exception cref="System.ArgumentNullException">
        /// The parameter 'lookupField' cannot be null.;lookupField
        /// or
        /// The parameter 'lookupList' cannot be null.;lookupList
        /// </exception>
        public void SetLookupToList(SPFieldLookup lookupField, SPList lookupList)
        {
            if (lookupField == null)
            {
                throw new ArgumentNullException("The parameter 'lookupField' cannot be null.", "lookupField");
            }

            if (lookupList == null)
            {
                throw new ArgumentNullException("The parameter 'lookupList' cannot be null.", "lookupList");
            }

            this._logger.Info("Start method 'SetLookupToList' for field with id '{0}'", lookupField.Id);

            // Get the fields schema xml.
            XDocument fieldSchema = XDocument.Parse(lookupField.SchemaXml);
            XElement root = fieldSchema.Root;

            // Reset the attributes list and source id.
            root.SetAttributeValue("List", lookupList.ID);
            root.SetAttributeValue("SourceID", lookupList.ParentWeb.ID);

            // Update the lookup field.
            lookupField.SchemaXml = fieldSchema.ToString();

            this._logger.Info("End method 'SetLookupToList'.");
        }
Beispiel #30
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;
        }
Beispiel #31
0
        private void GetAvailableValues(SPFieldLookup f, ListBox ddl)
        {
            var lookupWeb = SPContext.Current.Web;

            SPList lookupList = lookupWeb.Lists[new Guid(f.LookupList)];
            string caml = @"<Where><IsNull><FieldRef Name='ParentName' /></IsNull></Where><OrderBy><FieldRef Name='Title' /></OrderBy>";
            var query = new SPQuery()
            {
                Query = caml
            };
            var items = lookupList.GetItems(query);
            if (items != null && items.Count > 0)
            {
                foreach (SPListItem item in items)
                {
                    ddl.Items.Add(new ListItem(item[f.LookupField].ToString(), item.ID.ToString()));
                    GetAvailableValues(lookupList, f.LookupField, ddl, item.ID.ToString());
                }
            }
        }
Beispiel #32
0
        //活动动类型、结果更新
        private void UpdateActivityType(SPItemEventProperties properties)
        {
            string        actiType = "";
            string        fldName  = "CustAction";
            SPFieldLookup fld      = properties.List.Fields.GetFieldByInternalName(fldName) as SPFieldLookup;

            if (properties.ListItem[fld.Title] == null)
            {
                return;
            }
            SPWeb spWeb1 = properties.Web;

            if (properties.List.Fields.ContainsFieldWithStaticName(fldName))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(spWeb1.Site.ID)) //找到网站集
                    {
                        using (SPWeb spWeb = spSite.OpenWeb(spWeb1.ID))
                        {
                            //SPList lst = spWeb.Lists.TryGetList(properties.List.Title);
                            //SPField fld = lst.Fields.GetFieldByInternalName(fldName);

                            string lstID   = fld.LookupList;
                            SPList lstType = spWeb.Lists[new Guid(lstID)];//查阅项所在的列表

                            SPFieldLookupValue custID = properties.ListItem[fld.Title] as SPFieldLookupValue;
                            if (custID == null)
                            {
                                custID = (properties.ListItem[fld.Title] as SPFieldLookupValueCollection)[0];
                            }
                            SPListItem itemType = lstType.GetItemById(custID.LookupId);
                            foreach (SPField fldType in lstType.Fields)
                            {
                                if (fldType.Type == SPFieldType.Lookup && !fldType.Hidden)
                                {
                                    SPFieldLookupValue fldValue = itemType[fldType.Id] as SPFieldLookupValue;
                                    if (fldValue == null)
                                    {
                                        fldValue = new SPFieldLookupValue(itemType[fldType.Id].ToString());
                                    }
                                    actiType = fldValue.LookupValue;
                                    break;
                                }
                            }
                            bool isSave = false;
                            if (properties.ListItem["ActivityType"] == null || properties.ListItem["ActivityType"].ToString() != actiType)
                            {
                                properties.ListItem["ActivityType"] = actiType;
                                isSave = true;
                            }

                            //更新结果
                            string resultTitle = properties.List.Fields.GetFieldByInternalName("Result").Title;
                            //if (properties.ListItem[resultTitle] == null)
                            //{
                            SPList sList = spWeb.Lists[properties.ListTitle + "结果"];
                            SPQuery qry  = new SPQuery();

                            //当前个人学习记录的文档
                            qry.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='Author' /><FieldRef Name='Result' /><FieldRef Name='AssistantID' /><FieldRef Name='Title' /><FieldRef Name='Created' />";

                            qry.Query = @"<Where><Eq><FieldRef Name='AssistantID'/><Value Type='Number'>" + properties.ListItemId + "</Value></Eq></Where>";

                            SPListItemCollection docITems = sList.GetItems(qry);
                            if (docITems.Count > 0)//
                            {
                                properties.ListItem[resultTitle] = docITems[0]["Result"]; isSave = true;
                            }

                            //}
                            if (isSave)
                            {
                                this.EventFiringEnabled = false;
                                properties.ListItem.SystemUpdate();
                                this.EventFiringEnabled = true;
                            }
                        }
                    }
                });
            }
        }
Beispiel #33
0
        private static void CreateMetadataPair(List <GuidewireWS.trg_MetadataPair> metadata, string key, string propertyName, SPListItem item)
        {
            try
            {
                GuidewireWS.trg_MetadataPair metadataPair = new GuidewireWS.trg_MetadataPair();
                //SPListItem listItem = properties.ListItem;
                SPListItem listItem = item;
                if (listItem.Fields.ContainsField(propertyName))
                {
                    metadataPair.key = key;
                    SPField propertyField = listItem.Fields[propertyName];
                    switch (propertyField.Type)
                    {
                    case SPFieldType.User:
                    {
                        SPFieldUser      userField      = propertyField as SPFieldUser;
                        SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(listItem[propertyName].ToString());
                        if (userFieldValue != null && userFieldValue.User != null)
                        {
                            metadataPair.value = userFieldValue.User.Name;
                        }
                        else
                        {
                            metadataPair.value = (string)listItem[propertyName];
                        }
                    }
                    break;

                    case SPFieldType.Lookup:
                    {
                        SPFieldLookup      lookupField      = propertyField as SPFieldLookup;
                        SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString());
                        if (lookupFieldValue != null && lookupFieldValue.LookupValue != null)
                        {
                            metadataPair.value = lookupFieldValue.LookupValue;
                        }
                    }
                    break;

                    // Bamboo selectors have type of invalid but work like lookup
                    case SPFieldType.Invalid:
                    {
                        if (listItem[propertyName] != null)
                        {
                            if (propertyField.TypeAsString == "BusinessData")
                            {
                                metadataPair.value = (string)listItem[propertyName];
                            }
                            else
                            {
                                SPFieldLookup      lookupField      = propertyField as SPFieldLookup;
                                SPFieldLookupValue lookupFieldValue = (SPFieldLookupValue)lookupField.GetFieldValue(listItem[propertyName].ToString());
                                if (lookupFieldValue != null && lookupFieldValue.LookupValue != null)
                                {
                                    metadataPair.value = lookupFieldValue.LookupValue;
                                }
                            }
                        }
                    }
                    break;

                    case SPFieldType.DateTime:
                    {
                        metadataPair.value = listItem[propertyName].ToString();
                    }
                    break;

                    default:
                        if (listItem[propertyName] != null)
                        {
                            if (propertyName == "Name")
                            {
                                String fileName = (string)listItem[propertyName];
                                if (fileName.Length > 80)
                                {
                                    String extension = fileName.Substring(fileName.LastIndexOf("."));
                                    String name      = fileName.Substring(0, fileName.Length - extension.Length);
                                    fileName = name.Substring(0, 80 - extension.Length) + extension;
                                }
                                metadataPair.value = fileName;
                            }
                            else
                            {
                                metadataPair.value = (string)listItem[propertyName];
                            }
                        }
                        break;
                    }
                    metadata.Add(metadataPair);
                }
            }
            catch (Exception e)
            {
                LogError("CreateMetadataPair failed with exception: " + e.Message);
            }
        }
Beispiel #34
0
        private static void WriteMyAction(SPWeb spWeb1, int userID, string action)
        {
            string listMyAction = "我的操作";
            string spFieldName  = "ActionID";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(spWeb1.Site.ID))  //找到网站集
                {
                    using (SPWeb spWeb = spSite.OpenWeb(spWeb1.ID))
                    {
                        SPList lstMyAction = spWeb.Lists.TryGetList(listMyAction); //有查阅项的列表,我的操作
                        SPFieldLookup task = lstMyAction.Fields.GetFieldByInternalName(spFieldName) as SPFieldLookup;
                        SPList lstAction   = spWeb.Lists[new Guid(task.LookupList)];
                        SPQuery qry        = new SPQuery();
                        SPListItem newItem;
                        int actionID;
                        if (lstAction != null)
                        {//主表查询
                            qry            = new SPQuery();
                            qry.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='Title' />";
                            qry.Query      = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + action +
                                             "</Value></Eq></Where>";

                            SPListItemCollection myItems = lstAction.GetItems(qry);
                            if (myItems.Count == 0)//没有此操作则添加
                            {
                                newItem          = lstAction.Items.Add();
                                newItem["Title"] = action;
                                newItem.Update();
                            }
                            else
                            {
                                newItem = myItems[0];
                            }
                            actionID = newItem.ID;
                            //子表查询 Frequecy字段名称中少一个n Frequency
                            qry            = new SPQuery();
                            qry.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='User' /><FieldRef Name='ActionID' /><FieldRef Name='Frequency' />";
                            qry.Query      = @"<Where><And><Eq><FieldRef Name='User' LookupId='True' /><Value Type='Integer'>" + userID +
                                             "</Value></Eq><Eq><FieldRef Name='ActionID' LookupId='True' /><Value Type='Lookup'>" + actionID + "</Value></Eq></And></Where>";

                            myItems = lstMyAction.GetItems(qry);
                            if (myItems.Count == 0)//没有此操作则添加
                            {
                                newItem              = lstMyAction.Items.Add();
                                newItem["ActionID"]  = actionID;
                                newItem["User"]      = userID;
                                newItem["Frequency"] = 1;
                                newItem.Update();
                            }
                            else
                            {
                                newItem = myItems[0];
                                newItem["Frequency"] = (int)newItem["Frequency"] + 1;
                                newItem.Update();
                            }
                        }
                    }
                }
            });
        }
Beispiel #35
0
        /// <summary>
        /// 填充自上向下的级别数
        /// </summary>
        /// <returns></returns>
        private void FillChildLevel(List <int> selectedValues, int level)
        {
            CustomConcatenatedField f   = (CustomConcatenatedField)base.Field;
            SPFieldLookup           fld = GetCascadedField;

            ListItem[] items;
            bool       multiLevel = MultiLevel;
            int        tEnd       = selectedValues.Count - 1;//只有两级时,查阅项字段在另一个列表中,否则遍历会进入死
            bool       allowAdd   = false;

            if (tEnd == 0)//类别下操作为空,会出错2018-11-16
            {
                tEnd     = 1;
                allowAdd = true;
            }
            //循环
            string ddlID;

            if (multiLevel)
            {
                tEnd = selectedValues.Count;
            }
            int           parentID;
            HtmlTableRow  row;
            HtmlTableCell cell;

            for (int i = 0; i < tEnd; i++)
            {
                parentID = selectedValues[i];
                List <ListItem> lstDesc = new List <System.Web.UI.WebControls.ListItem>();
                items       = GetListItems(f.LookupList, f.LookupField, fld.InternalName, parentID, ref lstDesc);
                ddlID       = "DropDownList" + level;
                this.ddlNew = (DropDownList)TemplateContainer.FindControl(ddlID);
                if (items.Length > 0 || allowAdd)//还有下一级
                {
                    if (ddlNew == null)
                    {
                        ddlNew    = new DropDownList();
                        ddlNew.ID = ddlID;
                        if (f.SPLookupWidth != "")
                        {
                            ddlNew.Width = int.Parse(f.SPLookupWidth);
                        }
                        row  = new HtmlTableRow();
                        cell = new HtmlTableCell();
                        cell.Controls.Add(ddlNew);
                        row.Cells.Add(cell);
                        tblLevel.Rows.Add(row);

                        cell = new HtmlTableCell();
                        row.Cells.Add(cell);
                        tblLevel.Rows.Add(row);
                    }
                    else
                    {
                        if (f.SPLookupWidth != "")
                        {
                            ddlNew.Width = int.Parse(f.SPLookupWidth);
                        }
                    }
                    if (multiLevel)
                    {
                        ddlNew.AutoPostBack          = true;
                        ddlNew.SelectedIndexChanged += Ddl_SelectedIndexChanged;
                    }
                    ddlNew.Items.Clear();
                    ddlNew.Items.AddRange(items);
                    if ((i + 1) < selectedValues.Count)
                    {
                        ddlNew.SelectedValue = selectedValues[i + 1].ToString();
                    }
                    level = level + 1;
                }
            }
            //保留最后一级的选项
            if (multiLevel)
            {
                ViewState["lastID"] = selectedValues[tEnd - 1].ToString();//保留最后一级当前所选ID,临时的
                //txtCustAction.Visible = false;
                spanTxtDesc.Visible = false;
            }
            else//二级的,添加自定义操作
            {
                ViewState["lastID"] = null;
                this.txtCustAction  = (TextBox)TemplateContainer.FindControl("txtNewAction");//动态加的
                if (txtCustAction == null)
                {
                    TextBox txtNewAction = new TextBox();
                    txtNewAction.ID = "txtNewAction";

                    if (f.SPLookupWidth != "")
                    {
                        txtNewAction.Width = int.Parse(f.SPLookupWidth) - 10;
                    }
                    //txtCustAction.Visible = true;

                    tblLevel.Rows[level - 2].Cells[1].Controls.Add(txtNewAction);
                }
                spanTxtDesc.Visible = true;
            }
            //原来的是三级,更改选项后变成了两级,级别减少了
            for (int j = tblLevel.Rows.Count; j >= level; j--)
            {
                tblLevel.Rows.RemoveAt(j - 1);
            }
        }
        public void execute(SPSite site, SPWeb web, Guid listId, int itemId, int userid, string data)
        {
            SPList            list        = null;
            SPListItem        li          = null;
            GridGanttSettings settings    = null;
            List <string>     cNewGrps    = null;
            List <string>     fields      = null;
            SPUser            orignalUser = null;
            EnhancedLookupConfigValuesHelper valueHelper = null;
            SPList             lookupPrntList            = null;
            GridGanttSettings  prntListSettings          = null;
            SPFieldLookupValue lookupVal  = null;
            SPListItem         targetItem = null;

            try
            {
                list     = web.Lists[listId];
                li       = list.GetItemById(itemId);
                settings = new GridGanttSettings(list);
                cNewGrps = new List <string>();
                bool isSecure = false;
                try
                {
                    isSecure = settings.BuildTeamSecurity;
                }
                catch { }

                orignalUser = web.AllUsers.GetByID(userid);

                string safeTitle = !string.IsNullOrEmpty(li.Title) ? GetSafeGroupTitle(li.Title) : string.Empty;

                if (string.IsNullOrEmpty(safeTitle) && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
                {
                    safeTitle = GetSafeGroupTitle(li.Name); //Assign Name instead of Title - This should perticularly happen with Document libraries.
                }
                if (isSecure)
                {
                    if (!li.HasUniqueRoleAssignments)
                    {
                        web.AllowUnsafeUpdates = true;
                        safeGroupTitle         = safeTitle;

                        safeTitle = GetIdenticalGroupName(site.ID, web.ID, safeTitle, 0);

                        // step 1 perform actions related to "parent item"
                        // ===============================================
                        Dictionary <string, SPRoleType> pNewGrps = null;
                        try
                        {
                            pNewGrps = AddBasicSecurityGroups(web, safeTitle, orignalUser, li);

                            li.BreakRoleInheritance(false);

                            foreach (KeyValuePair <string, SPRoleType> group in pNewGrps)
                            {
                                SPGroup g = web.SiteGroups[group.Key];
                                AddNewItemLvlPerm(li, web, group.Value, g);
                                g = null;
                            }

                            AddBuildTeamSecurityGroups(web, settings, li);
                        }
                        catch { }
                        finally
                        {
                            pNewGrps = null;
                        }
                    }
                }


                // step 2 perform actions related to "child item"
                // ====================================
                // find lookups that has security enabled
                string lookupSettings = settings.Lookups;
                //string rawValue = "Region^dropdown^none^none^xxx|State^autocomplete^Region^Region^xxx|City^autocomplete^State^State^xxx";
                valueHelper = new EnhancedLookupConfigValuesHelper(lookupSettings);

                if (valueHelper == null)
                {
                    return;
                }

                fields = valueHelper.GetSecuredFields();

                bool bHasLookup = false;

                foreach (string fld in fields)
                {
                    SPFieldLookup lookup = null;
                    try
                    {
                        lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                    }
                    catch { }

                    if (lookup == null)
                    {
                        continue;
                    }

                    lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                    prntListSettings = new GridGanttSettings(lookupPrntList);
                    string sVal = string.Empty;
                    try
                    {
                        sVal = li[fld].ToString();
                    }
                    catch { }
                    if (!string.IsNullOrEmpty(sVal))
                    {
                        bHasLookup = true;
                        break;
                    }
                }
                if (bHasLookup)
                {
                    // has security fields
                    if (fields.Count > 0)
                    {
                        // if the list is not a security list itself
                        if (isSecure)
                        {
                            li.BreakRoleInheritance(false);
                        }

                        foreach (string fld in fields)
                        {
                            SPFieldLookup lookup = null;
                            try
                            {
                                lookup = list.Fields.GetFieldByInternalName(fld) as SPFieldLookup;
                            }
                            catch { }

                            if (lookup == null)
                            {
                                continue;
                            }

                            lookupPrntList   = web.Lists[new Guid(lookup.LookupList)];
                            prntListSettings = new GridGanttSettings(lookupPrntList);
                            bool isEnableSecurity = false;
                            bool isParentSecure   = false;
                            try
                            {
                                isParentSecure = prntListSettings.BuildTeamSecurity;
                            }
                            catch { }

                            string[]  LookupArray = settings.Lookups.Split('|');
                            string[]  sLookupInfo = null;
                            Hashtable hshLookups  = new Hashtable();
                            foreach (string sLookup in LookupArray)
                            {
                                if (sLookup != "")
                                {
                                    sLookupInfo = sLookup.Split('^');
                                    hshLookups.Add(sLookupInfo[0], sLookupInfo);
                                }
                            }
                            try
                            {
                                if (sLookupInfo != null && sLookupInfo[4].ToLower() == "true")
                                {
                                    isEnableSecurity = true;
                                }
                                else
                                {
                                    isEnableSecurity = false;
                                }
                            }
                            catch { isEnableSecurity = false; }

                            // skip fields with empty lookup values
                            string sVal = string.Empty;
                            try { sVal = li[fld].ToString(); }
                            catch { }
                            if (string.IsNullOrEmpty(sVal))
                            {
                                continue;
                            }

                            lookupVal  = new SPFieldLookupValue(sVal.ToString());
                            targetItem = lookupPrntList.GetItemById(lookupVal.LookupId);
                            if (!targetItem.HasUniqueRoleAssignments)
                            {
                                continue;
                            }
                            else
                            {
                                //EPML-4422: When a project is not using unique security, and a child list like tasks is set to Inherit security from the project lookup, It sets the task to unique, but does not add any groups. It should not get set to Unique.
                                if (!isSecure && isParentSecure && isEnableSecurity)
                                {
                                    web.AllowUnsafeUpdates = true;
                                    li.BreakRoleInheritance(false);
                                }
                            }

                            SPRoleAssignmentCollection raCol = targetItem.RoleAssignments;
                            string itemMemberGrp             = "Member";
                            foreach (SPRoleAssignment ra in raCol)
                            {
                                // add their groups to this item but change permission lvl
                                if (ra.Member.Name.Contains(itemMemberGrp))
                                {
                                    SPRoleAssignment newRa  = new SPRoleAssignment(ra.Member);
                                    SPRoleDefinition newDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                                    newRa.RoleDefinitionBindings.Add(newDef);
                                    li.RoleAssignments.Add(newRa);
                                }
                                else
                                {
                                    li.RoleAssignments.Add(ra);
                                }

                                cNewGrps.Add(ra.Member.Name);
                            }
                        }
                    }
                }
                ProcessSecurity(site, list, li, userid);

                // we wait until all groups have been created to createworkspace
                // only if there isn't a current process creating ws
                WorkspaceTimerjobAgent.QueueWorkspaceJobOnHoldForSecurity(site.ID, web.ID, list.ID, li.ID);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                list             = null;
                li               = null;
                lookupPrntList   = null;
                prntListSettings = null;
                settings         = null;
                cNewGrps         = null;
                fields           = null;
                orignalUser      = null;
                valueHelper      = null;
                lookupVal        = null;
                targetItem       = null;
                fields           = null;
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
Beispiel #37
0
        /// <summary>
        /// Fixes the SP field type lookup.
        /// </summary>
        /// <param name="fileSpListItem">The file sp list item.</param>
        /// <param name="sourceValue">The source value.</param>
        /// <returns>Fixes the SPField type Lookup.</returns>
        private string FixSPFieldTypeLookup(SPListItem fileSpListItem, string sourceValue)
        {
            string s = "\t\tLookup(" + sourceValue + ")\tIsThisLookup? " + this.SPFieldTypeIsLookup + "\n";

            s += "\t\twas:" + fileSpListItem[this.ContextSPField.Id] + "\n";

            // process lookup columns (including multi-valued ones)
            List <string> lookupValueList = new List <string>();

            if (this.SPFieldTypeIsLookup)
            {
                s += "\t\tIsThisLookupupMulti? " + this.SPFieldLookupIsMultiValue + "\n";

                if (this.SPFieldLookupIsMultiValue)
                {
                    foreach (SPFieldLookupValue spFieldLookupValue in (fileSpListItem[this.FileSPField.Id] as SPFieldLookupValueCollection))
                    {
                        lookupValueList.Add(spFieldLookupValue.LookupValue);
                    }
                }
                else
                {
                    lookupValueList.Add(new SPFieldLookupValue(sourceValue).LookupValue);
                }
            }
            else
            {
                string[] strList = sourceValue.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strList)
                {
                    lookupValueList.Add(str);
                }
                s += "\t\tLookupElse ListCount:\t" + lookupValueList.Count + "\n";
            }

            // construct an SPFieldLookup object in the image of our field
            SPFieldLookup spFieldLookup = this.ContextSPField as SPFieldLookup;

            s += "\t\tspfield as spfield lookup multi? " + spFieldLookup.AllowMultipleValues + "\n";
            s += "\t\tlookupvaluelistcount:\t" + lookupValueList.Count + "\n";

            if (spFieldLookup.AllowMultipleValues)
            {
                SPFieldLookupValueCollection spFieldLookupValues = new SPFieldLookupValueCollection();

                foreach (string value in lookupValueList)
                {
                    // obtain the lookup value and its corresponding ID
                    SPFieldLookupValue lookupValue =
                        GetLookupValue(fileSpListItem.Web.Site.ID, spFieldLookup, value);

                    // lookup value found in the lookup list
                    if (lookupValue != null)
                    {
                        spFieldLookupValues.Add(lookupValue);
                    }
                }

                fileSpListItem[this.ContextSPField.Id] = spFieldLookupValues;
                s += "\t\tis_:" + spFieldLookupValues + "\n";
            }
            else if (lookupValueList.Count > 0)
            {
                // empty column values are "copied" as well
                if (String.IsNullOrEmpty(lookupValueList[0]))
                {
                    fileSpListItem[this.ContextSPField.Id] = String.Empty;
                    // continue;
                }

                // obtain the lookup value and its corresponding ID
                SPFieldLookupValue spFieldLookupValue =
                    GetLookupValue(fileSpListItem.Web.Site.ID, spFieldLookup, lookupValueList[0]);

                // lookup value found in the lookup list
                if (spFieldLookupValue != null)
                {
                    fileSpListItem[this.ContextSPField.Id] = spFieldLookupValue.ToString();
                }
                s += "\t\tis_:" + fileSpListItem[this.ContextSPField.Id] + "\n";
            }

            return(s);
        }
        private string GetValueFromControlLookup(Control control, SPFieldLookup fieldLookup)
        {
            string results = string.Empty;
            if (!fieldLookup.AllowMultipleValues)
            {
                DropDownList ddlValue = ((DropDownList)control);
                results = ddlValue.SelectedItem.Value + ";#" + ddlValue.SelectedItem.Text;
            }
            else
            {
                HtmlGenericControl div =((HtmlGenericControl)control);
                CheckBoxList listBox = (CheckBoxList)div.Controls[0];

                foreach (var item in listBox.Items.Cast<ListItem>().Where(p=>p.Selected))
                {
                    results += item.Value + ";#" + item.Text + SEPARATOR;
                }
            }
            return results.TrimEnd(SEPARATOR.ToCharArray());
        }