Пример #1
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return;
            }

            //get the collection of users from people editor
            string users = string.Empty;
            SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection();
            int index = 0;

            for (index = 0; index <= this.peContactUsers.ResolvedEntities.Count - 1; ++index)
            {
                PickerEntity objEntity = (PickerEntity)this.peContactUsers.ResolvedEntities[index];
                users += objEntity.EntityData["AccountName"] + ",";
            }

            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_INTERNAL_EMAIL_PROPERTY, users.TrimEnd(','));
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_EXTERNAL_EMAIL_PROPERTY, txtContactEmail.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_ADD_DATE_EMAIL_PROPERTY, chkAddDate.Checked.ToString());
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_TITLE_EMAIL_PROPERTY, txtEmailTitle.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_BODY_HTML_EMAIL_PROPERTY, txtHtmlBody.Text);
            GoToListSettingsPage();
        }
        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);
        }
Пример #3
0
        public List <SPUser> GetUsersFromSPFieldUser(SPListItem item, string filedName)
        {
            List <SPUser> fUsers = new List <SPUser>();
            SPWeb         web    = item.ParentList.ParentWeb;
            SPFieldUser   uField = item.Fields[" 作者 "] as SPFieldUser;

            if (!uField.AllowMultipleValues)  //未允许多重选择
            {
                SPFieldUserValue userValue = new SPFieldUserValue(web, item[filedName].ToString());
                fUsers.Add(userValue.User);
            }
            else
            {
                SPFieldUserValueCollection userValues = item[filedName] as SPFieldUserValueCollection;
                foreach (SPFieldUserValue userValue  in  userValues)
                {
                    if (userValue.User != null)
                    {
                        fUsers.Add(userValue.User);
                    }
                    //else
                    //{
                    //    SPGroup userGroup = web.SiteGroups.GetByID(userValue.LookupID);
                    //    fUsers.AddRange(userGroup.Users);
                    //}
                }
            }
            return(fUsers);
        }
Пример #4
0
        private ShimSPFieldUserValueCollection InitializeSPFieldUserValuesShim()
        {
            var result = new SPFieldUserValueCollection();

            result.Add(FieldUserValueShim);
            return(new ShimSPFieldUserValueCollection(result));
        }
Пример #5
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;
        }
Пример #6
0
        /// <summary>
        /// Recebe o item que foi adicionado e copia o item para cada nova pessoa que deve receber
        /// </summary>
        /// <param name="properties"></param>
        private void replicarItem(SPItemEventProperties properties)
        {
            using (SPWeb web = properties.Web.Site.RootWeb)
            {
                try
                {
                    web.AllowUnsafeUpdates = true;
                    SPFieldUserValueCollection usuarios = (SPFieldUserValueCollection)properties.ListItem["Destinatario"];
                    List <SPUser> SPusuarios            = capturarTodosUsuarios(usuarios, properties);
                    //usuarios = capturarTodosUsuarios(usuarios, properties);

                    foreach (SPUser usuario in SPusuarios)
                    {
                        SPList     lstCircularesEnviadas = web.Lists["DBS.CircularesEnviadas"];
                        SPListItem novoItem;

                        novoItem = lstCircularesEnviadas.Items.Add();

                        SPAttachmentCollection anexos = properties.ListItem.Attachments;

                        novoItem["Title"]          = (String)properties.ListItem["Title"];
                        novoItem["Descricao"]      = properties.ListItem["Mensagem"];
                        novoItem["Destinatario"]   = usuario;
                        novoItem["EnviarEmail"]    = (bool)properties.ListItem["EnviarEmail"];
                        novoItem["Ciente"]         = false;
                        novoItem["DataHoraCiente"] = null;
                        novoItem.Update();  //Para poder incluir anexos, é necessário ter salvo previamente o novo item

                        //Copiando os anexos:
                        if (anexos.Count > 0)
                        {
                            //get the folder with the attachments for the source item
                            SPFolder sourceItemAttachmentsFolder =
                                properties.ListItem.Web.Folders["Lists"].SubFolders[properties.ListItem.ParentList.Title].SubFolders["Attachments"].SubFolders[properties.ListItem.ID.ToString()];
                            //Loop over the attachments, and add them to the target item
                            foreach (SPFile file in sourceItemAttachmentsFolder.Files)
                            {
                                byte[] binFile = file.OpenBinary();
                                novoItem.Attachments.AddNow(file.Name, binFile);
                            }
                            novoItem.Update();
                        }

                        //Envio o e-mail
                        EnviarEmail(web, usuario, properties.ListItem);
                        novoItem["EmailEnviado"] = true;
                        novoItem.Update();
                    }
                }
                catch (Exception ex)
                {
                    //todo: salvar em algum lugar essa exception
                    throw ex;
                }
                finally
                {
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
Пример #7
0
        private static void setPerrmissionToListItem(SPListItem listItem, PermissionAssigment pa)
        {
            List<string> members = new List<string>();
            if (pa.Members != null && pa.Members.Count > 0)
            {
                members.AddRange(pa.Members);
            }

            if (pa.FieldIds != null && pa.FieldIds.Count > 0)
            {
                foreach (string fieldId in pa.FieldIds)
                {
                    if (listItem.Fields.ContainFieldId(new Guid(fieldId)) && listItem[new Guid(fieldId)] != null)
                    {
                        SPFieldUserValueCollection users = new SPFieldUserValueCollection(listItem.Web, listItem[new Guid(fieldId)].ToString());
                        foreach (SPFieldUserValue user in users)
                        {
                            if (user.User != null)
                                members.Add(user.LookupId + ";#" + user.User.LoginName);
                            else
                                members.Add(user.ToString());
                        }
                    }
                }
            }

            listItem.SetPermissions(pa.PermissionLevel, members);
        }
Пример #8
0
        //根据当前时间判断当前进行到什么审批阶段,如果为空则当前没有进行审批
        //用户是否有权限
        private bool UserHasAttachRight(SPUser user, int itemID)
        {
            bool isRight = false;

            using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb sWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
                {
                    SPList sList = sWeb.Lists.TryGetList(webObj.ListName);
                    if (sList != null)
                    {
                        SPListItem       item   = sList.GetItemById(itemID);
                        SPFieldUserValue author = new SPFieldUserValue(sWeb, (item["创建者"].ToString()));
                        if (author.LookupId == user.ID)
                        {
                            isRight = true;
                        }
                        else
                        {
                            SPFieldUserValueCollection adUsers = item["AuthorName"] as SPFieldUserValueCollection;
                            foreach (SPFieldUserValue adUser in adUsers)
                            {
                                if (adUser.LookupId == user.ID)
                                {
                                    isRight = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return(isRight);
        }
Пример #9
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            SPFieldUserValueCollection users = (SPFieldUserValueCollection)properties.ListItem["Inviter"];

            foreach (SPFieldUserValue user in users)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(properties.Site.ID, user.User.UserToken))
                    {
                        using (SPWeb web = site.OpenWeb(properties.Web.ID))
                        {
                            SPList list             = web.Lists.TryGetList("SPForumsMessageList");
                            SPList post             = web.Lists.TryGetList("SPForumsPostList");
                            SPListItem postItem     = post.GetItemById(Convert.ToInt32(properties.ListItem["Title"]));
                            SPListItem itemAdd      = list.Items.Add();
                            itemAdd["Title"]        = "[Reply Invite]Post Title:" + postItem["Title"];
                            itemAdd["MessageLink"]  = post.DefaultDisplayFormUrl + "?ID=" + properties.ListItem["Title"];
                            itemAdd["ReplyContent"] = properties.ListItem["Reply"];
                            itemAdd["IsRead"]       = "No";
                            itemAdd.SystemUpdate();
                        }
                    }
                });
            }
            //base.ItemAdded(properties);
        }
Пример #10
0
        public string GetFieldValueUserCollectionEmails(SPListItem item, 
                                                        string fieldName)
        {
            string emails = "";

            if (item != null &&
                item.Fields.ContainsField(fieldName) &&
                item[fieldName] != null)
            {
                string fieldVal = item[fieldName].ToString();

                SPFieldUserValueCollection usersV =
                    new SPFieldUserValueCollection(item.Web, fieldVal);

                foreach (SPFieldUserValue uv in usersV)
                {
                    emails += uv.User.Email + "; ";
                }

                return emails;

            }
            else
            {
                return string.Empty;
            }
        }
        public static void UnLike(SPWeb web, SPUser user, SPListItem listItem)
        {
            try
            {
                if (listItem["LikedBy"] != null)
                {
                    var likedBy = new SPFieldUserValueCollection(web, listItem["LikedBy"].ToString());

                    if (likedBy.Any(f => f.LookupId == user.ID))
                    {
                        var deleteUser = likedBy.First(f => f.LookupId == user.ID);

                        int likes = likedBy.Distinct().Count();

                        likedBy.Remove(deleteUser);
                        likes = likes - 1;
                        listItem["LikesCount"] = likes;
                        listItem["LikedBy"]    = likedBy;

                        listItem.SystemUpdate(false);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Logger.Unexpected("LikesColumn.UnLike", e.Message);
                throw e;
            }
        }
Пример #12
0
        private void AddCustomPermissions(SPListItem myItem, SPWeb web)
        {
            // Give Contribute to the author
            SPRoleDefinition roledefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
            SPRoleAssignment roleAssignment = new SPRoleAssignment(GetSPUser(myItem, "Author"));

            roleAssignment.RoleDefinitionBindings.Add(roledefinition);
            myItem.RoleAssignments.Add(roleAssignment);

            // Give Read to anyone that the item has been shared with
            if (myItem["SharedWith"] != null)
            {
                SPFieldUserValueCollection values = (SPFieldUserValueCollection)myItem["SharedWith"];

                foreach (SPFieldUserValue value in values)
                {
                    // Get a user from the key
                    var sharedUser = value.User;
                    // Change our role definition to Read
                    roledefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                    // Change our role assignment to the new user
                    roleAssignment = new SPRoleAssignment(sharedUser);
                    // Bind the new role
                    roleAssignment.RoleDefinitionBindings.Add(roledefinition);
                    myItem.RoleAssignments.Add(roleAssignment);
                }
            }
        }
        private void SetFieldUser(SPListItem item, SPWeb web, object valor, PropertyInfo prop, bool addPrefix)
        {
            var userList = (List <UserSP>)valor;
            var result   = new StringBuilder();

            foreach (var userd in userList)
            {
                if (!string.IsNullOrEmpty(result.ToString()))
                {
                    result.Append(";");
                }
                result.Append(userd.Key);
            }
            if (userList.Count == 1)
            {
                item[GetInternalName(prop.Name, addPrefix)] = !string.IsNullOrEmpty(result.ToString())
                    ? result.ToString()
                    : string.Empty;
            }
            else
            {
                Logger.Warn("Estoy insertando un multiusuario");
                var usercollection = new SPFieldUserValueCollection();
                usercollection.AddRange(
                    userList.Select(userd => new SPFieldUserValue(web, Convert.ToInt32(userd.Key), userd.LoginName)));
                item[GetInternalName(prop.Name, addPrefix)] = usercollection;
            }
        }
Пример #14
0
        private bool UserIsAssigned(int userID, SPListItem item)
        {
            bool    isAssigned = false;
            SPField testFld    = null;

            try
            {
                testFld = item.Fields[item.Fields.GetFieldByInternalName("AssignedTo").Id];
            }
            catch { }

            if ((testFld != null) && (item[item.Fields.GetFieldByInternalName("AssignedTo").Id] != null))
            {
                SPFieldUserValueCollection uc = (SPFieldUserValueCollection)item[item.Fields.GetFieldByInternalName("AssignedTo").Id];
                foreach (SPFieldUserValue uv in uc)
                {
                    if (uv.LookupId == userID)
                    {
                        isAssigned = true;
                        break;
                    }
                }
            }

            return(isAssigned);
        }
Пример #15
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);
        }
Пример #16
0
        /// <summary>
        /// Gets a collection of <see cref="SPPrincipal"/> objects from a multiple User field.
        /// </summary>
        /// <param name="fieldName">Field name.</param>
        /// <returns>A collection of <see cref="SPPrincipal"/> objects.</returns>
        protected virtual IList <SPPrincipal> GetMultiUserFieldValueInternal(string fieldName)
        {
            Collection <SPPrincipal> collection = new Collection <SPPrincipal>();
            object value = this[fieldName];

            if (value != null)
            {
                try {
                    SPFieldUserValueCollection values = CommonHelper.TryCastOrDefault <SPFieldUserValueCollection>(value) ?? new SPFieldUserValueCollection(this.Web, value.ToString());
                    foreach (SPFieldUserValue u in values)
                    {
                        if (u.LookupId == -1)
                        {
                            using (this.Web.GetAllowUnsafeUpdatesScope()) {
                                collection.Add(this.Web.EnsureUser(u.LookupValue));
                            }
                        }
                        else if (u.User != null)
                        {
                            collection.Add(u.User);
                        }
                        else if (u.LookupId > 0)
                        {
                            collection.Add(this.Web.SiteGroups.GetByID(u.LookupId));
                        }
                    }
                } catch { }
            }
            return(collection);
        }
Пример #17
0
        void Refresh()
        {
            this.Name  = m_Item[TemplateCT.TemplateName] as string;
            this.State = EnumConverter.ToState(m_Item[TemplateCT.TemplateState] as string);

            SPFieldUserValueCollection v = new SPFieldUserValueCollection(m_Item.Web, m_Item.GetFieldValue <object>(TemplateCT.SendDraftTo, string.Empty).ToString());

            this.SendDraftToAdresses = v.Select(p => p.User.Email).ToList();

            this.UseFileForSubject = m_Item.GetFieldValue <bool>(TemplateCT.TemplateSubjectUseFile);
            this.UseFileForBody    = m_Item.GetFieldValue <bool>(TemplateCT.TemplateBodyUseFile);
            this.UseFileForFrom    = m_Item.GetFieldValue <bool>(TemplateCT.TemplateFromUseFile);
            this.UseFileForReply   = m_Item.GetFieldValue <bool>(TemplateCT.TemplateReplayUseFile);

            this.From    = m_Item.GetValueFromTextFieldOrFile(this.UseFileForFrom, TemplateCT.TemplateFrom, TemplateCT.TemplateFromFile, out FromAttached);
            this.Replay  = m_Item.GetValueFromTextFieldOrFile(this.UseFileForReply, TemplateCT.TemplateReplay, TemplateCT.TemplateReplayFile, out ReplyAttached);
            this.Body    = m_Item.GetValueFromTextFieldOrFile(this.UseFileForBody, TemplateCT.TemplateBody, TemplateCT.TemplateBodyFile, out this.BodyAttached);
            this.Subject = m_Item.GetValueFromTextFieldOrFile(this.UseFileForSubject, TemplateCT.TemplateSubject, TemplateCT.TemplateSubjectFile, out this.SubjectAttached);

            if (m_Item[TemplateCT.TemplateType] != null)
            {
                var val = new SPFieldMultiChoiceValue(m_Item[TemplateCT.TemplateType].ToString());
                this.EventTypes = EnumConverter.ToType(val);
            }
            else
            {
                this.EventTypes = (int)TemplateTypeEnum.Unknown;
            }

            this.Associations = AssociationCollection.ParseOrDefault(m_Item[TemplateCT.Associations] as string);
        }
        private string GetEmailByEnquiry(SPWeb web, int id)
        {
            string email = string.Empty;
            try
            {
                var enquiryList = Utility.GetListFromURL(Constants.TYPE_OF_ENQUIRY_LIST_URL, web);
                if (enquiryList != null)
                {
                    SPListItem item = enquiryList.GetItemById(id);
                    if (item["InternalEmail"] != null)
                    {
                        SPFieldUserValueCollection userValueCollection = new SPFieldUserValueCollection(web, item["InternalEmail"].ToString());
                        if (userValueCollection != null && userValueCollection.Count > 0)
                        {
                            foreach (SPFieldUserValue us in userValueCollection)
                            {
                                email += us.User.Email + ";";
                            }
                        }
                    }

                    email += (item["ExternalEmail"] == null ? string.Empty : item["ExternalEmail"].ToString());
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, AIAPortalFeatures.Infrastructure);
            }
            return email;
        }
        private void CheckManager(SPListItem item, string loginName)
        {
            List <string> doubledUsers = new List <string>();

            if (item["Person in charge"] is SPFieldUserValueCollection)
            {
                SPFieldUserValueCollection fieldValues = item["Person in charge"] as SPFieldUserValueCollection;
                if (fieldValues.Where(fv => fv.User.LoginName == loginName).Count() > 0)
                {
                    List <SPFieldUserValue> otherFieldValues = fieldValues.Where(fv => fv.User.LoginName != loginName).ToList();
                    foreach (SPFieldUserValue uv in otherFieldValues)
                    {
                        doubledUsers.Add(uv.LookupId + ";#" + uv.LookupValue);
                    }
                    CompleteTasks(item, doubledUsers);
                    return;
                }
            }


            //CheckManager(sourceItem, "Tax");
            //CheckManager(sourceItem, "Finance");
            //CheckManager(sourceItem, "Compliance");
            //CheckManager(sourceItem, "Internal Control");
        }
Пример #20
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);
        }
Пример #21
0
        private string GetEmailByEnquiry(SPWeb web, int id)
        {
            string email = string.Empty;

            try
            {
                var enquiryList = Utility.GetListFromURL(Constants.TYPE_OF_ENQUIRY_LIST_URL, web);
                if (enquiryList != null)
                {
                    SPListItem item = enquiryList.GetItemById(id);
                    if (item["InternalEmail"] != null)
                    {
                        SPFieldUserValueCollection userValueCollection = new SPFieldUserValueCollection(web, item["InternalEmail"].ToString());
                        if (userValueCollection != null && userValueCollection.Count > 0)
                        {
                            foreach (SPFieldUserValue us in userValueCollection)
                            {
                                email += us.User.Email + ";";
                            }
                        }
                    }

                    email += (item["ExternalEmail"] == null ? string.Empty : item["ExternalEmail"].ToString());
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, AIAPortalFeatures.Infrastructure);
            }
            return(email);
        }
 public bool IsExistUser(SPListItem item, string sLowerUser)
 {
     try
     {
         //retrieve user value collection from the "AssignedTo" field and iterate
         SPFieldUserValueCollection usersFields = new SPFieldUserValueCollection(SPContext.Current.Web.Site.RootWeb, item["Permission"].ToString());
         foreach (SPFieldUserValue usersField in usersFields)
         {
             if (usersField.User == null)
             {
                 //UserField contains a SharePoint group -> extract users from it
                 SPGroup group = SPContext.Current.Web.Groups.GetByID(usersField.LookupId);
                 foreach (SPUser user in group.Users)
                 {
                     if (user.LoginName.ToLower() == sLowerUser)
                     {
                         return(true);
                     }
                 }
             }
             else
             {
                 if (usersField.User.LoginName == sLowerUser)
                 {
                     return(true);
                 }
             }
         }
     }
     catch (Exception)
     {
         return(false);
     }
     return(false);
 }
Пример #23
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);
        }
Пример #24
0
 public SPFieldUserValueCollectionInstance(ScriptEngine engine, SPFieldUserValueCollection fieldUserValueCollection)
     : base(new ListInstance <SPFieldUserValueCollectionInstance, SPFieldUserValue>(engine))
 {
     this.m_fieldUserValueCollection = fieldUserValueCollection;
     this.List = fieldUserValueCollection;
     this.PopulateFunctions(this.GetType(),
                            BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
 }
Пример #25
0
 private static void AssignRights(SPWeb web, SPFieldUserValueCollection users, SPRoleDefinition roleDefinition,
                                  SPListItem item)
 {
     foreach (SPFieldUserValue value2 in users)
     {
         AssignRights(web, value2, roleDefinition, item);
     }
 }
        private bool IsNotValidate(string name, SPFieldUserValue director, SPFieldUserValueCollection members)
        {
            bool hasNotName     = string.IsNullOrWhiteSpace(name);
            bool hasNotDirector = director == null;
            bool hasNotMembers  = members == null || !members.Any();

            return(hasNotName || hasNotDirector || hasNotMembers);
        }
Пример #27
0
 private static void AssignRights(SPWeb web, SPFieldUserValueCollection users, SPRoleDefinition roleDefinition,
                                  SPFolder folder)
 {
     foreach (SPFieldUserValue value2 in users)
     {
         AssignRights(web, value2, roleDefinition, folder);
     }
 }
Пример #28
0
        private void MatchSPFieldTextOrChoice(SPListItem targetSPListItem, SPField targetSPField,
                                              SPWeb sourceSPWeb, SPField sourceSPField, string sourceValue)
        {
            // get just the term label
            if (sourceSPField is TaxonomyField)
            {
                targetSPListItem[targetSPField.Id] =
                    this.SubstringBefore(sourceValue,
                                         TaxonomyField.TaxonomyGuidLabelDelimiter.ToString(CultureInfo.InvariantCulture));
            }

            // for lookup and custom fields, convert RAW values into plain text
            else if (sourceSPField.Type == SPFieldType.Lookup || sourceSPField.Type == SPFieldType.Invalid)
            {
                SPFieldLookup spFieldLookupField = sourceSPField as SPFieldLookup;
                if (spFieldLookupField == null)
                {
                    // TODO: multi-valued source fields should be deconstructed properly!
                    targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#");
                }
                else
                {
                    if (spFieldLookupField.AllowMultipleValues)
                    {
                        string formatted = string.Empty;
                        SPFieldLookupValueCollection spFieldLookupValues =
                            new SPFieldLookupValueCollection(sourceValue);
                        foreach (SPFieldLookupValue spFieldLookupValue in spFieldLookupValues)
                        {
                            formatted = formatted + ";" + spFieldLookupValue.LookupValue;
                        }

                        targetSPListItem[targetSPField.Id] = formatted.TrimStart(';');
                    }
                    else
                    {
                        SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(sourceValue);
                        targetSPListItem[targetSPField.Id] = spFieldLookupValue.LookupValue;
                    }
                }
            }
            else if (sourceSPField.Type == SPFieldType.User)
            {
                // TODO: TEST THIS !!!!!!!!
                string formatted = string.Empty;
                SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection(sourceSPWeb, sourceValue);
                foreach (SPFieldLookupValue spFieldLookupValue in spFieldUserValues)
                {
                    formatted = formatted + ";" + spFieldLookupValue.LookupValue;
                }

                targetSPListItem[targetSPField.Id] = formatted.TrimStart(';');
            }
            else
            {
                targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#");
            }
        }
Пример #29
0
        public static string GetStringValue(this SPListItem item, string fieldname)
        {
            if (item[fieldname] == null || string.IsNullOrEmpty(item[fieldname].ToString().Trim()))
            {
                return(string.Empty);
            }
            SPField field = item.Fields.GetField(fieldname);
            string  ReturnValue;

            switch (field.Type)
            {
            case SPFieldType.Lookup:
                if (((SPFieldLookup)field).AllowMultipleValues == false)
                {
                    SPFieldLookupValue lookup = new SPFieldLookupValue(item[fieldname].ToString());
                    ReturnValue = lookup.LookupValue;
                }
                else
                {
                    SPFieldLookupValueCollection lookup = new SPFieldLookupValueCollection(item[fieldname].ToString());
                    ReturnValue = "";
                    foreach (SPFieldLookupValue v in lookup)
                    {
                        ReturnValue += v.LookupValue + ";";
                    }
                    ReturnValue.TrimEnd(';');
                }
                break;

            case SPFieldType.User:
                if (((SPFieldUser)field).AllowMultipleValues == false)
                {
                    SPFieldUserValue users = new SPFieldUserValue(item.Web, item[fieldname].ToString());
                    ReturnValue = users.User.Name;
                }
                else
                {
                    SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, item[fieldname].ToString());
                    ReturnValue = users[0].User.Name;
                }
                break;

            case SPFieldType.MultiChoice:
                SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue(item[fieldname].ToString());
                ReturnValue = "";
                for (int i = 0; i < values.Count; i++)
                {
                    ReturnValue += values[i].ToString() + ";";
                }
                ReturnValue.TrimEnd(';');
                break;

            default:
                ReturnValue = item[fieldname].ToString().Trim();
                break;
            }
            return(ReturnValue);
        }
Пример #30
0
        public static bool CompareObject(SPFieldUserValueCollection x, object y)
        {
            if (y == null || y is DBNull)
            {
                return(false);
            }

            return(x.Sum(p => p.LookupId) == Utils.Cast <SPFieldUserValueCollection>(y).Sum(p => p.LookupId));
        }
Пример #31
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);
        }
Пример #32
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);
            }
        }
Пример #33
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;
                    }
                }
            });
        }
 private void SetItemPermission(SPWeb web, Guid listId, int itemId, SPFieldUserValueCollection userValueCollections)
 {
     SPList list = web.Lists[listId];
     SPListItem listItem = list.GetItemById(itemId);
     listItem.RemoveAllPermissions();
     foreach (SPFieldUserValue userValue in userValueCollections)
     {
         listItem.SetPermissions(userValue.User, SPRoleType.Contributor);
     }
 }
Пример #35
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();
        }
Пример #36
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;
        }
Пример #37
0
        /// <summary>
        /// Метод возвращает необходимые состояния кнопок для карточки КМ
        /// </summary>
        /// <param name="Item">Текущий Item</param>
        /// <param name="State">Текущий статус карточки</param>
        /// <returns></returns>
        private static AccessData GetCMAccessData(SPWeb Web, SPGroup Group, SPListItem Item, CardState State, List<string> Companies)
        {
            AccessData result = new AccessData();

            bool IsExpert = Group.Name == GlobalConstants.Groups.Expert;

            bool InCompany = Companies.Any(Company => Item[GlobalConstants.ControlMeasure_Fields.CompanyName].ToString().Contains(Company));

            bool Approver = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Approver].ToString()).User.ID == Web.CurrentUser.ID;

            bool Responsible = new SPFieldUserValue(Web, Item[GlobalConstants.ControlMeasure_Fields.Responsible].ToString()).User.ID == Web.CurrentUser.ID;

            bool InMailingList = new SPFieldUserValueCollection(Web, Item[GlobalConstants.ControlMeasure_Fields.MailingList].ToString()).Any(User => User.User.ID == Web.CurrentUser.ID);

            bool AuditorOrAdministrator = Group.Name == GlobalConstants.Groups.Administrator || Group.Name == GlobalConstants.Groups.Auditor;

            result.Edit.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Edit.Visible = State;

            result.Bind.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Bind.Visible = State;

            result.CreateNewRequestCM.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator);
            result.CreateNewRequestCM.Visible = State;

            result.ExcelExport.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert)&& (!AuditorOrAdministrator);
            result.ExcelExport.Visible = State;

            result.ToAffirmation.Enabled = ((InCompany || Responsible || InMailingList) && IsExpert) && (!AuditorOrAdministrator);
            result.ToAffirmation.Visible = State;

            result.ToWork.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator);
            result.ToWork.Visible = State;

            result.ToRework.Enabled = (Approver && IsExpert) && (!AuditorOrAdministrator);
            result.ToRework.Visible = State;

            result.Close.Enabled = ((InCompany || Approver || Responsible || InMailingList) && IsExpert) || (InMailingList && AuditorOrAdministrator);
            result.Close.Visible = State;

            //
            //Нужно доделать доступность кнопок в зависимости от дополнительных параметров, как-то : указана ли компания, какой текущий статус карточки и тд тп
            //
            //                                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            return result;
        }
	    public object FromSpValue(object value)
		{
			if (value == null)
				return null;

			if (!Field.AllowMultipleValues)
			{
				var fieldValue = new SPFieldUserValue(Field.ParentList.ParentWeb, value.ToString());

				return new UserInfo(fieldValue.User);
			}

			var fieldValues = new SPFieldUserValueCollection(Field.ParentList.ParentWeb, value.ToString());
		    var users = fieldValues.Select(fieldValue => fieldValue.User).Select(user => new UserInfo(user));

		    return PropertyType == typeof (UserInfo[]) ? (object) users.ToArray() : users.ToList();
		}
        public object ToSpValue(object value)
		{
			if (value == null)
				return null;

			if (!Field.AllowMultipleValues)
			{
				var userInfo = value as UserInfo;

				return new SPFieldUserValue(Field.ParentList.ParentWeb, userInfo.Id, userInfo.Login);
			}

			var userInfos = (IEnumerable<UserInfo>)value;

			var fieldValues = new SPFieldUserValueCollection();
			fieldValues.AddRange(userInfos.Select(userInfo => new SPFieldUserValue(Field.ParentList.ParentWeb, userInfo.Id, userInfo.Login)));

			return fieldValues;
		}
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            //get the collection of users from people editor
            string users = string.Empty;
            SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection();
            int index = 0;
            for (index = 0; index <= this.peContactUsers.ResolvedEntities.Count - 1; ++index)
            {
                 PickerEntity objEntity = (PickerEntity)this.peContactUsers.ResolvedEntities[index];
                 users += objEntity.EntityData["AccountName"] + ",";
            }

            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_INTERNAL_EMAIL_PROPERTY, users.TrimEnd(','));
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_EXTERNAL_EMAIL_PROPERTY, txtContactEmail.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_ADD_DATE_EMAIL_PROPERTY, chkAddDate.Checked.ToString());
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_TITLE_EMAIL_PROPERTY, txtEmailTitle.Text);
            SPContext.Current.List.SetCustomProperty(Constants.CONTACT_BODY_HTML_EMAIL_PROPERTY, txtHtmlBody.Text);
            GoToListSettingsPage();
        }
Пример #41
0
        public static SPFieldUserValueCollection GetAgendaContentProviders(string agendaType)
        {
            SPList list = SPContext.Current.Web.Lists["Agenda Coordinators"];

            SPFieldUserValueCollection authUsers = null;

            if (list != null)
            {
                foreach (SPListItem item in list.Items)
                {
                    if (item["Agenda Type"].ToString() == agendaType)
                    {
                        string authUsersFieldValue = item["ContentProviders"].ToString();

                        authUsers = new SPFieldUserValueCollection(item.Web, authUsersFieldValue);
                        break;
                    }
                }
                return authUsers;
            }
            else
                return null;
        }
Пример #42
0
 public void AddWorkFlowStepApprovers(string workFlowStep, string approvers, string approversLoginName)
 {
     var rootweb = SPContext.Current.Site.RootWeb;
     var web = SPContext.Current.Web;
     var fields = WorkflowContext.Current.DataFields;
     var curUser = web.CurrentUser;
     //审批过该条单子的人集合
     var approverList = new List<string>();
     //var approverUsers = fields[approvers].AsString();
     //var userValueColl = fields[approversLoginName] as SPFieldUserValueCollection;
     var approverUsers = fields[approversLoginName].AsString();
     var userValueColl = fields[approvers] as SPFieldUserValueCollection;
     if (userValueColl == null)
     {
         userValueColl = new SPFieldUserValueCollection();
     }
     if (!string.IsNullOrEmpty(approverUsers))
     {
         approverList = approverUsers.Split(';').ToList<string>();
     }
     List<string> workFlowStepsAndUsers = fields["WorkFlowStepsAndUsers"].AsString().Split(';').ToList<string>();
     foreach (string str in workFlowStepsAndUsers)
     {
         if (str.IndexOf(workFlowStep) != -1)
         {
             string workFlowStepsAndUsersNameCollection = str.Replace(workFlowStep + ":", "").Trim();
             foreach (var currentStepApprover in workFlowStepsAndUsersNameCollection.Split(','))
             {
                 if (!string.IsNullOrEmpty(currentStepApprover) && !approverList.Contains(currentStepApprover))
                 {
                     try
                     {
                         var spUser = web.AllUsers[currentStepApprover];
                         approverList.Add(currentStepApprover);
                         userValueColl.Add(new SPFieldUserValue(rootweb, spUser.ID, spUser.Name));
                     }
                     catch (Microsoft.SharePoint.SPException)
                     {
                         //错误信息日志记录
                     }
                 }
             }
         }
     }
     //加上当前审批者(当前审批者是某个审批人的代理的场合)
     if (!approverList.Contains(curUser.LoginName))
     {
         try
         {
             approverList.Add(curUser.LoginName);
             userValueColl.Add(new SPFieldUserValue(rootweb, curUser.ID, curUser.Name));
         }
         catch (Microsoft.SharePoint.SPException)
         {
             //错误信息日志记录
         }
     }
     fields[approvers] = userValueColl;
     fields[approversLoginName] = string.Join(";", approverList.ToArray());
 }
Пример #43
0
        /**
         * 将一组用户帐号添加到字段中,如果字段中已包含该帐号则不用重复添加
         * 添加字段为People Group类型,返回类型同样为People Group类型
         */
        protected SPFieldUserValueCollection ReturnAllApproversSP(string approverCol, params string[] accounts)
        {
            var web = SPContext.Current.Web;
            SPUser user = null;
            SPFieldUserValue spUser = null;
            SPFieldUserValueCollection approvers = WorkflowContext.Current.DataFields[approverCol] as SPFieldUserValueCollection;

            foreach (var account in accounts)
            {
                user = web.AllUsers[account];
                spUser = new SPFieldUserValue(web, user.ID, user.Name);

                if (approvers == null)
                {
                    approvers = new SPFieldUserValueCollection();
                }
                if (!approvers.Contains(spUser))
                {
                    approvers.Add(spUser);
                }
            }

            return approvers;
        }
Пример #44
0
        public static bool CompareObject(SPFieldUserValueCollection x, object y)
        {
            if (y == null || y is DBNull)
            {
                return false;
            }

            return x.Sum(p => p.LookupId) == Utils.Cast<SPFieldUserValueCollection>(y).Sum(p => p.LookupId);
        }
Пример #45
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;
        }
        public List<DataPublishPage> GetApprovalinformationByUser()
        {
            List<DataApprove> dataapproveList = new List<DataApprove>();
            List<DataPublishPage> dataPublishPageList = new List<DataPublishPage>();
            List<DataPublishPage> ResultdataPublishPageList = new List<DataPublishPage>();
            ResultdataApprovgedPages = new List<DataPublishPage>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(this.siteID))
                {
                    using (SPWeb web = site.OpenWeb(this.webID))
                    {
                        if (web.Lists.TryGetList(this.approveList) != null && web.Lists.TryGetList(this.listName) != null)
                        {
                            SPList PublicPageList = web.Lists[this.listName];
                            SPQuery pageListQuery = new SPQuery();
                            pageListQuery.Query = "<Where><Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>Approved</Value></Eq></Where>";
                            pageListQuery.Folder = PublicPageList.RootFolder.SubFolders["Policies"];
                            SPListItemCollection pagesCollection = PublicPageList.GetItems(pageListQuery);
                            foreach (SPListItem pageItem in pagesCollection)
                            {
                                string tempversion = string.Empty;
                                string tempcategory = string.Empty;
                                SPFieldUserValueCollection localSharePointGroup = null;
                                if(pageItem.Fields.ContainsField(constants.columns.PageList.Version) && pageItem[constants.columns.PageList.Version] != null)
                                    tempversion = pageItem[constants.columns.PageList.Version].ToString();
                                if (pageItem.Fields.ContainsField(constants.columns.PageList.PageCategory) && pageItem[constants.columns.PageList.PageCategory] != null)
                                    tempcategory = pageItem[constants.columns.PageList.PageCategory].ToString();
                                if (pageItem[constants.columns.PageList.ApprovalGroup] != null)
                                {
                                    localSharePointGroup = new SPFieldUserValueCollection(pageItem.Web, pageItem[constants.columns.PageList.ApprovalGroup].ToString());
                                    if (localSharePointGroup[0].User == null)
                                    {
                                        if (SPContext.Current.Web.Groups.GetByID(localSharePointGroup[0].LookupId) != null)
                                        {
                                            if (isUserinGroup(SPContext.Current.Site.ID, SPContext.Current.Web.ID, localSharePointGroup[0].LookupId, SPContext.Current.Web.CurrentUser))
                                            {
                                                dataPublishPageList.Add(new DataPublishPage
                                                {
                                                    PageID = pageItem.ID.ToString(),
                                                    PageName = pageItem.Title,
                                                    PageURL = (string)pageItem[SPBuiltInFieldId.EncodedAbsUrl],
                                                    PageVersion = tempversion,
                                                    PageCategory = tempcategory,
                                                    PageGroup = localSharePointGroup
                                                });
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (localSharePointGroup[0].User.LoginName.Equals(SPContext.Current.Web.CurrentUser.LoginName))
                                        {
                                            dataPublishPageList.Add(new DataPublishPage
                                            {
                                                PageID = pageItem.ID.ToString(),
                                                PageName = pageItem.Title,
                                                PageURL = pageItem.Url,
                                                PageVersion = tempversion,
                                                PageCategory = tempcategory,
                                                PageGroup = localSharePointGroup
                                            });
                                        }
                                    }
                                }
                            }

                            SPList apporoveList = web.Lists[this.approveList];
                            if (isValidList(apporoveList))
                            {
                                SPQuery listQuery = new SPQuery();
                                //listQuery.Query = string.Format("<Where><Eq><FieldRef Name='Approve_x0020_Page_x0020_ID' /><Value Type='Number'>{0}</Value></Eq></Where>", pageid);
                                //listQuery.Query = string.Format("<Query><Where><Eq><FieldRef Name='Author' LookupId=’TRUE’/><Value Type=’Integer’><UserID/></Value></Eq></Where></Query>");

                                SPListItemCollection cgenericCollection = apporoveList.GetItems(listQuery);
                                string cuserln = SPContext.Current.Web.CurrentUser.ID.ToString();
                                foreach (SPListItem approveItem in cgenericCollection)
                                {
                                    string PageName = string.Empty;
                                    if (approveItem["Author"].ToString().Split(';')[0].Equals(cuserln))
                                    {
                                        string PageVersion = string.Empty;
                                        string PageCategory = string.Empty;
                                        string PageID = string.Empty;

                                        if (approveItem.Fields.ContainsField(constants.columns.ApprovalList.Title) && approveItem[constants.columns.ApprovalList.Title] != null)
                                        {
                                            PageName = approveItem[constants.columns.ApprovalList.Title].ToString();
                                        }

                                        if (approveItem.Fields.ContainsField(constants.columns.ApprovalList.Version) && approveItem[constants.columns.ApprovalList.Version] != null)
                                        {
                                            PageVersion = approveItem[constants.columns.ApprovalList.Version].ToString();
                                        }

                                        if (approveItem.Fields.ContainsField(constants.columns.ApprovalList.ApprovePageID) && approveItem[constants.columns.ApprovalList.ApprovePageID] != null)
                                        {
                                            PageCategory = approveItem[constants.columns.ApprovalList.PageCategory].ToString();
                                        }

                                        if (approveItem.Fields.ContainsField(constants.columns.ApprovalList.ApprovePageID) && approveItem[constants.columns.ApprovalList.ApprovePageID] != null)
                                        {
                                            PageID = approveItem[constants.columns.ApprovalList.ApprovePageID].ToString();
                                        }

                                        dataapproveList.Add(new DataApprove
                                        {
                                            PageName = PageName,
                                            PageID = PageID,
                                            Version = PageVersion,
                                            Category = PageCategory
                                        });
                                    }
                                }

                                //get all pages
                                foreach (DataPublishPage DPP in dataPublishPageList)
                                {
                                    int approveCount = dataapproveList.Count(ap => ap.PageID == DPP.PageID && ap.Version == DPP.PageVersion);
                                    if ( approveCount <= 0)
                                    {
                                        ResultdataPublishPageList.Add(DPP);
                                    }
                                    else
                                    {
                                        ResultdataApprovgedPages.Add(DPP);
                                    }
                                }
                                int dd = ResultdataPublishPageList.Count;
                            }
                            else
                            {
                                //This list is not valid. It has not all teh necesasary columns
                                this.ApproveMessageError = "The list does not have the correct columns";
                            }
                        }
                        else
                        {
                            //This list doesn't exist
                            this.ApproveMessageError = "The list doesn't exist";
                        }
                    }
                }
            });
            return ResultdataPublishPageList;
        }
        public void ToEntity_WhenMappingFromListItem_AndItemPropertiesAreFilledWithValues_ShouldMapEntityWithAllItemValues()
        {
            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo(
                    "TestInternalNameInteger",
                    new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"),
                    "NameKeyInt",
                    "DescriptionKeyInt",
                    "GroupKey");

                NumberFieldInfo numberFieldInfo = new NumberFieldInfo(
                    "TestInternalNameNumber",
                    new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"),
                    "NameKeyNumber",
                    "DescriptionKeyNumber",
                    "GroupKey");

                CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo(
                    "TestInternalNameCurrency",
                    new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"),
                    "NameKeyCurrency",
                    "DescriptionKeyCurrency",
                    "GroupKey");

                BooleanFieldInfo boolFieldInfoBasic = new BooleanFieldInfo(
                    "TestInternalNameBool",
                    new Guid("{F556AB6B-9E51-43E2-99C9-4A4E551A4BEF}"),
                    "NameKeyBool",
                    "DescriptionKeyBool",
                    "GroupKey");

                BooleanFieldInfo boolFieldInfoDefaultTrue = new BooleanFieldInfo(
                    "TestInternalNameBoolTrue",
                    new Guid("{0D0289AD-C5FB-495B-96C6-48CC46737D08}"),
                    "NameKeyBoolTrue",
                    "DescriptionKeyBoolTrue",
                    "GroupKey")
                {
                    DefaultValue = true
                };

                BooleanFieldInfo boolFieldInfoDefaultFalse = new BooleanFieldInfo(
                    "TestInternalNameBoolFalse",
                    new Guid("{628181BD-9B0B-4B7E-934F-1CF1796EA4E4}"),
                    "NameKeyBoolFalse",
                    "DescriptionKeyBoolFalse",
                    "GroupKey")
                {
                    DefaultValue = false
                };

                DateTimeFieldInfo dateTimeFieldInfoFormula = new DateTimeFieldInfo(
                    "TestInternalNameDateFormula",
                    new Guid("{D23EAD73-9E18-46DB-A426-41B2D47F696C}"),
                    "NameKeyDateTimeFormula",
                    "DescriptionKeyDateTimeFormula",
                    "GroupKey")
                {
                    DefaultFormula = "=[Today]"
                };

                DateTimeFieldInfo dateTimeFieldInfoDefault = new DateTimeFieldInfo(
                    "TestInternalNameDateDefault",
                    new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"),
                    "NameKeyDateTimeDefault",
                    "DescriptionKeyDateTimeDefault",
                    "GroupKey");

                TextFieldInfo textFieldInfo = new TextFieldInfo(
                    "TestInternalNameText",
                    new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey");

                NoteFieldInfo noteFieldInfo = new NoteFieldInfo(
                    "TestInternalNameNote",
                    new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"),
                    "NameKeyAlt",
                    "DescriptionKeyAlt",
                    "GroupKey");

                HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo(
                    "TestInternalNameHtml",
                    new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"),
                    "NameKeyAlt",
                    "DescriptionKeyAlt",
                    "GroupKey");

                ImageFieldInfo imageFieldInfo = new ImageFieldInfo(
                    "TestInternalNameImage",
                    new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"),
                    "NameKeyImage",
                    "DescriptionKeyImage",
                    "GroupKey");

                UrlFieldInfo urlFieldInfo = new UrlFieldInfo(
                    "TestInternalNameUrl",
                    new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"),
                    "NameKeyUrl",
                    "DescriptionKeyUrl",
                    "GroupKey");

                UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo(
                    "TestInternalNameUrlImg",
                    new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"),
                    "NameKeyUrlImg",
                    "DescriptionKeyUrlImg",
                    "GroupKey")
                {
                    Format = UrlFieldFormat.Image
                };

                LookupFieldInfo lookupFieldInfo = new LookupFieldInfo(
                    "TestInternalNameLookup",
                    new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey");

                LookupFieldInfo lookupFieldInfoAlt = new LookupFieldInfo(
                    "TestInternalNameLookupAlt",
                    new Guid("{1F05DFFA-6396-4AEF-AD23-72217206D35E}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey")
                {
                    ShowField = "ID"
                };

                LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo(
                    "TestInternalNameLookupM",
                    new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"),
                    "NameKeyMulti",
                    "DescriptionKeyMulti",
                    "GroupKey");

                var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName);
                var ensuredUser2 = testScope.SiteCollection.RootWeb.EnsureUser("OFFICE\\maxime.boissonneault");

                UserFieldInfo userFieldInfo = new UserFieldInfo(
                    "TestInternalNameUser",
                    new Guid("{5B74DD50-0D2D-4D24-95AF-0C4B8AA3F68A}"),
                    "NameKeyUser",
                    "DescriptionKeyUser",
                    "GroupKey");

                UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo(
                    "TestInternalNameUserMulti",
                    new Guid("{8C662588-D54E-4905-B232-856C2239B036}"),
                    "NameKeyUserMulti",
                    "DescriptionKeyUserMulti",
                    "GroupKey");

                MediaFieldInfo mediaFieldInfo = new MediaFieldInfo(
                    "TestInternalNameMedia",
                    new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"),
                    "NameKeyMedia",
                    "DescriptionKeyMEdia",
                    "GroupKey");

                var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); // keep Ids random because, if this test fails midway, the term
                // set will not be cleaned up and upon next test run we will
                // run into a term set and term ID conflicts.
                var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet);
                var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet);
                var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet);
                var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet);

                TaxonomySession session = new TaxonomySession(testScope.SiteCollection);
                TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore;
                Group defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection);
                TermSet newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSet.Label, testTermSet.Id);
                Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id);
                Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id);
                Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id);
                Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id);
                defaultSiteCollectionTermStore.CommitAll();

                TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo(
                    "TestInternalNameTaxo",
                    new Guid("{18CC105F-16C9-43E2-9933-37F98452C038}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey")
                {
                    TermStoreMapping = new TaxonomyContext(testTermSet)     // choices limited to all terms in test term set
                };

                TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo(
                    "TestInternalNameTaxoMulti",
                    new Guid("{2F49D362-B014-41BB-9959-1000C9A7FFA0}"),
                    "NameKeyMulti",
                    "DescriptionKey",
                    "GroupKey")
                {
                    TermStoreMapping = new TaxonomyContext(levelOneTermA)   // choices limited to children of a specific term, instead of having full term set choices
                };

                var fieldsToEnsure = new List<BaseFieldInfo>()
                    {
                        integerFieldInfo,
                        numberFieldInfo,
                        currencyFieldInfo,
                        boolFieldInfoBasic,
                        boolFieldInfoDefaultTrue,
                        boolFieldInfoDefaultFalse,
                        dateTimeFieldInfoFormula,
                        dateTimeFieldInfoDefault,
                        textFieldInfo,
                        noteFieldInfo,
                        htmlFieldInfo,
                        imageFieldInfo,
                        urlFieldInfo,
                        urlFieldInfoImage,
                        lookupFieldInfo,
                        lookupFieldInfoAlt,
                        lookupMultiFieldInfo,
                        userFieldInfo,
                        userMultiFieldInfo,
                        mediaFieldInfo,
                        taxoFieldInfo,
                        taxoMultiFieldInfo
                    };

                ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup");

                ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey")
                {
                    FieldDefinitions = fieldsToEnsure
                };

                // Note how we need to specify SPSite for injection context - ISharePointEntityBinder's implementation
                // is lifetime-scoped to InstancePerSite.
                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope(testScope.SiteCollection))
                {
                    var listHelper = injectionScope.Resolve<IListHelper>();

                    // Lookup field ListId setup
                    SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo);
                    lookupFieldInfo.ListId = lookupList.ID;
                    lookupFieldInfoAlt.ListId = lookupList.ID;
                    lookupMultiFieldInfo.ListId = lookupList.ID;

                    // Create the looked-up items
                    var lookupItem1 = lookupList.Items.Add();
                    lookupItem1["Title"] = "Test Item 1";
                    lookupItem1.Update();

                    var lookupItem2 = lookupList.Items.Add();
                    lookupItem2["Title"] = "Test Item 2";
                    lookupItem2.Update();

                    // Create the first test list
                    SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo);
                    list.EnableVersioning = true;
                    list.Update();

                    // Create item on list
                    var itemOnList = list.AddItem();

                    // Update with the field values through the SharePoint API
                    itemOnList["Title"] = "Item under test";
                    itemOnList["TestInternalNameInteger"] = 555;
                    itemOnList["TestInternalNameNumber"] = 5.5;
                    itemOnList["TestInternalNameCurrency"] = 500.95;
                    itemOnList["TestInternalNameBool"] = true;
                    itemOnList["TestInternalNameBoolTrue"] = false;
                    itemOnList["TestInternalNameBoolFalse"] = true;
                    itemOnList["TestInternalNameDateFormula"] = new DateTime(1977, 7, 7);
                    itemOnList["TestInternalNameDateDefault"] = new DateTime(1977, 7, 7);
                    itemOnList["TestInternalNameText"] = "Text value";
                    itemOnList["TestInternalNameNote"] = "Note value";
                    itemOnList["TestInternalNameHtml"] = "<p class=\"some-css-class\">HTML value</p>";
                    itemOnList["TestInternalNameImage"] = new ImageFieldValue()
                        {
                            Hyperlink = "http://github.com/GSoft-SharePoint/",
                            ImageUrl = "/_layouts/15/MyFolder/MyImage.png"
                        };
                    itemOnList["TestInternalNameUrl"] = new SPFieldUrlValue()
                        {
                            Url = "http://github.com/GSoft-SharePoint/",
                            Description = "patate!"
                        };
                    itemOnList["TestInternalNameUrlImg"] = new SPFieldUrlValue()
                        {
                            Url = "http://github.com/GSoft-SharePoint/",
                            Description = "patate!"
                        };

                    itemOnList["TestInternalNameLookup"] = new SPFieldLookupValue(1, "Test Item 1");
                    itemOnList["TestInternalNameLookupAlt"] = new SPFieldLookupValue(2, "2");
                    itemOnList["TestInternalNameLookupM"] = new SPFieldLookupValueCollection() { new SPFieldLookupValue(1, "Test Item 1"), new SPFieldLookupValue(2, "Test Item 2") };
                    itemOnList["TestInternalNameUser"] = new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name);
                    itemOnList["TestInternalNameUserMulti"] = new SPFieldUserValueCollection() 
                        {  
                            new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser1.ID, ensuredUser1.Name),
                            new SPFieldUserValue(testScope.SiteCollection.RootWeb, ensuredUser2.ID, ensuredUser2.Name)
                        };
                    itemOnList["TestInternalNameMedia"] = new MediaFieldValue()
                        {
                            Title = "Some media file title",
                            MediaSource = "/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf",
                            AutoPlay = true,
                            Loop = true,
                            PreviewImageSource = "/_layouts/15/Images/logo.png"
                        };

                    var taxonomyField = (TaxonomyField)itemOnList.Fields.GetFieldByInternalName("TestInternalNameTaxo");
                    taxonomyField.SetFieldValue(itemOnList, createdTermB);

                    var taxonomyMultiField = (TaxonomyField)itemOnList.Fields.GetFieldByInternalName("TestInternalNameTaxoMulti");
                    taxonomyMultiField.SetFieldValue(itemOnList, new[] { createdTermAA, createdTermAB });

                    itemOnList.Update();

                    var entityBinder = injectionScope.Resolve<ISharePointEntityBinder>();
                    var entityMappedFromSingleItem = new TestItemEntityWithLookups();
                    var entityMappedFromItemVersion = new TestItemEntityWithLookups();

                    // Act

                    // Map from SPListItem
                    entityBinder.ToEntity<TestItemEntityWithLookups>(entityMappedFromSingleItem, itemOnList);

                    // Map from SPListItemVersion
                    entityBinder.ToEntity<TestItemEntityWithLookups>(entityMappedFromItemVersion, itemOnList.Versions[0]);

                    // Map from DataRow/SPListItemCollection
                    var entitiesMappedFromItemCollection = entityBinder.Get<TestItemEntity>(list.Items);

                    // Assert
                    // #1 Validate straight single list item to entity mappings
                    Assert.AreEqual(555, entityMappedFromSingleItem.IntegerProperty);
                    Assert.AreEqual(5.5, entityMappedFromSingleItem.DoubleProperty);
                    Assert.AreEqual(500.95, entityMappedFromSingleItem.CurrencyProperty);
                    Assert.IsTrue(entityMappedFromSingleItem.BoolProperty.Value);
                    Assert.IsFalse(entityMappedFromSingleItem.BoolDefaultTrueProperty);
                    Assert.IsTrue(entityMappedFromSingleItem.BoolDefaultFalseProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromSingleItem.DateTimeFormulaProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromSingleItem.DateTimeProperty);
                    Assert.AreEqual("Text value", entityMappedFromSingleItem.TextProperty);
                    Assert.AreEqual("Note value", entityMappedFromSingleItem.NoteProperty);
                    Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entityMappedFromSingleItem.HtmlProperty);

                    Assert.IsNotNull(entityMappedFromSingleItem.ImageProperty);
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.ImageProperty.Hyperlink);
                    Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entityMappedFromSingleItem.ImageProperty.ImageUrl);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.UrlProperty.Url);
                    Assert.AreEqual("patate!", entityMappedFromSingleItem.UrlProperty.Description);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromSingleItem.UrlImageProperty.Url);
                    Assert.AreEqual("patate!", entityMappedFromSingleItem.UrlProperty.Description);

                    Assert.AreEqual(1, entityMappedFromSingleItem.LookupProperty.Id);
                    Assert.AreEqual("Test Item 1", entityMappedFromSingleItem.LookupProperty.Value);

                    Assert.AreEqual(2, entityMappedFromSingleItem.LookupAltProperty.Id);
                    Assert.AreEqual("2", entityMappedFromSingleItem.LookupAltProperty.Value); // ShowField/LookupField is ID

                    Assert.AreEqual(1, entityMappedFromSingleItem.LookupMultiProperty[0].Id);
                    Assert.AreEqual("Test Item 1", entityMappedFromSingleItem.LookupMultiProperty[0].Value);
                    Assert.AreEqual(2, entityMappedFromSingleItem.LookupMultiProperty[1].Id);
                    Assert.AreEqual("Test Item 2", entityMappedFromSingleItem.LookupMultiProperty[1].Value);

                    Assert.AreEqual(ensuredUser1.Name, entityMappedFromSingleItem.UserProperty.DisplayName);

                    Assert.AreEqual(ensuredUser1.Name, entityMappedFromSingleItem.UserMultiProperty[0].DisplayName);
                    Assert.AreEqual("Maxime Boissonneault", entityMappedFromSingleItem.UserMultiProperty[1].DisplayName);

                    Assert.AreEqual("Some media file title", entityMappedFromSingleItem.MediaProperty.Title);
                    Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entityMappedFromSingleItem.MediaProperty.Url);
                    Assert.IsTrue(entityMappedFromSingleItem.MediaProperty.IsAutoPlay);
                    Assert.IsTrue(entityMappedFromSingleItem.MediaProperty.IsLoop);
                    Assert.AreEqual("/_layouts/15/Images/logo.png", entityMappedFromSingleItem.MediaProperty.PreviewImageUrl);

                    Assert.AreEqual(levelOneTermB.Id, entityMappedFromSingleItem.TaxonomyProperty.Id);
                    Assert.AreEqual(levelOneTermB.Label, entityMappedFromSingleItem.TaxonomyProperty.Label);

                    Assert.AreEqual(levelTwoTermAA.Id, entityMappedFromSingleItem.TaxonomyMultiProperty[0].Id);
                    Assert.AreEqual(levelTwoTermAA.Label, entityMappedFromSingleItem.TaxonomyMultiProperty[0].Label);
                    Assert.AreEqual(levelTwoTermAB.Id, entityMappedFromSingleItem.TaxonomyMultiProperty[1].Id);
                    Assert.AreEqual(levelTwoTermAB.Label, entityMappedFromSingleItem.TaxonomyMultiProperty[1].Label);

                    // #2 Validate list item version mappings
                    Assert.AreEqual(555, entityMappedFromItemVersion.IntegerProperty);
                    Assert.AreEqual(5.5, entityMappedFromItemVersion.DoubleProperty);
                    Assert.AreEqual(500.95, entityMappedFromItemVersion.CurrencyProperty);
                    Assert.IsTrue(entityMappedFromItemVersion.BoolProperty.Value);
                    Assert.IsFalse(entityMappedFromItemVersion.BoolDefaultTrueProperty);
                    Assert.IsTrue(entityMappedFromItemVersion.BoolDefaultFalseProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromItemVersion.DateTimeFormulaProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entityMappedFromItemVersion.DateTimeProperty);
                    Assert.AreEqual("Text value", entityMappedFromItemVersion.TextProperty);
                    Assert.AreEqual("Note value", entityMappedFromItemVersion.NoteProperty);
                    Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entityMappedFromItemVersion.HtmlProperty);

                    Assert.IsNotNull(entityMappedFromItemVersion.ImageProperty);
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.ImageProperty.Hyperlink);
                    Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entityMappedFromItemVersion.ImageProperty.ImageUrl);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.UrlProperty.Url);
                    Assert.AreEqual("patate!", entityMappedFromItemVersion.UrlProperty.Description);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entityMappedFromItemVersion.UrlImageProperty.Url);
                    Assert.AreEqual("patate!", entityMappedFromItemVersion.UrlProperty.Description);

                    Assert.AreEqual(1, entityMappedFromItemVersion.LookupProperty.Id);
                    Assert.AreEqual("Test Item 1", entityMappedFromItemVersion.LookupProperty.Value);

                    Assert.AreEqual(2, entityMappedFromItemVersion.LookupAltProperty.Id);
                    Assert.AreEqual("2", entityMappedFromItemVersion.LookupAltProperty.Value); // ShowField/LookupField is ID

                    Assert.AreEqual(1, entityMappedFromItemVersion.LookupMultiProperty[0].Id);
                    Assert.AreEqual("Test Item 1", entityMappedFromItemVersion.LookupMultiProperty[0].Value);
                    Assert.AreEqual(2, entityMappedFromItemVersion.LookupMultiProperty[1].Id);
                    Assert.AreEqual("Test Item 2", entityMappedFromItemVersion.LookupMultiProperty[1].Value);

                    Assert.AreEqual(ensuredUser1.Name, entityMappedFromItemVersion.UserProperty.DisplayName);

                    Assert.AreEqual(ensuredUser1.Name, entityMappedFromItemVersion.UserMultiProperty[0].DisplayName);
                    Assert.AreEqual("Maxime Boissonneault", entityMappedFromItemVersion.UserMultiProperty[1].DisplayName);

                    Assert.AreEqual("Some media file title", entityMappedFromItemVersion.MediaProperty.Title);
                    Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entityMappedFromItemVersion.MediaProperty.Url);
                    Assert.IsTrue(entityMappedFromItemVersion.MediaProperty.IsAutoPlay);
                    Assert.IsTrue(entityMappedFromItemVersion.MediaProperty.IsLoop);
                    Assert.AreEqual("/_layouts/15/Images/logo.png", entityMappedFromItemVersion.MediaProperty.PreviewImageUrl);

                    Assert.AreEqual(levelOneTermB.Id, entityMappedFromItemVersion.TaxonomyProperty.Id);
                    Assert.AreEqual(levelOneTermB.Label, entityMappedFromItemVersion.TaxonomyProperty.Label);

                    Assert.AreEqual(levelTwoTermAA.Id, entityMappedFromItemVersion.TaxonomyMultiProperty[0].Id);
                    Assert.AreEqual(levelTwoTermAA.Label, entityMappedFromItemVersion.TaxonomyMultiProperty[0].Label);
                    Assert.AreEqual(levelTwoTermAB.Id, entityMappedFromItemVersion.TaxonomyMultiProperty[1].Id);
                    Assert.AreEqual(levelTwoTermAB.Label, entityMappedFromItemVersion.TaxonomyMultiProperty[1].Label);

                    // #3 Validate straight list item collection to entity mappings
                    Assert.AreEqual(555, entitiesMappedFromItemCollection[0].IntegerProperty);
                    Assert.AreEqual(5.5, entitiesMappedFromItemCollection[0].DoubleProperty);
                    Assert.AreEqual(500.95, entitiesMappedFromItemCollection[0].CurrencyProperty);
                    Assert.IsTrue(entitiesMappedFromItemCollection[0].BoolProperty.Value);
                    Assert.IsFalse(entitiesMappedFromItemCollection[0].BoolDefaultTrueProperty);
                    Assert.IsTrue(entitiesMappedFromItemCollection[0].BoolDefaultFalseProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entitiesMappedFromItemCollection[0].DateTimeFormulaProperty);
                    Assert.AreEqual(new DateTime(1977, 7, 7), entitiesMappedFromItemCollection[0].DateTimeProperty);
                    Assert.AreEqual("Text value", entitiesMappedFromItemCollection[0].TextProperty);
                    Assert.AreEqual("Note value", entitiesMappedFromItemCollection[0].NoteProperty);
                    Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", entitiesMappedFromItemCollection[0].HtmlProperty);

                    Assert.IsNotNull(entitiesMappedFromItemCollection[0].ImageProperty);
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].ImageProperty.Hyperlink);
                    Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", entitiesMappedFromItemCollection[0].ImageProperty.ImageUrl);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].UrlProperty.Url);
                    Assert.AreEqual("patate!", entitiesMappedFromItemCollection[0].UrlProperty.Description);

                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", entitiesMappedFromItemCollection[0].UrlImageProperty.Url);
                    Assert.AreEqual("patate!", entitiesMappedFromItemCollection[0].UrlImageProperty.Description);

                    // No lookups or User fields because DataRow formatting screws up lookup values (we lose the lookup IDs)
                    Assert.AreEqual("Some media file title", entitiesMappedFromItemCollection[0].MediaProperty.Title);
                    Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), entitiesMappedFromItemCollection[0].MediaProperty.Url);
                    Assert.IsTrue(entitiesMappedFromItemCollection[0].MediaProperty.IsAutoPlay);
                    Assert.IsTrue(entitiesMappedFromItemCollection[0].MediaProperty.IsLoop);
                    Assert.AreEqual("/_layouts/15/Images/logo.png", entitiesMappedFromItemCollection[0].MediaProperty.PreviewImageUrl);

                    Assert.AreEqual(levelOneTermB.Id, entitiesMappedFromItemCollection[0].TaxonomyProperty.Id);
                    Assert.AreEqual(levelOneTermB.Label, entitiesMappedFromItemCollection[0].TaxonomyProperty.Label);

                    Assert.AreEqual(levelTwoTermAA.Id, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[0].Id);
                    Assert.AreEqual(levelTwoTermAA.Label, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[0].Label);
                    Assert.AreEqual(levelTwoTermAB.Id, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[1].Id);
                    Assert.AreEqual(levelTwoTermAB.Label, entitiesMappedFromItemCollection[0].TaxonomyMultiProperty[1].Label);
                }

                // Cleanup term set so that we don't pollute the metadata store
                newTermSet.Delete();
                defaultSiteCollectionTermStore.CommitAll();
            }
        }
Пример #48
0
        public static string GetEmailFromFieldValue(SPListItem item, string fieldId)
        {
            string emails = string.Empty;
            try
            {

                if (item[new Guid(fieldId)] != null)
                {
                    var field = item.ParentList.Fields[new Guid(fieldId)];

                    if (field.Type == SPFieldType.User)
                    {
                        SPFieldUserValueCollection userValues = new SPFieldUserValueCollection(item.Web.Site.RootWeb, item[new Guid(fieldId)].ToString());
                        foreach (SPFieldUserValue userValue in userValues)
                        {
                            if (userValue.User == null)
                            {
                                SPGroup group = item.Web.Site.RootWeb.SiteGroups.GetByID(userValue.LookupId);
                                foreach (SPUser user in group.Users)
                                {
                                    if (!string.IsNullOrEmpty(user.Email))
                                        emails += userValue.User.Email + ";";
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(userValue.User.Email))
                                    emails += userValue.User.Email + ";";
                            }
                        }
                    }
                    else if (field.TypeAsString == "LookupFieldWithPicker")
                    {
                        SPWeb rootWeb = item.ParentList.ParentWeb.Site.RootWeb;
                        SPFieldLookupValueCollection attendees = (SPFieldLookupValueCollection)item[new Guid(fieldId)];

                        if (attendees != null && attendees.Count > 0)
                        {
                            foreach (var attendee in attendees)
                            {
                                //Employee employee = EmployeeService.GetEmployeeByItemId(attendee.LookupId, rootWeb);
                                //emails += employee.UserEmail + ";";
                            }
                        }
                    }

                }
                emails.Trim(';');
            }
            catch { }
            return emails;
        }
        /// <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;
            }
        }
Пример #50
0
        public TaskItem(SPListItem item)
            : base(item)
        {
            try
            {
                ContentTypeId = item.ContentTypeId.ToString();

                int currentUser = SPContext.Current.Web.CurrentUser.ID;
                SPWeb web = SPContext.Current.Web;
                //Task Manager
                IsTaskManager = false;
                if (!string.IsNullOrEmpty(TaskManagerUser))
                {
                    SPFieldUserValue taskManager = new SPFieldUserValue(web, TaskManagerUser);
                    if (currentUser == taskManager.User.ID)
                        IsTaskManager = true;
                }
                //Task Supervisor
                IsTaskSupervisor = false;
                if (!string.IsNullOrEmpty(TaskSupervisorUsers))
                {
                    SPFieldUserValueCollection taskSupervisors = new SPFieldUserValueCollection(web, TaskSupervisorUsers);
                    if (taskSupervisors != null && taskSupervisors.Count > 0)
                    {
                        foreach (var taskSupervisor in taskSupervisors)
                        {
                            if (currentUser == taskSupervisor.User.ID)
                            {
                                IsTaskSupervisor = true;
                                break;
                            }
                        }
                    }
                }
                //Task Owner
                IsTaskOwner = false;
                var assignedTo = item[SPBuiltInFieldId.AssignedTo];
                if (assignedTo != null && !string.IsNullOrEmpty(assignedTo.ToString()))
                {
                    SPFieldUserValueCollection taskOwners = new SPFieldUserValueCollection(web, assignedTo.ToString());
                    if (taskOwners != null && taskOwners.Count > 0)
                    {
                        foreach (var taskOwner in taskOwners)
                        {
                            if (currentUser == taskOwner.User.ID)
                            {
                                IsTaskOwner = true;
                                break;
                            }
                        }
                    }
                }
                //Task Approve
                IsTaskApprove = false;
                if (this.ApprovalStatus == Constants.APPROVED)
                {
                    IsTaskApprove = true;
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }
 public static IEnumerable<SPUser> GetSPUsers(SPListItem listItem, string key)
 {
     object obj = null;
     try
     {
         obj = listItem[key];
     }
     catch (Exception)
     {
         var index = -1;
         switch (key)
         {
             case "Author":
                 index = GetFieldIndex(listItem, key);
                 obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Author               
                 break;
             case "Editor":
                 index = GetFieldIndex(listItem, key);
                 obj = listItem[index]; //Ошибка шарепоинта - иногда не ищет поле Editor               
                 break;
         }
     }
     if (obj == null)
         return null;
     try
     {
         var value = new SPFieldUserValueCollection(listItem.Web, obj.ToString());
         return value.Select(item => item.User);
     }
     catch (Exception)
     {
         return null;
     }
 }
Пример #52
0
 public static string GetValueAsString(this SPListItem item, string fieldname)
 {
     if (item[fieldname] == null || string.IsNullOrEmpty(item[fieldname].ToString()))
         return null;
     SPField field = item.Fields[fieldname];
     string ReturnValue;
     switch (field.Type)
     {
         case SPFieldType.Lookup:
             if (((SPFieldLookup)field).AllowMultipleValues == false)
             {
                 SPFieldLookupValue lookup = new SPFieldLookupValue(item[fieldname].ToString());
                 ReturnValue = lookup.LookupValue;
             }
             else
             {
                 SPFieldLookupValueCollection lookup = new SPFieldLookupValueCollection(item[fieldname].ToString());
                 ReturnValue = lookup[0].LookupValue;
             }
             break;
         case SPFieldType.User:
             if (((SPFieldUser)field).AllowMultipleValues == false)
             {
                 SPFieldUserValue users = new SPFieldUserValue(item.Web, item[fieldname].ToString());
                 ReturnValue = users.User.Name;
             }
             else
             {
                 SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, item[fieldname].ToString());
                 ReturnValue = users[0].User.Name;
             }
             break;
         default:
             ReturnValue = item[fieldname].ToString().Trim();
             break;
     }
     return ReturnValue;
 }
        public void AnalyzeSLAInformation()
        {
            this.ApproveMessageError ="Start Trace ";
            List<DataApprove> dataapproveList = new List<DataApprove>();
            List<DataPublishPage> dataPublishPageList = new List<DataPublishPage>();
            List<DataPublishPage> ResultdataPublishPageList = new List<DataPublishPage>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(this.siteID))
                {
                    using (SPWeb web = site.OpenWeb(this.webID))
                    {
                        if (web.Lists.TryGetList(this.approveList) != null && web.Lists.TryGetList(this.listName) != null)
                        {
                            SPList PublicPageList = web.Lists[this.listName];
                            SPQuery pageListQuery = new SPQuery();
                            pageListQuery.Query = "<Where><And><Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>Approved</Value></Eq><Gt><FieldRef Name='SLA' /><Value IncludeTimeValue='FALSE' Type='DateTime'><Today /></Value></Gt></And></Where>";
                            pageListQuery.Folder = PublicPageList.RootFolder.SubFolders["Policies"];
                            SPListItemCollection pagesCollection = PublicPageList.GetItems(pageListQuery);
                            foreach (SPListItem pageItem in pagesCollection)
                            {
                                string tempversion = string.Empty;
                                string tempcategory = string.Empty;
                                SPFieldUserValueCollection localSharePointGroup = null;
                                SPFieldUserValueCollection localPolicySupervisor = null;
                                if (pageItem.Fields.ContainsField(constants.columns.PageList.Version) && pageItem[constants.columns.PageList.Version] != null)
                                    tempversion = pageItem[constants.columns.PageList.Version].ToString();
                                if (pageItem.Fields.ContainsField(constants.columns.PageList.PageCategory) && pageItem[constants.columns.PageList.PageCategory] != null)
                                    tempcategory = pageItem[constants.columns.PageList.PageCategory].ToString();
                                if (pageItem[constants.columns.PageList.ApprovalGroup] != null && pageItem[constants.columns.PageList.PolicySupervisor] != null)
                                {
                                    localSharePointGroup = new SPFieldUserValueCollection(pageItem.Web, pageItem[constants.columns.PageList.ApprovalGroup].ToString());
                                    localPolicySupervisor = new SPFieldUserValueCollection(pageItem.Web, pageItem[constants.columns.PageList.PolicySupervisor].ToString());
                                    if (localSharePointGroup[0].User == null)
                                    {
                                        this.ApproveMessageError += "Send in Group";
                                        if (web.Groups.GetByID(localSharePointGroup[0].LookupId) != null)
                                        {
                                            SPList apporoveList = web.Lists[this.approveList];
                                            SPQuery listQuery = new SPQuery();
                                            listQuery.Query = string.Format("<Where><And><Eq><FieldRef Name='Policy_x0020_Page_x0020_ID' /><Value Type='Text'>{0}</Value></Eq><Eq><FieldRef Name='_UIVersionString' /><Value Type='Text'>{1}</Value></Eq></And></Where>", pageItem.ID.ToString(), pageItem[constants.columns.PageList.Version].ToString());

                                            SPListItemCollection cgenericCollection = apporoveList.GetItems(listQuery);
                                            if (cgenericCollection.Count == 0)
                                            {
                                                string allnames = GetAllNamesinGroup(this.siteID, this.webID, localSharePointGroup[0].LookupId);
                                                if (!string.IsNullOrEmpty(allnames))
                                                {
                                                    EmailControl emailControl = new EmailControl();
                                                    string bodyh = string.Format("User {0} has not acknowledged the policy: {1} by the due date", allnames, pageItem.Title);
                                                    this.ApproveMessageError += " Before sddn email suvervisor: " + localPolicySupervisor[0].User.Email;
                                                    emailControl.SendEmialInternal(this.siteID, site.Zone, this.webID, localPolicySupervisor[0].User.Email, bodyh, "Pending policy");
                                                }
                                            }
                                            else
                                            {
                                                List<SPUser> usersisgroup = GetUsersInGroup(this.siteID, this.webID, localSharePointGroup[0].LookupId);
                                                List<string> readyUserList = new List<string>();
                                                string NamesNotapprov = string.Empty;
                                                foreach (SPListItem approveItem in cgenericCollection)
                                                {
                                                    SPFieldUserValue userValue = new SPFieldUserValue(web, approveItem["Created By"].ToString());
                                                    readyUserList.Add(userValue.User.LoginName);
                                                }

                                                foreach (SPUser cuser in usersisgroup)
                                                {
                                                    if (readyUserList.IndexOf(cuser.LoginName) == -1)
                                                    {
                                                        if (string.IsNullOrEmpty(NamesNotapprov))
                                                        {
                                                            NamesNotapprov = cuser.Name;
                                                        }
                                                        else
                                                        {
                                                            NamesNotapprov += string.Format(" ,{0}", cuser.Name);
                                                        }
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(NamesNotapprov))
                                                {
                                                    EmailControl emailControl = new EmailControl();
                                                    string bodyh = string.Format("User {0} has not acknowledged the policy: {1} by the due date", NamesNotapprov, pageItem.Title);
                                                    this.ApproveMessageError += " Before sddn email suvervisor: " + localPolicySupervisor[0].User.Email;
                                                    emailControl.SendEmialInternal(this.siteID, site.Zone, this.webID, localPolicySupervisor[0].User.Email, bodyh, "Pending policy");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //No send individual
                                    }
                                }
                            }
                        }
                        else
                        {
                            //This list doesn't exist
                            this.ApproveMessageError = "The list doesn't exist";
                        }
                    }
                }
            });
        }
        public string GetEmailByPage(string pageid)
        {
            string result = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(this.siteID))
                {
                    using (SPWeb web = site.OpenWeb(this.webID))
                    {
                        if (web.Lists.TryGetList(this.listName) != null)
                        {
                            SPList PageList = web.Lists[this.listName];

                            SPListItem PageItem = PageList.GetItemById(int.Parse(pageid));
                            SPFieldUserValueCollection localSharePointGroup = null;
                            if (PageItem[constants.columns.PageList.ApprovalGroup] != null)
                            {
                                localSharePointGroup = new SPFieldUserValueCollection(((SPListItem)PageItem).Web, PageItem[constants.columns.PageList.ApprovalGroup].ToString());
                                if (localSharePointGroup[0].User == null)
                                {
                                    //is group
                                    result = GetEmailsFromGroup(SPContext.Current.Site.ID,
                                                                SPContext.Current.Web.ID,
                                                                localSharePointGroup[0].LookupId,
                                                                SPContext.Current.Web.CurrentUser);
                                }
                            }
                            else
                            {
                                //This list doesn't exist
                                this.ApproveMessageError = "The list doesn't exist";
                            }
                        }
                    }
                }
            });
            return result;
        }
Пример #55
0
        protected void SaveToApprovers(string currentStepApproversField, string approvedSPFieldUserValueCollField)
        {
            var rootweb = SPContext.Current.Site.RootWeb;
            var web = SPContext.Current.Web;
            //var item = SPContext.Current.ListItem;
            var fields = WorkflowContext.Current.DataFields;
            var curUser = web.CurrentUser;

            //审批过该条单子的人集合
            var approverList = new List<string>();
            var userValueColl = fields[approvedSPFieldUserValueCollField] as SPFieldUserValueCollection;
            if (userValueColl == null)
            {
                userValueColl = new SPFieldUserValueCollection();
            }

            //新步骤的审批人
            var currentStepApprovers = fields[currentStepApproversField].AsString();

            //加上新步骤的审批人
            if (!string.IsNullOrEmpty(currentStepApprovers))
            {
                foreach (var currentStepApprover in currentStepApprovers.Split(';'))
                {
                    if (!string.IsNullOrEmpty(currentStepApprover) && !approverList.Contains(currentStepApprover))
                    {
                        try
                        {
                            var spUser = web.AllUsers[currentStepApprover];
                            approverList.Add(currentStepApprover);
                            userValueColl.Add(new SPFieldUserValue(rootweb, spUser.ID, spUser.Name));
                        }
                        catch (Microsoft.SharePoint.SPException)
                        { }
                    }
                }

            }

            //加上当前审批者(当前审批者是某个审批人的代理的场合)
            if (!approverList.Contains(curUser.LoginName))
            {
                try
                {
                    approverList.Add(curUser.LoginName);
                    userValueColl.Add(new SPFieldUserValue(rootweb, curUser.ID, curUser.Name));
                }
                catch (Microsoft.SharePoint.SPException)
                { }
            }

            fields[approvedSPFieldUserValueCollField] = userValueColl;
        }
Пример #56
0
        public EmailListItem(SPListItem item)
            : base(item)
        {
            try
            {
                string userEmails = string.Empty;
                bool breakLoop = false;

                if (item["Users"] != null && !string.IsNullOrEmpty(item["Users"].ToString()))
                {
                    SPFieldUserValueCollection userValues = new SPFieldUserValueCollection(item.Web.Site.RootWeb, item["Users"].ToString());
                    foreach (SPFieldUserValue userValue in userValues)
                    {
                        if (userValue.User == null)
                        {
                            SPGroup group = item.Web.Site.RootWeb.SiteGroups.GetByID(userValue.LookupId);
                            foreach (SPUser user in group.Users)
                            {
                                if (user.LoginName == "NT AUTHORITY\\authenticated users")
                                {
                                    userEmails = string.Empty;
                                    foreach (SPUser siteUser in item.Web.Site.RootWeb.SiteUsers)
                                    {
                                        if (!string.IsNullOrEmpty(siteUser.Email))
                                            userEmails += siteUser.Email + ",";
                                    }

                                    breakLoop = true;
                                    break;
                                }

                                if (!string.IsNullOrEmpty(user.Email))
                                {
                                    userEmails += user.Email + ",";
                                }

                            }

                            if (breakLoop) break;
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(userValue.User.Email))
                                userEmails += userValue.User.Email + ",";
                        }
                    }

                    UserEmails = userEmails.Trim(',');
                }

                if (Emails == null) Emails = string.Empty;

                List<string> listEmails = Emails.Split(new string[] { ", "}, StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> listUserEmails = userEmails.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries).ToList();
                List<string> listAllEmails = listEmails.Union(listUserEmails).ToList();

                AllEmails = string.Join(",", listAllEmails.ToArray());
            }
            catch (Exception ex)
            {
            }
        }
Пример #57
0
        /// <summary>
        /// Gets User of People Picker field (Multi )
        /// </summary>
        /// <param name="item">Current item</param>
        /// <param name="fieldName">Field Name</param>
        /// <returns>Return SPUserCollection</returns>
        public static SPFieldUserValueCollection GetUserValueCollectionByField(SPListItem item, string fieldName)
        {
            var value = Convert.ToString(item[fieldName], CultureInfo.InvariantCulture);

            if (string.IsNullOrEmpty(value)) return null;

            var userFieldValueCollection = new SPFieldUserValueCollection(item.Web, value);
            if (userFieldValueCollection.Count > 0)
            {
                return userFieldValueCollection;
            }

            return null;
        }
        public void FromEntity_WhenMappingToNewListItem_ShouldInitializeListItemFieldValues()
        {
            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                IntegerFieldInfo integerFieldInfo = new IntegerFieldInfo(
                    "TestInternalNameInteger",
                    new Guid("{12E262D0-C7C4-4671-A266-064CDBD3905A}"),
                    "NameKeyInt",
                    "DescriptionKeyInt",
                    "GroupKey");

                NumberFieldInfo numberFieldInfo = new NumberFieldInfo(
                    "TestInternalNameNumber",
                    new Guid("{5DD4EE0F-8498-4033-97D0-317A24988786}"),
                    "NameKeyNumber",
                    "DescriptionKeyNumber",
                    "GroupKey");

                CurrencyFieldInfo currencyFieldInfo = new CurrencyFieldInfo(
                    "TestInternalNameCurrency",
                    new Guid("{9E9963F6-1EE6-46FB-9599-783BBF4D6249}"),
                    "NameKeyCurrency",
                    "DescriptionKeyCurrency",
                    "GroupKey");

                BooleanFieldInfo boolFieldInfoBasic = new BooleanFieldInfo(
                    "TestInternalNameBool",
                    new Guid("{F556AB6B-9E51-43E2-99C9-4A4E551A4BEF}"),
                    "NameKeyBool",
                    "DescriptionKeyBool",
                    "GroupKey");

                BooleanFieldInfo boolFieldInfoDefaultTrue = new BooleanFieldInfo(
                    "TestInternalNameBoolTrue",
                    new Guid("{0D0289AD-C5FB-495B-96C6-48CC46737D08}"),
                    "NameKeyBoolTrue",
                    "DescriptionKeyBoolTrue",
                    "GroupKey")
                {
                    DefaultValue = true
                };

                BooleanFieldInfo boolFieldInfoDefaultFalse = new BooleanFieldInfo(
                    "TestInternalNameBoolFalse",
                    new Guid("{628181BD-9B0B-4B7E-934F-1CF1796EA4E4}"),
                    "NameKeyBoolFalse",
                    "DescriptionKeyBoolFalse",
                    "GroupKey")
                {
                    DefaultValue = false
                };

                DateTimeFieldInfo dateTimeFieldInfoFormula = new DateTimeFieldInfo(
                    "TestInternalNameDateFormula",
                    new Guid("{D23EAD73-9E18-46DB-A426-41B2D47F696C}"),
                    "NameKeyDateTimeFormula",
                    "DescriptionKeyDateTimeFormula",
                    "GroupKey")
                {
                    DefaultFormula = "=[Today]"
                };

                DateTimeFieldInfo dateTimeFieldInfo = new DateTimeFieldInfo(
                    "TestInternalNameDateDefault",
                    new Guid("{016BF8D9-CEDC-4BF4-BA21-AC6A8F174AD5}"),
                    "NameKeyDateTimeDefault",
                    "DescriptionKeyDateTimeDefault",
                    "GroupKey");

                TextFieldInfo textFieldInfo = new TextFieldInfo(
                    "TestInternalNameText",
                    new Guid("{0C58B4A1-B360-47FE-84F7-4D8F58AE80F6}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey");

                NoteFieldInfo noteFieldInfo = new NoteFieldInfo(
                    "TestInternalNameNote",
                    new Guid("{E315BB24-19C3-4F2E-AABC-9DE5EFC3D5C2}"),
                    "NameKeyAlt",
                    "DescriptionKeyAlt",
                    "GroupKey");

                HtmlFieldInfo htmlFieldInfo = new HtmlFieldInfo(
                    "TestInternalNameHtml",
                    new Guid("{D16958E7-CF9A-4C38-A8BB-99FC03BFD913}"),
                    "NameKeyAlt",
                    "DescriptionKeyAlt",
                    "GroupKey");

                ImageFieldInfo imageFieldInfo = new ImageFieldInfo(
                    "TestInternalNameImage",
                    new Guid("{6C5B9E77-B621-43AA-BFBF-B333093EFCAE}"),
                    "NameKeyImage",
                    "DescriptionKeyImage",
                    "GroupKey");

                UrlFieldInfo urlFieldInfo = new UrlFieldInfo(
                    "TestInternalNameUrl",
                    new Guid("{208F904C-5A1C-4E22-9A79-70B294FABFDA}"),
                    "NameKeyUrl",
                    "DescriptionKeyUrl",
                    "GroupKey");

                UrlFieldInfo urlFieldInfoImage = new UrlFieldInfo(
                    "TestInternalNameUrlImg",
                    new Guid("{96D22CFF-5B40-4675-B632-28567792E11B}"),
                    "NameKeyUrlImg",
                    "DescriptionKeyUrlImg",
                    "GroupKey")
                {
                    Format = UrlFieldFormat.Image
                };

                LookupFieldInfo lookupFieldInfo = new LookupFieldInfo(
                    "TestInternalNameLookup",
                    new Guid("{62F8127C-4A8C-4217-8BD8-C6712753AFCE}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey");

                LookupFieldInfo lookupFieldInfoAlt = new LookupFieldInfo(
                    "TestInternalNameLookupAlt",
                    new Guid("{1F05DFFA-6396-4AEF-AD23-72217206D35E}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey")
                {
                    ShowField = "ID"
                };

                LookupMultiFieldInfo lookupMultiFieldInfo = new LookupMultiFieldInfo(
                    "TestInternalNameLookupM",
                    new Guid("{2C9D4C0E-21EB-4742-8C6C-4C30DCD08A05}"),
                    "NameKeyMulti",
                    "DescriptionKeyMulti",
                    "GroupKey");

                var ensuredUser1 = testScope.SiteCollection.RootWeb.EnsureUser(Environment.UserDomainName + "\\" + Environment.UserName);
                var ensuredUser2 = testScope.SiteCollection.RootWeb.EnsureUser("OFFICE\\maxime.boissonneault");

                UserFieldInfo userFieldInfo = new UserFieldInfo(
                    "TestInternalNameUser",
                    new Guid("{5B74DD50-0D2D-4D24-95AF-0C4B8AA3F68A}"),
                    "NameKeyUser",
                    "DescriptionKeyUser",
                    "GroupKey");

                UserMultiFieldInfo userMultiFieldInfo = new UserMultiFieldInfo(
                    "TestInternalNameUserMulti",
                    new Guid("{8C662588-D54E-4905-B232-856C2239B036}"),
                    "NameKeyUserMulti",
                    "DescriptionKeyUserMulti",
                    "GroupKey");

                MediaFieldInfo mediaFieldInfo = new MediaFieldInfo(
                    "TestInternalNameMedia",
                    new Guid("{A2F070FE-FE33-44FC-9FDF-D18E74ED4D67}"),
                    "NameKeyMedia",
                    "DescriptionKeyMEdia",
                    "GroupKey");

                var testTermSet = new TermSetInfo(Guid.NewGuid(), "Test Term Set"); // keep Ids random because, if this test fails midway, the term
                // set will not be cleaned up and upon next test run we will
                // run into a term set and term ID conflicts.
                var levelOneTermA = new TermInfo(Guid.NewGuid(), "Term A", testTermSet);
                var levelOneTermB = new TermInfo(Guid.NewGuid(), "Term B", testTermSet);
                var levelTwoTermAA = new TermInfo(Guid.NewGuid(), "Term A-A", testTermSet);
                var levelTwoTermAB = new TermInfo(Guid.NewGuid(), "Term A-B", testTermSet);

                TaxonomySession session = new TaxonomySession(testScope.SiteCollection);
                TermStore defaultSiteCollectionTermStore = session.DefaultSiteCollectionTermStore;
                Group defaultSiteCollectionGroup = defaultSiteCollectionTermStore.GetSiteCollectionGroup(testScope.SiteCollection);
                TermSet newTermSet = defaultSiteCollectionGroup.CreateTermSet(testTermSet.Label, testTermSet.Id);
                Term createdTermA = newTermSet.CreateTerm(levelOneTermA.Label, Language.English.Culture.LCID, levelOneTermA.Id);
                Term createdTermB = newTermSet.CreateTerm(levelOneTermB.Label, Language.English.Culture.LCID, levelOneTermB.Id);
                Term createdTermAA = createdTermA.CreateTerm(levelTwoTermAA.Label, Language.English.Culture.LCID, levelTwoTermAA.Id);
                Term createdTermAB = createdTermA.CreateTerm(levelTwoTermAB.Label, Language.English.Culture.LCID, levelTwoTermAB.Id);
                defaultSiteCollectionTermStore.CommitAll();

                TaxonomyFieldInfo taxoFieldInfo = new TaxonomyFieldInfo(
                    "TestInternalNameTaxo",
                    new Guid("{18CC105F-16C9-43E2-9933-37F98452C038}"),
                    "NameKey",
                    "DescriptionKey",
                    "GroupKey")
                {
                    TermStoreMapping = new TaxonomyContext(testTermSet)     // choices limited to all terms in test term set
                };

                TaxonomyMultiFieldInfo taxoMultiFieldInfo = new TaxonomyMultiFieldInfo(
                    "TestInternalNameTaxoMulti",
                    new Guid("{2F49D362-B014-41BB-9959-1000C9A7FFA0}"),
                    "NameKeyMulti",
                    "DescriptionKey",
                    "GroupKey")
                {
                    TermStoreMapping = new TaxonomyContext(levelOneTermA)   // choices limited to children of a specific term, instead of having full term set choices
                };

                var fieldsToEnsure = new List<BaseFieldInfo>()
                    {
                        integerFieldInfo,
                        numberFieldInfo,
                        currencyFieldInfo,
                        boolFieldInfoBasic,
                        boolFieldInfoDefaultTrue,
                        boolFieldInfoDefaultFalse,
                        dateTimeFieldInfoFormula,
                        dateTimeFieldInfo,
                        textFieldInfo,
                        noteFieldInfo,
                        htmlFieldInfo,
                        imageFieldInfo,
                        urlFieldInfo,
                        urlFieldInfoImage,
                        lookupFieldInfo,
                        lookupFieldInfoAlt,
                        lookupMultiFieldInfo,
                        userFieldInfo,
                        userMultiFieldInfo,
                        mediaFieldInfo,
                        taxoFieldInfo,
                        taxoMultiFieldInfo
                    };

                ListInfo lookupListInfo = new ListInfo("sometestlistpathlookup", "DynamiteTestListNameKeyLookup", "DynamiteTestListDescriptionKeyLookup");

                ListInfo listInfo = new ListInfo("sometestlistpath", "DynamiteTestListNameKey", "DynamiteTestListDescriptionKey")
                {
                    FieldDefinitions = fieldsToEnsure
                };

                // Note how we need to specify SPSite for injection context - ISharePointEntityBinder's implementation
                // is lifetime-scoped to InstancePerSite.
                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope(testScope.SiteCollection))
                {
                    var listHelper = injectionScope.Resolve<IListHelper>();

                    // Lookup field ListId setup
                    SPList lookupList = listHelper.EnsureList(testScope.SiteCollection.RootWeb, lookupListInfo);
                    lookupFieldInfo.ListId = lookupList.ID;
                    lookupFieldInfoAlt.ListId = lookupList.ID;
                    lookupMultiFieldInfo.ListId = lookupList.ID;

                    // Create the looked-up items
                    var lookupItem1 = lookupList.Items.Add();
                    lookupItem1["Title"] = "Test Item 1";
                    lookupItem1.Update();

                    var lookupItem2 = lookupList.Items.Add();
                    lookupItem2["Title"] = "Test Item 2";
                    lookupItem2.Update();

                    // Create the first test list
                    SPList list = listHelper.EnsureList(testScope.SiteCollection.RootWeb, listInfo);

                    // Initialize the entity object with all the property values we want to apply on the new list item
                    var entityBinder = injectionScope.Resolve<ISharePointEntityBinder>();
                    var entity = new TestItemEntityWithLookups()
                    {
                        IntegerProperty = 555,
                        DoubleProperty = 5.5,
                        CurrencyProperty = 500.95,
                        BoolProperty = true,
                        BoolDefaultTrueProperty = false,
                        BoolDefaultFalseProperty = true,
                        DateTimeFormulaProperty = new DateTime(2005, 10, 21),
                        DateTimeProperty = new DateTime(2005, 10, 21),
                        TextProperty = "Text value",
                        NoteProperty = "Note value",
                        HtmlProperty = "<p class=\"some-css-class\">HTML value</p>",
                        ImageProperty = new ImageValue()
                        {
                            Hyperlink = "http://github.com/GSoft-SharePoint/",
                            ImageUrl = "/_layouts/15/MyFolder/MyImage.png"
                        },
                        UrlProperty = new UrlValue()
                        {
                            Url = "http://github.com/GSoft-SharePoint/",
                            Description = "patate!"
                        },
                        UrlImageProperty = new UrlValue()
                        {
                            Url = "http://github.com/GSoft-SharePoint/",
                            Description = "patate!"
                        },
                        LookupProperty = new LookupValue(1, "Test Item 1"),
                        LookupAltProperty = new LookupValue(2, "2"),
                        LookupMultiProperty = new LookupValueCollection() { new LookupValue(1, "Test Item 1"), new LookupValue(2, "Test Item 2") },
                        UserProperty = new UserValue(ensuredUser1),
                        UserMultiProperty = new UserValueCollection() { new UserValue(ensuredUser1), new UserValue(ensuredUser2) },
                        MediaProperty = new MediaValue()
                        {
                            Title = "Some media file title",
                            Url = "/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf",
                            IsAutoPlay = true,
                            IsLoop = true,
                            PreviewImageUrl = "/_layouts/15/Images/logo.png"
                        },
                        TaxonomyProperty = new TaxonomyValue(createdTermB),
                        TaxonomyMultiProperty = new TaxonomyValueCollection(
                        new List<TaxonomyValue>() 
                            { 
                                new TaxonomyValue(createdTermAA), 
                                new TaxonomyValue(createdTermAB)
                            })
                    };

                    // Act (create the list item and bind the Entity's values to it)
                    var itemOnList = list.AddItem();
                    entityBinder.FromEntity<TestItemEntityWithLookups>(entity, itemOnList);
                    itemOnList.Update();

                    // Assert
                    // #1: validate ListItem field values on the mapped item object
                    Assert.AreEqual(555, itemOnList["TestInternalNameInteger"]);
                    Assert.AreEqual(5.5, itemOnList["TestInternalNameNumber"]);
                    Assert.AreEqual(500.95, itemOnList["TestInternalNameCurrency"]);
                    Assert.IsTrue((bool)itemOnList["TestInternalNameBool"]);
                    Assert.IsFalse((bool)itemOnList["TestInternalNameBoolTrue"]);
                    Assert.IsTrue((bool)itemOnList["TestInternalNameBoolFalse"]);
                    Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList["TestInternalNameDateFormula"]);
                    Assert.AreEqual(new DateTime(2005, 10, 21), itemOnList["TestInternalNameDateDefault"]);
                    Assert.AreEqual("Text value", itemOnList["TestInternalNameText"]);
                    Assert.AreEqual("Note value", itemOnList["TestInternalNameNote"]);
                    Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", itemOnList["TestInternalNameHtml"]);

                    var imageFieldVal = (ImageFieldValue)itemOnList["TestInternalNameImage"];
                    Assert.IsNotNull(imageFieldVal);
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", imageFieldVal.Hyperlink);
                    Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", imageFieldVal.ImageUrl);

                    var urlFieldVal = new SPFieldUrlValue(itemOnList["TestInternalNameUrl"].ToString());
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlFieldVal.Url);
                    Assert.AreEqual("patate!", urlFieldVal.Description);

                    var urlImageFieldVal = new SPFieldUrlValue(itemOnList["TestInternalNameUrlImg"].ToString());
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlImageFieldVal.Url);
                    Assert.AreEqual("patate!", urlImageFieldVal.Description);

                    var lookupFieldVal = new SPFieldLookupValue(itemOnList["TestInternalNameLookup"].ToString());
                    Assert.AreEqual(1, lookupFieldVal.LookupId);
                    Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue);

                    var lookupAltFieldVal = new SPFieldLookupValue(itemOnList["TestInternalNameLookupAlt"].ToString());
                    Assert.AreEqual(2, lookupAltFieldVal.LookupId);
                    Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID

                    var lookupMultiFieldVal = new SPFieldLookupValueCollection(itemOnList["TestInternalNameLookupM"].ToString());
                    Assert.AreEqual(1, lookupMultiFieldVal[0].LookupId);
                    Assert.AreEqual("Test Item 1", lookupMultiFieldVal[0].LookupValue);
                    Assert.AreEqual(2, lookupMultiFieldVal[1].LookupId);
                    Assert.AreEqual("Test Item 2", lookupMultiFieldVal[1].LookupValue);

                    var userFieldVal = new SPFieldUserValue(testScope.SiteCollection.RootWeb, itemOnList["TestInternalNameUser"].ToString());
                    Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name);

                    // TODO: Make this work with ListItem converters
                    var userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, itemOnList["TestInternalNameUserMulti"].ToString());
                    Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name);
                    Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name);

                    var mediaFieldVal = MediaFieldValue.FromString(itemOnList["TestInternalNameMedia"].ToString());
                    Assert.AreEqual("Some media file title", mediaFieldVal.Title);
                    Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), mediaFieldVal.MediaSource);
                    Assert.IsTrue(mediaFieldVal.AutoPlay);
                    Assert.IsTrue(mediaFieldVal.Loop);
                    Assert.AreEqual("/_layouts/15/Images/logo.png", mediaFieldVal.PreviewImageSource);

                    var taxoFieldValue = (TaxonomyFieldValue)itemOnList["TestInternalNameTaxo"];
                    Assert.AreNotEqual(-1, taxoFieldValue.WssId);
                    Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid));
                    Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label);

                    var taxoFieldValueMulti = (TaxonomyFieldValueCollection)itemOnList["TestInternalNameTaxoMulti"];
                    Assert.AreNotEqual(-1, taxoFieldValueMulti[0].WssId);
                    Assert.AreEqual(levelTwoTermAA.Id, new Guid(taxoFieldValueMulti[0].TermGuid));
                    Assert.AreEqual(levelTwoTermAA.Label, taxoFieldValueMulti[0].Label);
                    Assert.AreNotEqual(-1, taxoFieldValueMulti[1].WssId);
                    Assert.AreEqual(levelTwoTermAB.Id, new Guid(taxoFieldValueMulti[1].TermGuid));
                    Assert.AreEqual(levelTwoTermAB.Label, taxoFieldValueMulti[1].Label);

                    // #2: validate ListItem field values on the re-fetched list item
                    var refetchedItemOnList = list.GetItemById(itemOnList.ID);

                    Assert.AreEqual(555, refetchedItemOnList["TestInternalNameInteger"]);
                    Assert.AreEqual(5.5, refetchedItemOnList["TestInternalNameNumber"]);
                    Assert.AreEqual(500.95, refetchedItemOnList["TestInternalNameCurrency"]);
                    Assert.IsTrue((bool)refetchedItemOnList["TestInternalNameBool"]);
                    Assert.IsFalse((bool)refetchedItemOnList["TestInternalNameBoolTrue"]);
                    Assert.IsTrue((bool)refetchedItemOnList["TestInternalNameBoolFalse"]);
                    Assert.AreEqual(new DateTime(2005, 10, 21), refetchedItemOnList["TestInternalNameDateFormula"]);
                    Assert.AreEqual(new DateTime(2005, 10, 21), refetchedItemOnList["TestInternalNameDateDefault"]);
                    Assert.AreEqual("Text value", refetchedItemOnList["TestInternalNameText"]);
                    Assert.AreEqual("Note value", refetchedItemOnList["TestInternalNameNote"]);
                    Assert.AreEqual("<p class=\"some-css-class\">HTML value</p>", refetchedItemOnList["TestInternalNameHtml"]);

                    imageFieldVal = (ImageFieldValue)refetchedItemOnList["TestInternalNameImage"];
                    Assert.IsNotNull(imageFieldVal);
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", imageFieldVal.Hyperlink);
                    Assert.AreEqual("/_layouts/15/MyFolder/MyImage.png", imageFieldVal.ImageUrl);

                    urlFieldVal = new SPFieldUrlValue(refetchedItemOnList["TestInternalNameUrl"].ToString());
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlFieldVal.Url);
                    Assert.AreEqual("patate!", urlFieldVal.Description);     // proper Url description will never be set for Format=Hyperlink

                    urlImageFieldVal = new SPFieldUrlValue(refetchedItemOnList["TestInternalNameUrlImg"].ToString());
                    Assert.AreEqual("http://github.com/GSoft-SharePoint/", urlImageFieldVal.Url);
                    Assert.AreEqual("patate!", urlImageFieldVal.Description);     // proper Url description will never be set for Format=Image either

                    lookupFieldVal = new SPFieldLookupValue(refetchedItemOnList["TestInternalNameLookup"].ToString());
                    Assert.AreEqual(1, lookupFieldVal.LookupId);
                    Assert.AreEqual("Test Item 1", lookupFieldVal.LookupValue);

                    lookupAltFieldVal = new SPFieldLookupValue(refetchedItemOnList["TestInternalNameLookupAlt"].ToString());
                    Assert.AreEqual(2, lookupAltFieldVal.LookupId);
                    Assert.AreEqual("2", lookupAltFieldVal.LookupValue); // ShowField/LookupField is ID

                    lookupMultiFieldVal = new SPFieldLookupValueCollection(refetchedItemOnList["TestInternalNameLookupM"].ToString());
                    Assert.AreEqual(1, lookupMultiFieldVal[0].LookupId);
                    Assert.AreEqual("Test Item 1", lookupMultiFieldVal[0].LookupValue);
                    Assert.AreEqual(2, lookupMultiFieldVal[1].LookupId);
                    Assert.AreEqual("Test Item 2", lookupMultiFieldVal[1].LookupValue);

                    userFieldVal = new SPFieldUserValue(testScope.SiteCollection.RootWeb, refetchedItemOnList["TestInternalNameUser"].ToString());
                    Assert.AreEqual(ensuredUser1.Name, userFieldVal.User.Name);

                    userMultiFieldVal = new SPFieldUserValueCollection(testScope.SiteCollection.RootWeb, refetchedItemOnList["TestInternalNameUserMulti"].ToString());
                    Assert.AreEqual(ensuredUser1.Name, userMultiFieldVal[0].User.Name);
                    Assert.AreEqual("Maxime Boissonneault", userMultiFieldVal[1].User.Name);

                    mediaFieldVal = MediaFieldValue.FromString(refetchedItemOnList["TestInternalNameMedia"].ToString());
                    Assert.AreEqual("Some media file title", mediaFieldVal.Title);
                    Assert.AreEqual(HttpUtility.UrlDecode("/sites/test/SiteAssets/01_01_ASP.NET%20MVC%203%20Fundamentals%20Intro%20-%20Overview.asf"), mediaFieldVal.MediaSource);
                    Assert.IsTrue(mediaFieldVal.AutoPlay);
                    Assert.IsTrue(mediaFieldVal.Loop);
                    Assert.AreEqual("/_layouts/15/Images/logo.png", mediaFieldVal.PreviewImageSource);

                    taxoFieldValue = (TaxonomyFieldValue)refetchedItemOnList["TestInternalNameTaxo"];
                    Assert.AreNotEqual(-1, taxoFieldValue.WssId);
                    Assert.AreEqual(levelOneTermB.Id, new Guid(taxoFieldValue.TermGuid));
                    Assert.AreEqual(levelOneTermB.Label, taxoFieldValue.Label);

                    taxoFieldValueMulti = (TaxonomyFieldValueCollection)refetchedItemOnList["TestInternalNameTaxoMulti"];
                    Assert.AreNotEqual(-1, taxoFieldValueMulti[0].WssId);
                    Assert.AreEqual(levelTwoTermAA.Id, new Guid(taxoFieldValueMulti[0].TermGuid));
                    Assert.AreEqual(levelTwoTermAA.Label, taxoFieldValueMulti[0].Label);
                    Assert.AreNotEqual(-1, taxoFieldValueMulti[1].WssId);
                    Assert.AreEqual(levelTwoTermAB.Id, new Guid(taxoFieldValueMulti[1].TermGuid));
                    Assert.AreEqual(levelTwoTermAB.Label, taxoFieldValueMulti[1].Label);
                }

                // Cleanup term set so that we don't pollute the metadata store
                newTermSet.Delete();
                defaultSiteCollectionTermStore.CommitAll();
            }
        }
Пример #59
0
        private void replicatorActivity1_ChildInitialized(object sender, ReplicatorChildEventArgs e)
        {
            string strApprover = (string)e.InstanceData;
            ApprovalUnit approvalActivity = (ApprovalUnit)e.Activity;
            if (ApprovalInfo.ExpendGroup)
            {

                string[] strUsers = strApprover.Split(';');
                //SPUserCollection users = new SPUserCollection(workflowProperties.Web, strUsers);
                //users.GetCollection(strApprover.Split(';'));
                SPFieldUserValueCollection readers = new SPFieldUserValueCollection(workflowProperties.Web, strApprover);

                foreach (string strUser in strUsers)
                {
                    SPGroup spApprovalGroup = workflowProperties.Web.Groups[strUser];
                    if (spApprovalGroup != null)
                    {
                        foreach (SPUser userInGroup in spApprovalGroup.Users)
                        {
                            strApprover += userInGroup.LoginName + ";";
                        }
                    }
                    else
                    {
                        strApprover += strUser + ";";
                    }
                }
            }
            else approvalActivity.Approver = strApprover;

            approvalActivity.DueDate = ApprovalInfo.DueDate;
            approvalActivity.DurationPerTask = ApprovalInfo.DurationPerTask;
            approvalActivity.Message = ApprovalInfo.Message;
            approvalActivity.TaskTitle = ApprovalInfo.TaskTitle;
        }
Пример #60
0
        public bool MatchItemValueBasedOnOperatorAndValueType(object fieldValue, Type fieldValueType, AlertEventType eventType, SPWeb web)
        {
            //SPWeb web = item.ParentList.ParentWeb;
            //string strComputedValue = GetConditionComputedValue(item);

            if (fieldValue != null && !string.IsNullOrEmpty(fieldValue.ToString()))
            {
                if (fieldValueType == (typeof(SPFieldUrlValue)))
                {
                    SPFieldUrlValue fieldUrlValue = new SPFieldUrlValue(fieldValue.ToString());
                    bool isDescMatched = CompareValuesBasedOnOperator(fieldUrlValue.Description, this.comparisionOperator, this.strValue);
                    bool isUrlMatched = CompareValuesBasedOnOperator(fieldUrlValue.Url, this.comparisionOperator, strValue);

                    return isDescMatched || isUrlMatched;
                }
                else if (fieldValueType == (typeof(SPFieldUserValue)))
                {
                    //SPFieldUserValue fieldUserValue = new SPFieldUserValue(SPContext.Current.Web, fieldValue.ToString());
                    SPFieldUserValue fieldUserValue = new SPFieldUserValue(web, fieldValue.ToString());

                    string userLoginName = fieldUserValue.User.LoginName;
                    string userDispalyName = fieldUserValue.User.Name;

                    bool isLoginMatched = CompareValuesBasedOnOperator(userLoginName, this.comparisionOperator, strValue);
                    bool isDisplayNameMatched = CompareValuesBasedOnOperator(userLoginName, this.comparisionOperator, strValue);

                    return isLoginMatched || isDisplayNameMatched;

                }
                else if (fieldValueType == (typeof(SPFieldUserValueCollection)))
                {
                    //SPFieldUserValueCollection fieldUserValueCollection = new SPFieldUserValueCollection(SPContext.Current.Web, fieldValue.ToString());
                    SPFieldUserValueCollection fieldUserValueCollection = new SPFieldUserValueCollection(web, fieldValue.ToString());
                    string userLoginNames = "";
                    string userDispalyNames = "";

                    foreach (SPFieldUserValue userValue in fieldUserValueCollection)
                    {
                        userLoginNames += userValue.LookupValue + ValueCollectionSeperator;

                        if (userValue.User != null)
                            userDispalyNames += userValue.User.Name + ValueCollectionSeperator;

                    }

                    userLoginNames = userLoginNames.TrimEnd(ValueCollectionSeperator.ToCharArray());
                    userDispalyNames = userDispalyNames.TrimEnd(ValueCollectionSeperator.ToCharArray());

                    bool isLoginMatched = CompareValuesBasedOnOperator(userLoginNames, this.comparisionOperator, strValue);
                    bool isDisplayNameMatched = CompareValuesBasedOnOperator(userLoginNames, this.comparisionOperator, strValue);

                    return isLoginMatched || isDisplayNameMatched;



                }
                else if (fieldValueType == (typeof(SPFieldLookupValue)))
                {
                    SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(fieldValue.ToString());

                    string strFieldValue = fieldLookupValue.LookupValue;
                    return CompareValuesBasedOnOperator(strFieldValue, this.comparisionOperator, strValue);
                }
                else if (fieldValueType == (typeof(SPFieldLookupValueCollection)))
                {
                    SPFieldLookupValueCollection fieldLookupValueCollection = new SPFieldLookupValueCollection(fieldValue.ToString());
                    string strFieldValue = "";

                    foreach (SPFieldLookupValue lookup in fieldLookupValueCollection)
                    {
                        strFieldValue += lookup.LookupValue + ValueCollectionSeperator;
                    }

                    strFieldValue = strFieldValue.TrimEnd(ValueCollectionSeperator.ToCharArray());
                    return CompareValuesBasedOnOperator(strFieldValue, this.comparisionOperator, strValue);
                }
                else if (fieldValueType == (typeof(DateTime)))
                {
                    DateTime sourceDT = DateTime.Parse(fieldValue.ToString());
                    DateTime targetDT = new DateTime();
                    if (DateTime.TryParse(strValue, out targetDT))
                    {
                        switch (this.comparisionOperator)
                        {

                            case Operators.Eq:
                                return sourceDT == targetDT;
                            case Operators.Neq:
                                return sourceDT != targetDT;
                            case Operators.Gt:
                                return sourceDT > targetDT;
                            case Operators.Geq:
                                return sourceDT >= targetDT;
                            case Operators.Lt:
                                return sourceDT < targetDT;
                            case Operators.Leq:
                                return sourceDT <= targetDT;
                            default:
                                return false;
                        }
                    }
                    else
                    {
                        return false;
                    }


                }
                else if (fieldValueType == (typeof(int)))
                {
                    int sourceInt = int.Parse(fieldValue.ToString());
                    int targetInt;
                    if (Int32.TryParse(strValue, out targetInt))
                    {
                        switch (this.comparisionOperator)
                        {

                            case Operators.Eq:
                                return sourceInt == targetInt;
                            case Operators.Neq:
                                return sourceInt != targetInt;
                            case Operators.Gt:
                                return sourceInt > targetInt;
                            case Operators.Geq:
                                return sourceInt >= targetInt;
                            case Operators.Lt:
                                return sourceInt < targetInt;
                            case Operators.Leq:
                                return sourceInt <= targetInt;
                            default:
                                return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (fieldValueType == (typeof(Boolean)))
                {
                    bool sourceBool = Boolean.Parse(fieldValue.ToString());
                    bool targetBool = false;

                    if (strValue.Equals("True", StringComparison.InvariantCultureIgnoreCase) || strValue.Equals("Yes", StringComparison.InvariantCultureIgnoreCase))
                    {
                        targetBool = true;
                    }
                    else if (strValue.Equals("False", StringComparison.InvariantCultureIgnoreCase) || strValue.Equals("No", StringComparison.InvariantCultureIgnoreCase))
                    {
                        targetBool = false;
                    }
                    else
                    {
                        return false;
                    }

                    switch (this.comparisionOperator)
                    {

                        case Operators.Eq:
                            return sourceBool == targetBool;
                        case Operators.Neq:
                            return sourceBool != targetBool;
                        case Operators.Contains:
                            return sourceBool == targetBool;
                        case Operators.NotContains:
                            return sourceBool != targetBool;
                        default:
                            return false;
                    }
                }
                else // default matching will be performed with string type
                {
                    string strFieldValue = fieldValue.ToString();
                    return CompareValuesBasedOnOperator(strFieldValue, this.comparisionOperator, strValue);
                }
            }
            else
            {
                return false;
            }

        }