Ejemplo n.º 1
0
        private SPFieldUserValueCollection GetManagers(SPListItem item)
        {
            SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();

            if (item["Responsible"] != null)
            {
                SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item["Responsible"].ToString());
                fieldValues.Add(userValue);
            }

            SPFieldUser field = item.Fields["Person in charge"] as SPFieldUser;

            if (field != null && item["Person in charge"] != null)
            {
                SPFieldUserValueCollection picFieldValues = field.GetFieldValue(item["Person in charge"].ToString()) as SPFieldUserValueCollection;
                fieldValues.AddRange(picFieldValues);
            }

            if (item["Approver"] != null)
            {
                SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item["Approver"].ToString());
                fieldValues.Add(userValue);
            }

            string secondApprover = GetSecondApprover(item);

            if (secondApprover != string.Empty && item[secondApprover] != null)
            {
                SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[secondApprover].ToString());
                fieldValues.Add(userValue);
            }

            return(fieldValues);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Get multiple people information from people editor control
        /// </summary>
        /// <remarks>
        ///     References: http://blog.bugrapostaci.com/tag/spfielduservalue/
        /// </remarks>
        /// <param name="editor"></param>
        /// <returns></returns>
        public SPFieldUserValueCollection GetSelectedUsers(PeopleEditor editor, SPWeb currentWeb)
        {
            string selectedUsers = editor.CommaSeparatedAccounts;
            SPFieldUserValueCollection values = new SPFieldUserValueCollection();

            try
            {
                // commaseparatedaccounts returns entries that are comma separated. we want to split those up
                char[]   splitter    = { ',' };
                string[] splitPPData = selectedUsers.Split(splitter);
                // this collection will store the user values from the people editor which we'll eventually use
                // to populate the field in the list

                // for each item in our array, create a new sp user object given the loginname and add to our collection
                for (int i = 0; i < splitPPData.Length; i++)
                {
                    string loginName = splitPPData[i];
                    if (!string.IsNullOrEmpty(loginName))
                    {
                        SPUser           user = currentWeb.SiteUsers[loginName];
                        SPFieldUserValue fuv  = new SPFieldUserValue(currentWeb, user.ID, user.LoginName);
                        values.Add(fuv);
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at GetSelectedUsers function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }
            return(values);
        }
Ejemplo n.º 3
0
        public SPFieldUserValueCollection ConvertMultUser(IList <User> Users, SPWeb web)
        {
            SPFieldUserValueCollection userCollection = null;

            if (Users != null && Users.Count > 0)
            {
                userCollection = new SPFieldUserValueCollection();
                foreach (var user in Users)
                {
                    SPUser userToAdd;
                    if (user.ID > 0)
                    {
                        userToAdd = web.AllUsers.GetByID(user.ID);
                    }
                    else
                    {
                        userToAdd = web.EnsureUser(user.UserName);
                    }
                    if (userToAdd != null)
                    {
                        SPFieldUserValue SPFieldUserValue = new SPFieldUserValue(web, userToAdd.ID, userToAdd.LoginName);
                        userCollection.Add(SPFieldUserValue);
                    }
                }
            }
            return(userCollection);
        }
Ejemplo n.º 4
0
        public static SPFieldUserValueCollection GetKeyPeopleForAgenda(string agendaType, string agmOffice, SPItemEventProperties eventProperties)
        {
            string masterKeyPeopleListName = null;
            //SPFolder defaultDocuments =rootWeb.RootWeb.Folders["Default Documents"];
            SPWebApplication webApplication = eventProperties.Web.Site.WebApplication;
            if (webApplication.Properties != null && webApplication.Properties.Count > 0)
            {
                masterKeyPeopleListName = webApplication.Properties["MasterKeyPeopleListName"].ToString();
            }

            SPList list = eventProperties.Web.Lists[masterKeyPeopleListName];

            SPFieldUserValueCollection authUsers = new SPFieldUserValueCollection();

            if (list != null)
            {
                foreach (SPListItem item in list.Items)
                {
                    if ((item["Agenda Type"].ToString() == agendaType) && (item["AGM Office"].ToString() == agmOffice) && (item["Position"].ToString() == "Agenda Coordinator"))
                    {
                        string authUsersFieldValue = item["KeyPerson"].ToString();

                        authUsers.Add(new SPFieldUserValue(item.Web, authUsersFieldValue));
                        //break;
                    }
                }
                return authUsers;
            }
            else
                return null;
        }
Ejemplo n.º 5
0
        private ShimSPFieldUserValueCollection InitializeSPFieldUserValuesShim()
        {
            var result = new SPFieldUserValueCollection();

            result.Add(FieldUserValueShim);
            return(new ShimSPFieldUserValueCollection(result));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Recebe a lista de destinatários com usuários e grupos e retorna uma lista com os usuários envolvidos (cada usuário
        /// de cada grupo), sem repetição e sem os grupos.
        /// </summary>
        /// <param name="listaDestinatarios"></param>
        /// <returns>Usuários sem os grupos</returns>
        private List <SPUser> capturarTodosUsuarios(SPFieldUserValueCollection listaDestinatarios, SPItemEventProperties properties)
        {
            List <SPUser> listaRetorno         = new List <SPUser>();
            List <int>    usuariosListaRetorno = new List <int>();

            using (SPWeb web = properties.Web.Site.RootWeb)
            {
                List <SPUser> usuariosDeGrupos = new List <SPUser>();

                SPFieldUserValueCollection collectionGrupos = new SPFieldUserValueCollection();

                foreach (SPFieldUserValue usuarioOuGrupo in listaDestinatarios)
                {
                    //jogo grupos em outra lista
                    if (usuarioOuGrupo.User == null)             //Ver se vou precisar colocar a linha if(SPUtility.IsLoginValid(site, usersField.User.LoginName))
                    {
                        collectionGrupos.Add(usuarioOuGrupo);
                    }
                    else  //Adiciona o usuário caso já não esteja na lista
                    {
                        if (!usuariosListaRetorno.Contains(usuarioOuGrupo.User.ID))
                        {
                            usuariosListaRetorno.Add(usuarioOuGrupo.User.ID);
                            listaRetorno.Add(usuarioOuGrupo.User);
                        }
                    }
                }

                //Se tem grupos, devo separar cada usuário
                if (collectionGrupos.Count > 0)
                {
                    foreach (SPFieldUserValue grupo in collectionGrupos)
                    {
                        SPGroup group = web.Groups.GetByID(grupo.LookupId);

                        foreach (SPUser user in group.Users)
                        {
                            if (!usuariosDeGrupos.Contains(user))
                            {
                                // add all the group users to the list
                                usuariosDeGrupos.Add(user);
                            }
                        }
                    }
                }

                foreach (SPUser user in usuariosDeGrupos)
                {
                    if (!usuariosListaRetorno.Contains(user.ID))
                    {
                        // add all the group users to the list
                        usuariosListaRetorno.Add(user.ID);
                        listaRetorno.Add(user);
                    }
                }
            }

            return(listaRetorno);
        }
Ejemplo n.º 7
0
        internal static SPFieldUserValueCollection GetUsers(SPList list, string fieldStaticName, object value)
        {
            if (value == null)
            {
                return(null);
            }

            var userField = (SPFieldUser)list.Fields.TryGetFieldByStaticName(fieldStaticName);

            if (userField == null)
            {
                throw new SharepointCommonException(string.Format("Field {0} not exist", fieldStaticName));
            }

            IEnumerable <int> ids;

            if (value is SPFieldUserValueCollection)
            {
                var vv = value as SPFieldUserValueCollection;
                ids = vv.Select(v => v.LookupId);
            }
            else
            {
                var mlv = new SPFieldLookupValueCollection((string)value);

                ids = mlv.Select(v => v.LookupId);
            }

            var users = new SPFieldUserValueCollection();

            foreach (var id in ids)
            {
                try
                {
                    var user = list.ParentWeb.AllUsers.GetByID(id);
                    users.Add(new SPFieldUserValue(list.ParentWeb, user.ID, user.LoginName));
                }
                catch (SPException)
                {
                    var group = list.ParentWeb.SiteGroups.GetByID(id);
                    users.Add(new SPFieldUserValue(list.ParentWeb, group.ID, group.Name));
                }
            }
            return(users);
        }
Ejemplo n.º 8
0
        /// <summary>Fixes the SP field type user.</summary>
        /// <param name="contextSPWeb">The context sp web.</param>
        /// <param name="fileSPListItem">The file sp list item.</param>
        /// <param name="sourceValue">The source value.</param>
        /// <returns>The fix sp field type user.</returns>
        private string FixSPFieldTypeUser(SPWeb contextSPWeb, SPListItem fileSPListItem, string sourceValue)
        {
            string s = "\t\tUser(" + contextSPWeb.Url + "," + sourceValue + "\n";

            s += "\t\twas:" + fileSPListItem[this.FileSPField.Id] + "\n";

            // transform non-user values into user type
            string[] userNames = sourceValue.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            s += "\t\tuserNamescount:\t" + userNames.Length + "\n";

            // create list of user names parsing array of names
            SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection();

            // update SPPrincipal using user info
            foreach (string userName in userNames)
            {
                string user = userName.Trim();
                s += "\t\tuser:\t" + user + "\n";
                SPPrincipal spPrincipal = null;

                // checking if this string is the name of a SharePoint group, add to user collection if (spPrincipal != null)
                if (this.IsUserSPGroupName(contextSPWeb, user))
                {
                    spPrincipal = this.GetUserSPPrincipal(contextSPWeb, user);
                    spFieldUserValues.Add(new SPFieldUserValue(contextSPWeb, spPrincipal.ID, spPrincipal.Name));
                }

                // the value is not a group; try to set it as a user then.
                // if (spPrincipal == null)
                else
                {
                    try
                    {
                        spPrincipal = contextSPWeb.EnsureUser(user);
                    }
                    catch
                    {
                    }
                }
                s += "\t\tspPrncipal:\t" + spPrincipal.Name + "\n";
            }

            // set multi-user fields to new user collection
            if (this.SPFieldUserIsMultiValue)
            {
                fileSPListItem[this.FileSPField.Id] = spFieldUserValues;
            }

            // set single-user fields to just one user value
            else
            {
                fileSPListItem[this.FileSPField.Id] = spFieldUserValues[0];
            }

            s += "\t\tis_:" + fileSPListItem[this.FileSPField.Id] + "\n";
            return(s);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// copies list properties excluding readonly fields and fields that are not present in destination list
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        private static void CopyFieldValues(SPListItem source, SPListItem destination, bool linkToOriginal)
        {
            foreach (SPField sourceField in source.Fields)                   // loop thru source item fields
            {
                if (FieldShouldBeCopied(sourceField))                        //can we copy this field?
                {
                    if (destination.Fields.ContainsField(sourceField.Title)) // does a field with same title exists in dest list
                    {
                        SPField destField = destination.Fields[sourceField.Title];

                        if (FieldShouldBeCopied(destField) && FieldShouldBeCopiedTo(sourceField, destField)) // do the field types match?
                        {
                            //user lookup ids are not valid when copying items cross site, so we need to create new lookup ids in destination site by calling SPWeb.EnsureUser()
                            if (sourceField.Type == SPFieldType.User && source[sourceField.Title] != null && source.ParentList.ParentWeb.ID != destination.ParentList.ParentWeb.ID)
                            {
                                try
                                {
                                    SPFieldUser fieldUser = sourceField as SPFieldUser;

                                    if (fieldUser.AllowMultipleValues == false)
                                    {
                                        SPFieldUserValue userValue = new SPFieldUserValue(source.ParentList.ParentWeb, source[sourceField.Title].ToString());

                                        destination[sourceField.Title] = destination.ParentList.ParentWeb.EnsureUser(userValue.User.LoginName);
                                    }
                                    else
                                    {
                                        SPFieldUserValueCollection useValCol  = new SPFieldUserValueCollection(source.ParentList.ParentWeb, source[sourceField.Title].ToString());
                                        SPFieldUserValueCollection destValCol = new SPFieldUserValueCollection();

                                        foreach (SPFieldUserValue usr in useValCol)
                                        {
                                            using (SPWeb parentWeb = destination.ParentList.ParentWeb)
                                            {
                                                SPUser destUser = parentWeb.EnsureUser(usr.User.LoginName);
                                                destValCol.Add(new SPFieldUserValue(parentWeb, destUser.ID, string.Empty));
                                            }
                                        }
                                        destination[sourceField.Title] = destValCol;
                                    }
                                }
                                catch { }
                            }
                            else
                            {
                                destination[sourceField.Title] = source[sourceField.Title];
                            }
                        }
                    }
                }
            }
            if (linkToOriginal)
            {
                destination[ColumnHelper.PublishedFromInternalColumnName] = ListHelper.GetDisplayUrl(source);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="likeCount">1/-1点赞和取消赞</param>
        private void SaveLikeUnLike(int itemID, int likeCount)
        {
            SPUser loginUser = SPContext.Current.Web.CurrentUser;
            Guid   webID     = SPContext.Current.Web.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb thisWeb = mySite.AllWebs[webID])
                    {
                        thisWeb.AllowUnsafeUpdates = true;
                        try
                        {
                            string listUrl     = Page.Request.FilePath;;
                            SPList list        = thisWeb.GetList(listUrl);
                            SPListItem lstItem = list.GetItemById(itemID);
                            SPFieldUserValueCollection users = lstItem["LikedBy"] as SPFieldUserValueCollection;
                            SPFieldUserValue userValue       = new SPFieldUserValue(thisWeb, loginUser.ID, loginUser.Name);
                            if (users != null)
                            {
                                lstItem["LikesCount"] = (double)lstItem["LikesCount"] + likeCount;
                                if (likeCount > 0)//点赞
                                {
                                    users.Add(userValue);
                                    lstItem["LikedBy"] = users;
                                }
                                else //取消赞
                                {
                                    for (int i = 0; i < users.Count; i++)
                                    {
                                        if (users[i].LookupId == loginUser.ID)
                                        {
                                            users.RemoveAt(i);
                                            break;
                                        }
                                    }
                                    lstItem["LikedBy"] = users;
                                }
                            }
                            else
                            {
                                lstItem["LikedBy"]    = loginUser;
                                lstItem["LikesCount"] = likeCount;
                            }
                            lstItem.Update();
                        }
                        catch (Exception ex)
                        {
                            this.Controls.Add(new LiteralControl(ex.ToString()));
                        }
                        thisWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
Ejemplo n.º 11
0
        private void OnMultiUserValueChanged(object sender, string fieldName)
        {
            SPFieldUserValueCollection collection = new SPFieldUserValueCollection();

            foreach (SPPrincipal user in (IEnumerable)sender)
            {
                collection.Add(new SPFieldUserValue(user.ParentWeb, user.ID, user.Name));
            }
            this[fieldName] = collection.ToString();
        }
Ejemplo n.º 12
0
        private void MatchSPFieldTypeUser(SPWeb contextSPWeb, SPListItem targetSPListItem, SPField targetSPField,
                                          string sourceValue)
        {
            // transform non-user values into user type
            string[] nameArr = sourceValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            // create list of user names
            SPFieldUserValueCollection spFieldUserValueCollection = new SPFieldUserValueCollection();

            foreach (string name in nameArr)
            {
                SPPrincipal spPrincipal = null;

                // checking if this string is the name of a SharePoint group
                foreach (SPGroup spGroup in contextSPWeb.SiteGroups)
                {
                    if (spGroup.Name == name.Trim())
                    {
                        spPrincipal = spGroup;
                        break;
                    }
                }

                // the value is not a group; try to set it as a user then.
                if (spPrincipal == null)
                {
                    try
                    {
                        spPrincipal = contextSPWeb.EnsureUser(name.Trim());
                    }
                    catch
                    {
                    }
                }

                // add to user collection
                if (spPrincipal != null)
                {
                    spFieldUserValueCollection.Add(
                        new SPFieldUserValue(contextSPWeb, spPrincipal.ID, spPrincipal.Name));
                }
            }

            // set multi-user fields to new user collection
            if ((targetSPField as SPFieldUser).AllowMultipleValues)
            {
                targetSPListItem[targetSPField.Id] = spFieldUserValueCollection;
            }

            // set single-user fields to just one user value
            else
            {
                targetSPListItem[targetSPField.Id] = spFieldUserValueCollection[0];
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Fixes the SP field type same user.
        /// </summary>
        /// <param name="contextSPWeb">The context sp web.</param>
        /// <param name="fileSPListItem">The file SP list item.</param>
        /// <param name="sourceValue">The source value.</param>
        /// <returns>
        /// The fix to sp field having the same username.
        /// </returns>
        private string FixSPFieldTypeSameUser(SPWeb contextSPWeb, SPListItem fileSPListItem, string sourceValue)
        {
            string s = "\t\tSameUser(" + contextSPWeb.Url + "," + sourceValue + ")\n";

            s += "\t\twas:" + fileSPListItem[this.FileSPField.Id] + "\n";

            // process "Person or Group" fields (including multi-valued ones)
            SPFieldUserValueCollection sourceUserValues = new SPFieldUserValueCollection(contextSPWeb, sourceValue);
            SPFieldUserValueCollection targetUserValues = new SPFieldUserValueCollection();

            s += "\t\tsourceUserValues:" + sourceUserValues.Count + "\n";

            foreach (SPFieldUserValue spFieldUserValue in sourceUserValues)
            {
                string      logon       = spFieldUserValue.LookupValue;
                SPPrincipal spPrincipal = null;

                // checking if this string is the name of a SharePoint group
                spPrincipal = this.GetUserSPPrincipal(contextSPWeb, logon);

                if (spPrincipal == null)
                {
                    // the value is not a group; try to set it as a user then.
                    try
                    {
                        spPrincipal = contextSPWeb.EnsureUser(logon);
                    }
                    catch
                    {
                    }
                }

                // add to user collection
                if (spPrincipal != null)
                {
                    targetUserValues.Add(new SPFieldUserValue(contextSPWeb, spPrincipal.ID, spPrincipal.Name));
                }
            }

            // set multi-user fields to new user collection
            if (this.SPFieldUserIsMultiValue)
            {
                fileSPListItem[this.FileSPField.Id] = targetUserValues;
            }

            // set single-user fields to just one user value
            else
            {
                fileSPListItem[this.FileSPField.Id] = targetUserValues[0];
            }

            s += "\t\tis_:" + fileSPListItem[this.FileSPField.Id] + "\n";
            return(s);
        }
Ejemplo n.º 14
0
        private static SPFieldUserValueCollection CreateSharePointUserValueCollection(SPWeb web, UserValueCollection userValueCollection)
        {
            SPFieldUserValueCollection resultCollection = new SPFieldUserValueCollection();

            foreach (UserValue defaultVal in userValueCollection)
            {
                resultCollection.Add(new SPFieldUserValue(web, defaultVal.Id, HttpUtility.HtmlEncode(defaultVal.DisplayName)));
            }

            return(resultCollection);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///   Get multiple people information from people editor control
        /// </summary>
        /// <remarks>
        ///     References: http://kancharla-sharepoint.blogspot.com.au/2012/10/sometimes-we-need-to-get-all-people-or.html
        /// </remarks>
        /// <param name="people"></param>
        /// <param name="web"></param>
        /// <returns></returns>
        public SPFieldUserValueCollection GetPeopleFromPickerControl(PeopleEditor people, SPWeb web)
        {
            SPFieldUserValueCollection values = new SPFieldUserValueCollection();

            try
            {
                if (people.ResolvedEntities.Count > 0)
                {
                    for (int i = 0; i < people.ResolvedEntities.Count; i++)
                    {
                        PickerEntity user = (PickerEntity)people.ResolvedEntities[i];

                        switch ((string)user.EntityData["PrincipalType"])
                        {
                        case "User":
                            SPUser           webUser   = web.EnsureUser(user.Key);
                            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
                            values.Add(userValue);
                            break;

                        case "SharePointGroup":
                            SPGroup          siteGroup  = web.SiteGroups[user.EntityData["AccountName"].ToString()];
                            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
                            values.Add(groupValue);
                            break;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, web);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at GetPeopleFromPickerControl function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }

            return(values);
        }
Ejemplo n.º 16
0
        private void UpdateUserInfo(SPListItem item)
        {
            SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();
            //SPUser user = SPContext.Current.Web.EnsureUser("LogonName");
            SPUser user = SPContext.Current.Web.CurrentUser;

            if (user != null)
            {
                fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name));
                item[SPBuiltInFieldId.Author] = fieldValues;
                item[SPBuiltInFieldId.Editor] = fieldValues;
            }
        }
Ejemplo n.º 17
0
        public static SPFieldUserValueCollection PickUserValue(PeopleEditor peopleEditor)
        {
            SPFieldUserValueCollection fieldUserValues = new SPFieldUserValueCollection();
            foreach (PickerEntity entity in peopleEditor.ResolvedEntities)
            {
                SPPrincipal principal = MOSSPrincipal.FindUserOrSiteGroup(entity.Key);
                SPFieldUserValue userValue = new SPFieldUserValue(MOSSContext.Current.Web, principal.ID,principal.Name);

                fieldUserValues.Add(userValue);
            }

            return fieldUserValues;
        }
Ejemplo n.º 18
0
        private SPFieldUserValueCollection GetUserValues(SPWeb web)
        {
            SPFieldUserValueCollection values = new SPFieldUserValueCollection();

            foreach (PickerEntity entity in spPeoplePicker.ResolvedEntities)
            {
                SPUser           user = web.EnsureUser(entity.Key);
                SPFieldUserValue fuv  = new SPFieldUserValue(web, user.ID, user.LoginName);
                values.Add(fuv);
            }

            return(values);
        }
Ejemplo n.º 19
0
        public static void HandleMultiUserCase(SPWeb web, string value, SPListItem listItem, SPField field)
        {
            var users = value.Split('\n');
            var userValueCollection = new SPFieldUserValueCollection();

            for (var i = 0; i < users.Length; i = i + 2)
            {
                var iGroup   = 0;
                var userName = users[i];
                if (int.TryParse(userName, out iGroup))
                {
                    var userValue = new SPFieldUserValue(web, $"{userName};#{users[i + 1]}");
                    userValueCollection.Add(userValue);
                }
                else
                {
                    var user      = web.AllUsers[userName];
                    var userValue = new SPFieldUserValue(web, $"{user.ID};#{user.Name}");
                    userValueCollection.Add(userValue);
                }
            }
            listItem[field.Id] = userValueCollection;
        }
Ejemplo n.º 20
0
        private static SPFieldUserValueCollection FormatUserCollection(IEnumerable <User> usersList,
                                                                       SPListItem item,
                                                                       string siteUrl = null)
        {
            var userValueCollection = new SPFieldUserValueCollection();

            foreach (User user in usersList)
            {
                if (user.IsGroup)
                {
                    SPGroup group = item.Web.Groups.GetByID(user.ID);
                    if (group != null)
                    {
                        userValueCollection.Add(new SPFieldUserValue(item.Web, group.ID, group.LoginName));
                    }
                }
                else
                {
                    SPUser spuser = string.IsNullOrEmpty(siteUrl)
                        ? SPHelper.EnsureUser(SPHelper.GetAccountName(user.UserName))
                        : SPHelper.EnsureUser(SPHelper.GetAccountName(user.UserName), siteUrl);
                    if (spuser != null)
                    {
                        userValueCollection.Add(new SPFieldUserValue(item.Web, spuser.ID, user.UserName));
                    }
                    else
                    {
                        throw new ArgumentException(
                                  string.Format("User {0} not found in the {1} webapplication", user.UserName, item.Web.Title),
                                  "usersList");
                    }
                }
            }

            return(userValueCollection);
        }
Ejemplo n.º 21
0
        public static SPFieldUserValueCollection UserValueCollection(SPWeb web, string users)
        {
            SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();

            string[] userarray = users.Split(';');
            string   email = string.Empty; string name = string.Empty;
            string   cpnameori = string.Empty;

            for (int j = 0; j < userarray.Length - 1; j++)
            {
                SPFieldUserValue usertoadd = ConvertLoginName(userarray[j], web);
                usercollection.Add(usertoadd);
            }

            return(usercollection);
        }
Ejemplo n.º 22
0
        public static void SetFieldValueUser(this SPListItem item,
                                             string fieldName, IEnumerable <SPPrincipal> principals)
        {
            if (item != null)
            {
                SPFieldUserValueCollection fieldValues =
                    new SPFieldUserValueCollection();

                foreach (SPPrincipal principal in principals)
                {
                    fieldValues.Add(
                        new SPFieldUserValue(
                            item.Web, principal.ID, principal.Name));
                }
                item[fieldName] = fieldValues;
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Sets the value of a multivalue User-Field to
        /// a list of user names.
        /// </summary>
        public static void SetFieldValueUser(this SPListItem item,
                                             string fieldName, IEnumerable <string> loginNames)
        {
            if (item != null)
            {
                SPFieldUserValueCollection fieldValues =
                    new SPFieldUserValueCollection();

                foreach (string loginName in loginNames)
                {
                    SPUser user = item.Web.EnsureUser(loginName);
                    fieldValues.Add(
                        new SPFieldUserValue(
                            item.Web, user.ID, user.Name));
                }

                item[fieldName] = fieldValues;
            }
        }
Ejemplo n.º 24
0
        private SPFieldUserValueCollection GetAuthorsFromString(string txtAuthors, SPWeb myWeb)
        {
            txtAuthors = txtAuthors.TrimEnd(';');
            string[] authors = Regex.Split(txtAuthors, ";");
            SPFieldUserValueCollection author1 = new SPFieldUserValueCollection();//创建者为第一作者

            for (int i = 0; i < authors.Length; i++)
            {
                DirectoryEntry adUser = GetDirectoryEntryByName(authors[i].Trim());
                if (adUser != null)
                {
                    string           account = adUser.Properties["sAMAccountName"].Value.ToString();
                    SPUser           user    = myWeb.EnsureUser("ccc\\" + account);
                    SPFieldUserValue fUser   = new SPFieldUserValue(myWeb, user.ID, user.LoginName);
                    author1.Add(fUser);
                }
            }
            return(author1);
        }
        internal static SPFieldUserValueCollection UserValueCollection(this PeopleEditor editor)
        {
            var res = new SPFieldUserValueCollection();
            var ctx = SPContext.Current;

            SPSecurity.RunWithElevatedPrivileges(
                () =>
            {
                using (var site = new SPSite(ctx.Site.ID))
                {
                    using (var web = site.OpenWeb(ctx.Web.ID))
                    {
                        editor.Validate();
                        if (editor.ResolvedEntities.Count > 0)
                        {
                            foreach (PickerEntity entity in editor.ResolvedEntities)
                            {
                                var id = 0;
                                switch (entity.EntityData["PrincipalType"].ToString())
                                {
                                case "User":
                                    id = Convert.ToInt32(entity.EntityData["SPUserID"]);
                                    if (id <= 0)
                                    {
                                        var u = web.EnsureUser(entity.Key);
                                        id    = u.ID;
                                    }
                                    break;

                                case "SharePointGroup":
                                    id = Convert.ToInt32(entity.EntityData["SPGroupID"]);
                                    break;
                                }
                                res.Add(new SPFieldUserValue(web, id, entity.Key));
                            }
                        }
                    }
                }
            });
            return(res);
        }
Ejemplo n.º 26
0
        public static SPFieldUserValueCollection GetApproversValue()
        {
            SPListItem item = SPContext.Current.ListItem;

            SPFieldUserValueCollection col = item["Approvers"] as SPFieldUserValueCollection;

            if (col != null)
            {
                SPUser user = SPContext.Current.Web.CurrentUser;
                SPFieldUserValue value = new SPFieldUserValue(SPContext.Current.Site.RootWeb, user.ID, user.Name);

                bool IsExist = false;
                foreach (SPFieldUserValue v in col)
                {
                    if (v.LookupId == value.LookupId)
                    {
                        IsExist = true;
                        break;
                    }
                }
                if (!IsExist)
                {
                    col.Add(value);
                }
            }
            else
            {
                SPUser user = SPContext.Current.Web.CurrentUser;
                SPFieldUserValue value = new SPFieldUserValue(SPContext.Current.Site.RootWeb, user.ID, user.Name);
                col = new SPFieldUserValueCollection();
                col.Add(value);
            }

            return col;
        }
Ejemplo n.º 27
0
        public static void UpdateFieldValue(this SPListItem item, SPField updatedField, string data)
        {
            if (string.IsNullOrEmpty(data) || data.CompareTo(";#") == 0)
            {
                return;
            }

            switch (updatedField.Type)
            {
            case SPFieldType.Boolean:
                item[updatedField.Id] = Convert.ToBoolean(data);
                break;

            case SPFieldType.File:
            case SPFieldType.Calculated:
            case SPFieldType.Computed:
            case SPFieldType.Currency:
            case SPFieldType.Integer:
            case SPFieldType.Note:
            case SPFieldType.Number:
            case SPFieldType.Text:
                item[updatedField.Id] = data;
                break;

            case SPFieldType.Choice:
                SPFieldChoice fieldChoice = (SPFieldChoice)updatedField;
                item[updatedField.Id] = data;
                break;

            case SPFieldType.DateTime:
                SPFieldDateTime fieldDate = (SPFieldDateTime)updatedField;
                item[updatedField.Id] = Convert.ToDateTime(data);
                break;

            case SPFieldType.Lookup:

                SPFieldLookup fieldLookup = (SPFieldLookup)updatedField;
                if (fieldLookup.AllowMultipleValues)
                {
                    SPFieldLookupValueCollection multiValues = new SPFieldLookupValueCollection();
                    foreach (var s in data.Split("|".ToCharArray()))
                    {
                        multiValues.Add(new SPFieldLookupValue(s));
                    }
                    item[updatedField.Id] = multiValues;
                }
                else
                {
                    //int id = fieldLookup.GetLookupIdFromValue(data);

                    SPFieldLookupValue singleLookupValue = new SPFieldLookupValue(data);
                    item[updatedField.Id] = singleLookupValue;
                }
                break;

            case SPFieldType.MultiChoice:
                SPFieldMultiChoice fieldMultichoice = (SPFieldMultiChoice)updatedField;

                string[] items = data.Split("|".ToCharArray());
                SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue();
                foreach (string choice in items)
                {
                    values.Add(choice);
                }

                item[updatedField.Id] = values;

                break;

            case SPFieldType.User:
                SPFieldUser fieldUser = (SPFieldUser)updatedField;

                SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();
                string[] entities = data.Split("|".ToCharArray());

                foreach (string entity in entities)
                {
                    SPUser user = item.Web.EnsureUser(entity.Split(";#".ToCharArray())[2]);
                    if (user != null)
                    {
                        fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name));
                    }
                }

                item[updatedField.Id] = fieldValues;
                break;
            }
        }
Ejemplo n.º 28
0
        protected void AGMOffice_SelectedIndexChanged(object sender, EventArgs e)
        {
            SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

            string keyPeopleListName = webApplication.Properties["MasterKeyPeopleListName"].ToString();

            SPList list = SPContext.Current.Web.Lists[keyPeopleListName];

            ShowAuthPanel(false);

            SPQuery query = new SPQuery()
            {
                Query = string.Format(@"<Query>
                                          <Where>
                                            <And>
                                              <Eq>
                                                <FieldRef Name='Agenda Type' />
                                                <Value Type='Choice'>{0}</Value>
                                              </Eq>
                                              <And>
                                                <Eq>
                                                  <FieldRef Name='AGM Office' />
                                                  <Value Type='Choice'>{1}</Value>
                                                </Eq>
                                                <Eq>
                                                  <FieldRef Name='PositionInMarta' />
                                                  <Value Type='Text'>Agenda Coordinator</Value>
                                                </Eq>
                                              </And>
                                            </And>
                                          </Where>
                                        </Query>", ddlAgendaType.SelectedValue, ddlAGMOffice.SelectedValue)
            };

            if (list != null)
            {
                SPFieldUserValueCollection authUsers = new SPFieldUserValueCollection();

                foreach (SPListItem item in list.GetItems(query))
                {
                    //For some reason the Query seems to be returning all data and not what its filtered by, so explicity check here.
                    if ((item["PositionInMarta"].ToString() == "Agenda Coordinator") && (item["AGM Office"].ToString() == ddlAGMOffice.SelectedValue) && (item["Agenda Type"].ToString() == ddlAgendaType.SelectedValue))
                    {
                        string authUsersFieldValue = item["KeyPerson"].ToString();

                        authUsers.Add(new SPFieldUserValue(item.Web, authUsersFieldValue));
                    }
                }

                SPUser currentUser = list.ParentWeb.CurrentUser;
                SPFieldUserValue currentUserValue = new SPFieldUserValue(list.ParentWeb, currentUser.ID, currentUser.Name);

                if (authUsers.Where(u => u.User.LoginName == currentUser.LoginName).SingleOrDefault() != null)
                {
                    ShowAuthPanel(true);
                }
                else
                    ShowAuthPanel(false);

            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// copies list properties excluding readonly fields and fields that are not present in destination list
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        private static void CopyFieldValues(SPListItem source, SPListItem destination)
        {
            foreach (SPField sourceField in source.Fields) // loop thru source item fields
            {
                if (FieldShouldBeCopied(sourceField)) //can we copy this field?
                {
                    if (destination.Fields.ContainsField(sourceField.Title)) // does a field with same title exists in dest list
                    {
                        SPField destField = destination.Fields[sourceField.Title];

                        if (FieldShouldBeCopied(destField) && FieldShouldBeCopiedTo(sourceField, destField)) // do the field types match?
                        {

                            //user lookup ids are not valid when copying items cross site, so we need to create new lookup ids in destination site by calling SPWeb.EnsureUser()
                            if (sourceField.Type == SPFieldType.User && source[sourceField.Title] != null && source.ParentList.ParentWeb.ID != destination.ParentList.ParentWeb.ID)
                            {
                                try
                                {
                                    SPFieldUser fieldUser = sourceField as SPFieldUser;

                                    if (fieldUser.AllowMultipleValues == false)
                                    {
                                        SPFieldUserValue userValue = new SPFieldUserValue(source.ParentList.ParentWeb, source[sourceField.Title].ToString());

                                        destination[sourceField.Title] = destination.ParentList.ParentWeb.EnsureUser(userValue.User.LoginName);
                                    }
                                    else
                                    {
                                        SPFieldUserValueCollection useValCol = new SPFieldUserValueCollection(source.ParentList.ParentWeb, source[sourceField.Title].ToString());

                                        SPFieldUserValueCollection destValCol = new SPFieldUserValueCollection();

                                        foreach (SPFieldUserValue usr in useValCol)
                                        {
                                            SPUser destUser = destination.ParentList.ParentWeb.EnsureUser(usr.User.LoginName);

                                            destValCol.Add(new SPFieldUserValue(destination.ParentList.ParentWeb, destUser.ID, string.Empty));

                                        }

                                        destination[sourceField.Title] = destValCol;

                                    }
                                }
                                catch { }

                            }
                            else
                                destination[sourceField.Title] = source[sourceField.Title];

                        }

                    }

                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Guarda el registro de nueva correspondencia en lista FundaPro
        /// </summary>
        /// <param name="tipoCarta"></param>
        /// <param name="origenCarta"></param>
        /// <param name="referencia"></param>
        /// <param name="fechaCarta"></param>
        /// <param name="fechaRecibida"></param>
        /// <param name="destinatario"></param>
        /// <param name="dirigidaA"></param>
        /// <param name="numCarta"></param>
        /// <param name="privada"></param>
        /// <param name="hojaRuta"></param>
        /// <param name="archivo"></param>
        public static int GuardarNuevoRegistro(string tipoCarta, int origenCarta,
                                               string referencia, DateTime fechaCarta, DateTime fechaRecibida, string destinatario,
                                               ArrayList dirigidaA, string numCarta, string adjunto, string clase, string prioridad,
                                               bool privada, bool hojaRuta, string archivo, List <string> rutas, string urlLista)
        {
            UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

            #region Consulta lista SP
            try
            {
                sitio = new SPSite(UrlFPC);
                web   = sitio.OpenWeb();

                #region Conversion de usuarios para insercion
                SPFieldUserValueCollection usuariosDirigidos = new SPFieldUserValueCollection();
                foreach (string usuario in dirigidaA)
                {
                    SPFieldUserValue spv = null;

                    do
                    {
                        try
                        { spv = new SPFieldUserValue(web, web.SiteUsers[usuario].ID, usuario); }
                        catch
                        { web.SiteUsers.Add(usuario, "", "", ""); }
                    } while (spv == null);

                    usuariosDirigidos.Add(spv);
                }
                #endregion

                //SPListItem nuevoItem = web.Lists[urlLista].Items.Add();
                SPListItem nuevoItem = web.GetList(urlLista).Items.Add();
                nuevoItem["Tipo corr."]         = tipoCarta;
                nuevoItem["Origen"]             = origenCarta;
                nuevoItem["Referencia"]         = referencia;
                nuevoItem["Fecha origen"]       = fechaCarta;
                nuevoItem["Fecha recibida"]     = fechaRecibida;
                nuevoItem["Destinatario"]       = destinatario;
                nuevoItem["Dirigida a"]         = usuariosDirigidos;
                nuevoItem["Num. ó Cite"]        = numCarta;
                nuevoItem["Adjunto"]            = adjunto;
                nuevoItem["Clase de documento"] = clase;
                nuevoItem["Prioridad corr."]    = prioridad;
                nuevoItem["Privada"]            = privada;
                nuevoItem["Hoja de ruta"]       = hojaRuta;
                nuevoItem["Archivo"]            = archivo;
                if (!string.IsNullOrEmpty(archivo))
                {
                    nuevoItem["Estado corr."] = "PASIVA";
                }
                //if (!string.IsNullOrEmpty(archivo) &&
                //    !(archivo.Equals("<DIV></DIV>", StringComparison.CurrentCultureIgnoreCase) ||
                //    archivo.Equals("<P>&nbsp;</P>", StringComparison.CurrentCultureIgnoreCase) ||
                //    archivo.Equals("<DIV>&nbsp;</DIV>", StringComparison.CurrentCultureIgnoreCase)))
                //    nuevoItem["Estado corr."] = "PASIVA";

                AdjuntarArchivos(rutas, nuevoItem);

                nuevoItem.Update();

                return(nuevoItem.ID);
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (sitio != null)
                {
                    sitio.Dispose();
                }
            }
            #endregion
        }
Ejemplo n.º 31
0
        internal static void ToItem <T>(T entity, SPListItem listItem, List <string> propertiesToSet = null)
        {
            var itemType = entity.GetType();
            var props    = itemType.GetProperties();

            foreach (PropertyInfo prop in props)
            {
                if (CommonHelper.IsPropertyNotMapped(prop))
                {
                    continue;
                }

                Assert.IsPropertyVirtual(prop);

                if (propertiesToSet != null && propertiesToSet.Count > 0)
                {
                    if (propertiesToSet.Contains(prop.Name) == false)
                    {
                        continue;
                    }
                }

                string spName;

                // var fieldAttrs = prop.GetCustomAttributes(typeof(FieldAttribute), false);
                var fieldAttrs = Attribute.GetCustomAttributes(prop, typeof(FieldAttribute));
                CustomFieldProvider customFieldProvider = null;
                if (fieldAttrs.Length != 0)
                {
                    spName = ((FieldAttribute)fieldAttrs[0]).Name;
                    if (spName == null)
                    {
                        spName = prop.Name;
                    }
                    customFieldProvider = ((FieldAttribute)fieldAttrs[0]).FieldProvider;
                }
                else
                {
                    spName = FieldMapper.TranslateToFieldName(prop.Name);
                }
                if (FieldMapper.IsReadOnlyField(spName) == false)
                {
                    continue;                                               // skip fields that cant be set
                }
                var propValue = prop.GetValue(entity, null);

                if (propValue == null)
                {
                    listItem[spName] = null;
                    continue;
                }

                if (prop.PropertyType == typeof(string))
                {
                    listItem[spName] = propValue;
                    continue;
                }

                if (prop.PropertyType == typeof(DateTime))
                {
                    // update DateTime field with empty value thrown exception
                    if (((DateTime)propValue) != DateTime.MinValue)
                    {
                        listItem[spName] = propValue;
                    }
                    continue;
                }

                if (prop.PropertyType == typeof(User))
                {
                    // domain user or group
                    Assert.IsPropertyVirtual(prop);

                    var user = (User)propValue;

                    SPFieldUserValue spUserValue = FieldMapper.ToUserValue(user, listItem.Web);

                    listItem[spName] = spUserValue;

                    continue;
                }

                // handle lookup fields
                if (typeof(Item).IsAssignableFrom(prop.PropertyType))
                {
                    Assert.IsPropertyVirtual(prop);

                    if (customFieldProvider == null)
                    {
                        var item   = (Item)propValue;
                        var lookup = new SPFieldLookupValue(item.Id, item.Title);
                        listItem[spName] = lookup;
                    }
                    else
                    {
                        var providerType = customFieldProvider.GetType();
                        var method       = providerType.GetMethod("SetLookupItem");

                        if (method.DeclaringType == typeof(CustomFieldProvider))
                        {
                            throw new SharepointCommonException(string.Format("Must override 'SetLookupItem' in {0} to get custom lookups field working.", providerType));
                        }

                        var value = customFieldProvider.SetLookupItem(propValue);
                        listItem[spName] = value;
                    }
                    continue;
                }

                //// handle multivalue fields
                if (CommonHelper.ImplementsOpenGenericInterface(prop.PropertyType, typeof(IEnumerable <>)))
                {
                    Assert.IsPropertyVirtual(prop);

                    Type argumentType = prop.PropertyType.GetGenericArguments()[0];

                    if (argumentType == typeof(User))
                    {
                        var users = propValue as IEnumerable <User>;
                        Assert.NotNull(users);

                        var values = new SPFieldUserValueCollection();

                        foreach (User user in users)
                        {
                            if (user is Person)
                            {   // domain user or group
                                var    person = (Person)user;
                                SPUser spUser = null;
                                try
                                {
                                    spUser = listItem.ParentList.ParentWeb.SiteUsers[person.Login];
                                }
                                catch (SPException)
                                {
                                    throw new SharepointCommonException(string.Format("User {0} not found.", user.Id));
                                }

                                var val = new SPFieldUserValue();
                                val.LookupId = spUser.ID;
                                values.Add(val);
                            }
                            else
                            {   // sharepoint group
                                SPGroup spGroup = null;
                                try
                                {
                                    spGroup = listItem.ParentList.ParentWeb.SiteGroups[user.Name];
                                }
                                catch (SPException)
                                {
                                    throw new SharepointCommonException(string.Format("Group {0} not found.", user.Name));
                                }

                                var val = new SPFieldUserValue();
                                val.LookupId = spGroup.ID;
                                values.Add(val);
                            }
                        }

                        listItem[spName] = values;
                    }

                    if (typeof(Item).IsAssignableFrom(argumentType))
                    {
                        var lookupvalues = propValue as IEnumerable;

                        if (customFieldProvider == null)
                        {
                            var spLookupValues = new SPFieldLookupValueCollection();

                            foreach (Item lookupvalue in lookupvalues)
                            {
                                var val = new SPFieldLookupValue();
                                val.LookupId = lookupvalue.Id;
                                spLookupValues.Add(val);
                            }

                            listItem[spName] = spLookupValues;
                        }
                        else
                        {
                            var providerType = customFieldProvider.GetType();
                            var method       = providerType.GetMethod("SetLookupItem");

                            if (method.DeclaringType == typeof(CustomFieldProvider))
                            {
                                throw new SharepointCommonException(string.Format("Must override 'SetLookupItem' in {0} to get custom lookups field working.", providerType));
                            }

                            var values = customFieldProvider.SetLookupItem(propValue);
                            listItem[spName] = values;
                        }
                    }
                    continue;
                }

                if (prop.PropertyType.IsEnum)
                {
                    listItem[spName] = EnumMapper.ToItem(prop.PropertyType, propValue);
                    continue;
                }

                var innerType = Nullable.GetUnderlyingType(prop.PropertyType);

                if (innerType != null && innerType.IsEnum)
                {
                    listItem[spName] = EnumMapper.ToItem(innerType, propValue);
                    continue;
                }

                if (prop.PropertyType == typeof(Person))
                {
                    throw new SharepointCommonException("Cannot use [Person] as mapped property. Use [User] instead.");
                }

                listItem[spName] = propValue;
            }
        }
        /// <summary>
        /// Update SPListItem with correcsponding data parse from actions.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="updatedField"></param>
        /// <param name="data"></param>
        private void DoUpdateItem(SPListItem item, SPField updatedField, string data)
        {
            switch (updatedField.Type)
            {
                case SPFieldType.Boolean:
                    item[updatedField.Id] = Convert.ToBoolean(data);
                    break;

                case SPFieldType.File:
                case SPFieldType.Calculated:
                case SPFieldType.Computed:
                case SPFieldType.Currency:
                case SPFieldType.Integer:
                case SPFieldType.Note:
                case SPFieldType.Number:
                case SPFieldType.Text:
                    item[updatedField.Id] = data;
                    break;

                case SPFieldType.Choice:
                    SPFieldChoice fieldChoice = (SPFieldChoice)updatedField;
                    item[updatedField.Id] = data;
                    break;

                case SPFieldType.DateTime:
                    SPFieldDateTime fieldDate = (SPFieldDateTime)updatedField;
                    item[updatedField.Id] = Convert.ToDateTime(data);
                    break;

                case SPFieldType.Lookup:

                    SPFieldLookup fieldLookup = (SPFieldLookup)updatedField;
                    if (fieldLookup.AllowMultipleValues)
                    {
                        SPFieldLookupValueCollection multiValues = new SPFieldLookupValueCollection();
                        foreach (var s in data.Split("|".ToCharArray()))
                        {
                            multiValues.Add(new SPFieldLookupValue(s));
                        }
                        item[updatedField.Id] = multiValues;
                    }
                    else
                    {
                        //int id = fieldLookup.GetLookupIdFromValue(data);

                        SPFieldLookupValue singleLookupValue = new SPFieldLookupValue(data);
                        item[updatedField.Id] = singleLookupValue;
                    }
                    break;

                case SPFieldType.MultiChoice:
                    SPFieldMultiChoice fieldMultichoice = (SPFieldMultiChoice)updatedField;

                    string [] items = data.Split("|".ToCharArray());
                    SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue();
                    foreach (string choice in items)
                    {
                        values.Add(choice);
                    }

                    item[updatedField.Id] = values;

                    break;

                case SPFieldType.User:
                    SPFieldUser fieldUser = (SPFieldUser)updatedField;

                     SPFieldUserValueCollection fieldValues = new SPFieldUserValueCollection();
                     string[] entities = data.Split("|".ToCharArray());

                    foreach (string entity in entities)
                    {
                        SPUser user = item.Web.EnsureUser(entity.Split(";#".ToCharArray())[2]);
                        if(user!= null)
                        fieldValues.Add(new SPFieldUserValue(item.Web, user.ID, user.Name));
                    }

                    item[updatedField.Id] = fieldValues;
                    break;

                case SPFieldType.Invalid:
                    if (string.Compare(updatedField.TypeAsString, Constants.LOOKUP_WITH_PICKER_TYPE_NAME, true) == 0)
                    {
                        item[updatedField.Id] = data;
                    }
                    break;
            }
        }
Ejemplo n.º 33
0
        private static void iSetGridRowEdit(ref XmlDocument doc, SPWeb oWeb, XmlDocument DocIn)
        {
            Guid ListId = new Guid(DocIn.FirstChild.Attributes["listid"].Value);
            int  itemid = int.Parse(DocIn.FirstChild.Attributes["itemid"].Value);

            SPList     list      = oWeb.Lists[ListId];
            SPListItem li        = list.GetItemById(itemid);
            var        gSettings = new GridGanttSettings(list);

            oWeb.AllowUnsafeUpdates = true;

            foreach (XmlNode nd in DocIn.FirstChild.SelectNodes("//Field"))
            {
                SPField oField = null;
                try
                {
                    if (nd.Attributes["Name"].Value == "FState")
                    {
                        oField = list.Fields.GetFieldByInternalName("State");
                    }
                    else
                    {
                        oField = list.Fields.GetFieldByInternalName(nd.Attributes["Name"].Value);
                    }
                }
                catch { }
                if (oField != null)
                {
                    string sFieldValue = System.Web.HttpUtility.UrlDecode(nd.InnerText);

                    switch (oField.Type)
                    {
                    case SPFieldType.User:
                        if (nd.InnerText != "")
                        {
                            string[] sUVals = sFieldValue.Split(';');
                            SPFieldUserValueCollection uvc = new SPFieldUserValueCollection();
                            foreach (string sVal in sUVals)
                            {
                                SPFieldUserValue lv = new SPFieldUserValue(oWeb, sVal);
                                uvc.Add(lv);
                            }
                            li[oField.Id] = uvc;
                        }
                        else
                        {
                            li[oField.Id] = null;
                        }
                        break;

                    case SPFieldType.Lookup:
                        // Need to check for null / empty value otherwise it will display invalid lookup value error message
                        // when we click outside the grid after editing lookup field value by double clicking on the field.
                        if (!string.IsNullOrEmpty(nd.InnerText))
                        {
                            string[] sVals = sFieldValue.Split(';');
                            SPFieldLookupValueCollection lvc = new SPFieldLookupValueCollection();
                            foreach (string sVal in sVals)
                            {
                                SPFieldLookupValue lv = new SPFieldLookupValue(sVal);
                                lvc.Add(lv);
                            }
                            li[oField.Id] = lvc;
                        }
                        else
                        {
                            li[oField.Id] = null;
                        }
                        break;

                    case SPFieldType.MultiChoice:
                        li[oField.Id] = sFieldValue.Replace(";", ";#");
                        break;

                    case SPFieldType.Currency:
                        if (nd.InnerText == "")
                        {
                            li[oField.Id] = null;
                        }
                        else
                        {
                            li[oField.Id] = sFieldValue;
                        }
                        break;

                    case SPFieldType.Number:
                        SPFieldNumber fNum = (SPFieldNumber)oField;
                        if (fNum.ShowAsPercentage)
                        {
                            try
                            {
                                li[oField.Id] = float.Parse(sFieldValue, CultureInfo.InvariantCulture) / 100;
                            }
                            catch { li[oField.Id] = null; }
                        }
                        else
                        {
                            if (nd.InnerText == "")
                            {
                                li[oField.Id] = null;
                            }
                            else
                            {
                                li[oField.Id] = sFieldValue;
                            }
                        }
                        break;

                    case SPFieldType.DateTime:
                        if (nd.InnerText == "")
                        {
                            li[oField.Id] = null;
                        }
                        else
                        {
                            li[oField.Id] = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(double.Parse(sFieldValue));
                        }
                        break;

                    default:
                        li[oField.Id] = sFieldValue;
                        break;
                    }
                }
            }

            try
            {
                if (gSettings.EnableWorkList)
                {
                    if (li.Fields.ContainsField(FieldCompleteName))
                    {
                        if ((bool)li[FieldCompleteName])
                        {
                            li[FieldCompletePercentName] = 1;
                            if (list.Title == ListProjectCenterName)
                            {
                                li[FieldProjectCompletePercentName] = 1;
                            }
                        }
                    }
                }
            }
            catch {}

            li.Update();

            iGetRowValue(ref doc, oWeb, DocIn, list, li, true);
        }
Ejemplo n.º 34
0
        private void MatchSPFieldTypeUserIdem(SPWeb fileSPWeb, SPWeb contextSPWeb, SPListItem targetSPListItem,
                                              SPField targetSPField, string sourceValue)
        {
            // process "Person or Group" fields (including multi-valued ones)
            SPFieldUserValueCollection sourceUsers = new SPFieldUserValueCollection(fileSPWeb, sourceValue);

            if (fileSPWeb.ID == contextSPWeb.ID)
            {
                // set multi-user fields to user collection
                if ((targetSPField as SPFieldUser).AllowMultipleValues)
                {
                    targetSPListItem[targetSPField.Id] = sourceUsers;
                }

                // set single-user fields to just one user value
                else
                {
                    targetSPListItem[targetSPField.Id] = sourceUsers[0];
                }
            }
            else
            {
                SPFieldUserValueCollection targetUsers = new SPFieldUserValueCollection();

                foreach (SPFieldUserValue userValue in sourceUsers)
                {
                    string      logon     = userValue.LookupValue;
                    SPPrincipal principal = null;

                    // checking if this string is the name of a SharePoint group
                    foreach (SPGroup oGroup in contextSPWeb.SiteGroups)
                    {
                        if (oGroup.Name == logon)
                        {
                            principal = oGroup;
                            break;
                        }
                    }
                    if (principal == null)
                    {
                        // the value is not a group; try to set it as a user then.
                        try
                        {
                            principal = contextSPWeb.EnsureUser(logon);
                        }
                        catch
                        {
                        }
                    }
                    // add to user collection
                    if (principal != null)
                    {
                        targetUsers.Add(new SPFieldUserValue(contextSPWeb, principal.ID, principal.Name));
                    }
                }

                // set multi-user fields to new user collection
                if ((targetSPField as SPFieldUser).AllowMultipleValues)
                {
                    targetSPListItem[targetSPField.Id] = targetUsers;
                }

                // set single-user fields to just one user value
                else
                {
                    targetSPListItem[targetSPField.Id] = targetUsers[0];
                }
            }
        }