示例#1
0
        private static void LoopThroughListItems(ClientContext ctx)
        {
            ListItemCollection list = ctx.Web.Lists.GetByTitle("Employee").GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(list);
            ctx.ExecuteQuery();

            int i = 1;

            foreach (var item in list)
            {
                FieldUserValue Username  = item["TIM_Employee"] as FieldUserValue;
                FieldUrlValue  picUrl    = item["TIM_Picture"] as FieldUrlValue;
                FieldUrlValue  LinkinUrl = item["TIM_Linkedin"] as FieldUrlValue;
                //FieldLookupValue empType = item[] as FieldLookupValue;
                //FieldLookupValue managerType = item[] as FieldLookupValue;

                Console.WriteLine("Person " + i++);
                Console.WriteLine();
                Console.WriteLine(item["Title"]);
                Console.WriteLine(Username.Email);
                Console.WriteLine(picUrl.Url);
                Console.WriteLine("descrip " + picUrl.Description);
                Console.WriteLine(LinkinUrl.Url);
                Console.WriteLine("descrip " + LinkinUrl.Description);
                Console.WriteLine(item["TIM_Age"]);
                Console.WriteLine(item["TIM_Education"]);
            }
        }
示例#2
0
        //CheckTermGroupName
        //GetDeatils
        public Advertisment GetDeatils(ClientContext context, string listTitle, int id)
        {
            Advertisment adDetails = new Advertisment();

            if (context != null)
            {
                List     list    = context.Web.Lists.GetByTitle(listTitle);
                ListItem newItem = list.GetItemById(id);
                context.Load(newItem);
                context.ExecuteQuery();

                TaxonomyFieldValue taxFieldValue = newItem["Kategorier"] as TaxonomyFieldValue;
                FieldUserValue     user          = (FieldUserValue)newItem["S_x00e4_ljare"];
                adDetails = new Advertisment
                {
                    ID           = Convert.ToInt32(newItem["ID"]),
                    ProductTitle = newItem["Title"].ToString(),
                    Description  = Convert.ToString(newItem["ubza"]),
                    Created      = Convert.ToDateTime(newItem["Created"]),
                    Price        = Convert.ToDecimal(newItem["Pris"]),
                    Category     = taxFieldValue.Label,
                    ImageUrl     = ((FieldUrlValue)(newItem["Bild"])).Url,
                    Seller       = user.Email,
                    SellerToken  = VerifyUser(user),
                };
            }

            return(adDetails);
        }
示例#3
0
        public ActionResult EditItem(int id)
        {
            ClientContext clientContext = new ClientContext(SiteUrl);
            List          spList        = clientContext.Web.Lists.GetByTitle(ListName);

            clientContext.Load(spList);
            ListItem spListItem = spList.GetItemById(id);

            clientContext.Load(spListItem);
            clientContext.ExecuteQuery();

            string         Request_ID       = (String)spListItem[FieldId];
            string         Request_Details  = (String)spListItem[FieldDetails];
            string         Request_Status   = (String)spListItem[FieldStatus];
            var            dueDate          = spListItem[FieldDueDate];
            string         Request_Due_Date = dueDate != null ? ((DateTime)dueDate).ToShortDateString() : "";
            FieldUserValue Author           = (FieldUserValue)spListItem[FieldAuthor];
            string         Request_By       = Author.LookupValue;

            ViewBag.Request_ID       = Request_ID;
            ViewBag.Request_Details  = Request_Details;
            ViewBag.Request_Status   = Request_Status;
            ViewBag.Request_Due_Date = Request_Due_Date;
            ViewBag.Request_By       = Request_By;
            ViewBag.ID = id;

            // Getting choice fields from Request Status column
            FieldChoice choiceField = clientContext.CastTo <FieldChoice>(spList.Fields.GetByInternalNameOrTitle(FieldStatus));

            clientContext.Load(choiceField);
            clientContext.ExecuteQuery();
            ViewBag.Request_Status_Choices = choiceField.Choices;

            return(View());
        }
示例#4
0
        public static List <SPTask> GetTasksFromSharePoint(ClientContext ctx)
        {
            string taskListName = "AddinTasks";
            List   list         = ctx.Web.Lists.GetByTitle("AddinTasks");

            //TODO: Make query use viewfields so its better
            ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(items);
            ctx.ExecuteQuery();

            List <SPTask> tasks = new List <SPTask>();

            foreach (ListItem item in items)
            {
                SPTask task = new SPTask();
                task.Title = item["Title"].ToString();
                if (item["DueDate"] != null)
                {
                    task.TaskDueDate = DateTime.Parse(item["DueDate"].ToString());
                }
                if (item["AssignedTo"] != null)
                {
                    FieldUserValue value = item["AssignedTo"] as FieldUserValue;
                    task.AssigedTo = value.LookupValue;
                }

                tasks.Add(task);
            }

            return(tasks);
        }
示例#5
0
        /// <summary>
        /// Gets all employee.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="web">The web.</param>
        /// <returns>
        /// List of users
        /// </returns>
        private List <EmployeeDetails> GetAllEmployeeDetails(ClientContext context, Web web)
        {
            List <EmployeeDetails> empDetaillist = new List <EmployeeDetails>();
            string             siteUrl           = GetSiteURL(SiteURLs.ITEMCODECREATIONSITEURL);//this.GetConfigVariable(SiteURLs.ROOTSITEURL);
            List               slaList           = web.Lists.GetByTitle(ListNames.APPROVERMASTERLIST);
            ListItemCollection items             = slaList.GetItems(CamlQuery.CreateAllItemsQuery());

            context.Load(items);
            context.ExecuteQuery();

            foreach (ListItem item in items)
            {
                FieldUserValue fuv = (FieldUserValue)item["UserName"];
                empDetaillist.Add(new EmployeeDetails()
                {
                    UserID   = Convert.ToString(fuv.LookupId),
                    UserName = fuv.LookupValue,
                    //Email = Convert.ToString(item["EmailAddress"]).ToLower(),
                    //Alias = Convert.ToString(item["Alias"]),
                    //EmployeeCode = Convert.ToString(item["EmployeeCode"]).ToLower(),
                    Role     = Convert.ToString(item["Role"]),
                    IsActive = Convert.ToBoolean(item["IsActive"])
                });
            }
            return(empDetaillist);
        }
示例#6
0
        public async Task CreateListItem(TalkListItem item)
        {
            ClientContext context = GetSharepointContext(item.Url);
            List          list    = context.Web.Lists.GetByTitle(item.ListName);

            context.Load(list);
            await context.ExecuteQueryAsync();

            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem newItem = list.AddItem(itemCreateInfo);

            newItem["Title"]       = item.Title;
            newItem["Description"] = item.Description;
            newItem["Number"]      = item.Number;
            newItem["Boolean"]     = item.Boolean;
            newItem["DateTime"]    = item.Datetime;
            newItem["Choice"]      = item.Choice;
            //User or group
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId     = item.UserOrGroup;
            newItem["UserOrGroup"] = userValue;
            newItem["Sevilla"]     = item.Sevilla;
            newItem.Update();
            await context.ExecuteQueryAsync();
        }
        public List <SharePointTask> GetUserTasks(string userFirstName)
        {
            var    toReturn           = new List <SharePointTask>();
            string lowerCaseFirstName = userFirstName.ToLower();
            Web    latestSite         = GetLatestSite();

            List      heroTaskList = latestSite.Lists.GetByTitle(TASK_LIST_TITLE);
            CamlQuery query        = CamlQuery.CreateAllItemsQuery();

            ListItemCollection taskList = heroTaskList.GetItems(query);

            SharePointContext.Load(taskList);
            SharePointContext.ExecuteQuery();

            foreach (ListItem heroTask in taskList)
            {
                FieldUserValue assignedUser = heroTask["AssignedTo"] as FieldUserValue;
                if (assignedUser.LookupValue.ToLower().Contains(lowerCaseFirstName))
                {
                    toReturn.Add(new SharePointTask()
                    {
                        // AssignedTo = (User)heroTask["AssignedTo"],
                        Title  = (string)heroTask["Title"],
                        Status = (string)heroTask["Status"]
                    });
                }
            }
            return(toReturn);
        }
示例#8
0
        private void MapMembers(ImportFile importFile, ListItem listItem)
        {
            listItem["Created"]  = importFile.Created;
            listItem["Modified"] = importFile.Modified;

            if (importFile.ModifiedBy != null)
            {
                listItem["Editor"] = new FieldUserValue {
                    LookupId = importFile.ModifiedBy.Id
                };
            }
            if (importFile.CreatedBy != null)
            {
                listItem["Author"] = new FieldUserValue {
                    LookupId = importFile.CreatedBy.Id
                };
            }

            listItem["_Source"] = importFile.OriginalFullName;

            foreach (var foo in importFile.MetaData)
            {
                if (m_availableFields.ContainsKey(foo.Key))
                {
                    listItem[foo.Key] = foo.Value;
                }
                else
                {
                    log.Warn("Could not import " + foo.Key + ". Field not found");
                }
            }
        }
示例#9
0
        public RedirectResult NewItem(string managerName, string details, DateTime dueDate)
        {
            ClientContext clientContext = new ClientContext(SiteUrl);

            var user = clientContext.Web.EnsureUser(User.Identity.Name);

            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId = user.Id;

            var manager = clientContext.Web.EnsureUser(managerName);

            clientContext.Load(manager);
            clientContext.ExecuteQuery();
            FieldUserValue managerValue = new FieldUserValue();

            managerValue.LookupId = manager.Id;

            List spList = clientContext.Web.Lists.GetByTitle(ListName);
            var  info   = new ListItemCreationInformation();
            var  item   = spList.AddItem(info);

            item[FieldDetails] = details;
            item[FieldDueDate] = dueDate;
            item[FieldAuthor]  = userValue;
            item[FieldManager] = managerValue;
            item.Update();
            clientContext.ExecuteQuery();

            return(Redirect("Items"));
        }
示例#10
0
        /// <summary>
        /// Updates the system fields.
        /// </summary>
        /// <param name="targetContext">The target context.</param>
        /// <param name="targetItem">The target item.</param>
        /// <param name="sourceItem">The source item.</param>
        protected ListItem UpdateSystemFields(ClientContext targetContext, ListItem targetItem, ListItem sourceItem)
        {
            Logger.Log("Into UpdateSystemFields for " + sourceItem.DisplayName);

            if (sourceItem != null && targetItem != null)
            {
                try
                {
                    var            securityPrincipal = new SecurityPrincipal(Logger, RetryCount, Delay);
                    FieldUserValue author            = securityPrincipal.GetTargetUserFromUserMapping(targetContext, ((FieldUserValue)sourceItem[Constants.Author]));
                    FieldUserValue editor            = securityPrincipal.GetTargetUserFromUserMapping(targetContext, ((FieldUserValue)sourceItem[Constants.Editor]));

                    targetItem[Constants.Author]   = author; //authorUpn.Substring(authorUpn.LastIndexOf('|') + 1)
                    targetItem[Constants.Editor]   = editor; //((FieldUserValue)sourceItem["Editor"]).LookupValue
                    targetItem[Constants.Created]  = (DateTime)sourceItem[Constants.Created];
                    targetItem[Constants.Modified] = (DateTime)sourceItem[Constants.Modified];

                    //targetItem.Update();
                    targetItem.UpdateOverwriteVersion();
                    //targetContext.Load(targetItem);
                    //targetContext.ExecuteQuery();
                    targetContext.ExecuteQueryWithIncrementalRetry(RetryCount, Delay);
                }
                catch (Exception ex)
                {
                    Logger.LogError("Error in AddContent for " + sourceItem.DisplayName + Environment.NewLine + ex.Message);
                    //throw ex;
                }
            }

            return(targetItem);
        }
示例#11
0
        /// <summary>
        /// Get the specified user account in the Target environment.
        /// </summary>
        /// <param name="sourceLogonName">Logon name of the user</param>
        /// <returns>Null if input is invalid, a valid <see cref="Microsoft.SharePoint.Client.FieldUserValue"/> object if found;
        /// a dummy object (LookupId = -1) if specified user and/or the fallback user is not found.</returns>
        private FieldUserValue GetTargetUser(string sourceLogonName)
        {
            if (string.IsNullOrEmpty(sourceLogonName))
            {
                return(null);
            }


            if (null == userMappings[sourceLogonName])
            {
                User userObj = null;

                try
                {
                    userObj = Program.SPContext.Web.EnsureUser(sourceLogonName);
                    Program.SPContext.Load(userObj);
                    Program.SPContext.ExecuteQuery();

                    userMappings[sourceLogonName] = new FieldUserValue()
                    {
                        LookupId = userObj.Id
                    };
                }
                catch (Exception)
                {
                    userMappings[sourceLogonName] = new FieldUserValue()
                    {
                        LookupId = -1
                    };
                }
            }

            return(userMappings[sourceLogonName]);
        }
示例#12
0
        public async Task UpdateListItem(TalkListItem item, int id)
        {
            ClientContext context = GetSharepointContext(item.Url);
            List          list    = context.Web.Lists.GetByTitle(item.ListName);

            context.Load(list);
            await context.ExecuteQueryAsync();

            ListItem itemToUpdate = list.GetItemById(id);

            itemToUpdate["Title"]       = item.Title;
            itemToUpdate["Description"] = item.Description;
            itemToUpdate["Number"]      = item.Number;
            itemToUpdate["Boolean"]     = item.Boolean;
            itemToUpdate["DateTime"]    = item.Datetime;
            itemToUpdate["Choice"]      = item.Choice;
            //User or group
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId          = item.UserOrGroup;
            itemToUpdate["UserOrGroup"] = userValue;
            itemToUpdate["Sevilla"]     = item.Sevilla;
            itemToUpdate.Update();
            await context.ExecuteQueryAsync();
        }
示例#13
0
        private static FieldUserValue GetUserFieldValue(string userName, ClientContext clientContext)
        {
            //Returns first principal match based on user identifier (display name, email, etc.)
            ClientResult <PrincipalInfo> principalInfo = Utility.ResolvePrincipal(
                clientContext,       //context
                clientContext.Web,   //web
                userName,            //input
                PrincipalType.User,  //scopes
                PrincipalSource.All, //sources
                null,                //usersContainer
                false);              //inputIsEmailOnly

            clientContext.ExecuteQuery();
            PrincipalInfo person = principalInfo.Value;

            if (person != null)
            {
                //Get User field from login name
                User validatedUser = clientContext.Web.EnsureUser(person.LoginName);
                clientContext.Load(validatedUser);
                clientContext.ExecuteQuery();

                if (validatedUser != null && validatedUser.Id > 0)
                {
                    //Sets lookup ID for user field to the appropriate user ID
                    FieldUserValue userFieldValue = new FieldUserValue();
                    userFieldValue.LookupId = validatedUser.Id;
                    return(userFieldValue);
                }
            }
            return(null);
        }
示例#14
0
        //GetTaxanomy
        //AddToSharePoinList
        public void AddToSharePoinList(ClientContext context, Advertisment formData, string listTitle)
        {
            _user = GetUser();
            List bookedRooms = context.Web.Lists.GetByTitle(listTitle);
            ListItemCreationInformation SVitemCreateInfo = new ListItemCreationInformation();
            ListItem newItem = bookedRooms.AddItem(SVitemCreateInfo);

            Web Web = context.Web;

            context.Load(Web);
            context.ExecuteQuery();

            User newUser = Web.EnsureUser(_user.LoginName);

            context.Load(newUser);
            context.ExecuteQuery();

            FieldUserValue userValue = new FieldUserValue
            {
                LookupId = newUser.Id
            };

            newItem["Title"]         = formData.ProductTitle;
            newItem["ubza"]          = formData.Description;
            newItem["Pris"]          = formData.Price;
            newItem["Kategorier"]    = formData.Category;
            newItem["Bild"]          = formData.ImageUrl;
            newItem["S_x00e4_ljare"] = userValue;

            newItem.Update();
            context.ExecuteQuery();
        }
示例#15
0
        public static void ApplyCibCollectiveProcess(ClientContext ctx, ClientContext ctx1, ListItem item, string emailCibField, string cibleCollectiveField, bool createAL)
        {
            List <String> CibleIDs = new List <string>();

            CibleIDs = GetTaxonomiesId(item, cibleCollectiveField);
            FieldUserValue[]      ciblInd     = (FieldUserValue[])item[emailCibField];
            List <FieldUserValue> lstCibIndId = new List <FieldUserValue>();
            int cibIndCount = 0;

            if (ciblInd != null)
            {
                cibIndCount = ciblInd.Length;
            }
            foreach (string CibleID in CibleIDs)
            {
                Task <string> azFun = CallEmailAzAsync("wf_Get-Emails-from-CH-Pole-UF", CibleID);


                ListUserDetails lstUserDetails = JsonConvert.DeserializeObject <ListUserDetails>(azFun.Result);
                foreach (UserDetails usd in lstUserDetails.usersDetails)
                {
                    User usr;
                    try
                    {
                        usr = ctx1.Web.EnsureUser(usd.UserName);
                        ctx1.Load(usr);
                        ctx1.ExecuteQuery();
                        FieldUserValue usrValue = new FieldUserValue();
                        usrValue.LookupId = usr.Id;
                        if (ciblInd.Where(a => a.Email == usrValue.Email) == null)
                        {
                            lstCibIndId.Add(usrValue);
                            SPPermissionAuteur(ctx, item, "read", usrValue, createAL, usd.UFDefaultLabel, usd.UFMetadataID);
                        }
                        else
                        {
                            SPPermissionAuteur(ctx, item, "read", usrValue, false);
                        }
                    }
                    catch { }
                }
            }
            if (lstCibIndId.Count() > 0)
            {
                int counter   = 0;
                int arrLength = lstCibIndId.Count() + ciblInd.Length;
                FieldUserValue[] newCibInd = new FieldUserValue[arrLength];
                foreach (FieldUserValue usV in ciblInd)
                {
                    newCibInd[counter] = usV;
                    counter++;
                }
                foreach (FieldUserValue usV in lstCibIndId)
                {
                    newCibInd[counter] = usV;
                    counter++;
                }
                item[emailCibField] = newCibInd;
            }
        }
示例#16
0
        public static void AddAccusseDeLecture(string webUrl, int docID, string docName, User lecteur, string taxLabel = null, string termGuid = null)
        {
            using (ClientContext ctx = SPConnection.GetSPOLContext(webUrl))
            {
                List itemList = ctx.Web.Lists.GetByTitle("Accusés de lecture");
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem itemtoADD = itemList.AddItem(itemCreateInfo);
                itemtoADD["Title"] = docName;
                FieldUserValue usrValue = new FieldUserValue();
                usrValue.LookupId    = lecteur.Id;;
                itemtoADD["Lecteur"] = usrValue;
                if (!string.IsNullOrEmpty(taxLabel))
                {
                    var termValue = new TaxonomyFieldValue();
                    termValue.Label    = taxLabel;
                    termValue.TermGuid = termGuid;
                    termValue.WssId    = -1;

                    itemtoADD["UF_x0020_du_x0020_lecteur"] = termValue;
                }
                FieldLookupValue val = new FieldLookupValue();
                val.LookupId                   = docID;
                itemtoADD["Document"]          = val;
                itemtoADD["Document_x0020_lu"] = false;
                itemtoADD["Commentaires_x0020__x0028_inform"] = "";


                itemtoADD.Update();
                ctx.ExecuteQuery();
            }
        }
示例#17
0
 private static ListItem MapToListItem(BusinessDocumentViewModel viewModel, ListItem targetListItem)
 {
     targetListItem[FileLeafRefField]     = viewModel.Name;
     targetListItem[DocumentPurposeField] = viewModel.Purpose;
     targetListItem[InChargeField]        = FieldUserValue.FromUser(viewModel.InCharge);
     return(targetListItem);
 }
示例#18
0
        private List <FieldUserValue> SetUserValues(IList <string> users)
        {
            var clientContext = new ClientContext(_root);

            var filteredUsers = new List <string>();

            foreach (var user in users)
            {
                try
                {
                    var ensureUser = _rootWeb.EnsureUser(user);
                    clientContext.Load(ensureUser);
                    clientContext.ExecuteQuery();

                    filteredUsers.Add(user);
                }
                catch (Exception)
                {
                    // Do nothing, user does not exists.
                }
            }

            clientContext.Dispose();

            if (filteredUsers.Count > 0)
            {
                return(filteredUsers.Select(loginName => FieldUserValue.FromUser(loginName)).ToList());
            }

            return(new List <FieldUserValue>());
        }
示例#19
0
        // POST: api/BusinessDocuments
        public IHttpActionResult Post([FromBody] BusinessDocumentViewModel value)
        {
            string validationError = null;

            if (!ValidateModel(value, out validationError))
            {
                return(BadRequest(validationError));
            }

            using (var clientContext = WebAPIHelper.GetClientContext(this.ControllerContext))
            {
                // Get the documents from the Business Documents library
                List businessDocsLib = clientContext.Web.GetListByUrl("/BusinessDocs");
                // Ensure the root folder is loaded
                Folder   rootFolder = businessDocsLib.EnsureProperty(l => l.RootFolder);
                ListItem newItem    = businessDocsLib.CreateDocument(value.Name, rootFolder, DocumentTemplateType.Word);

                // Update the new document metadata
                newItem[DocumentPurposeField] = value.Purpose;
                newItem[InChargeField]        = FieldUserValue.FromUser(value.InCharge);
                newItem.Update();

                // Ensure the needed metadata are loaded
                clientContext.Load(newItem, item => item.Id,
                                   item => item[FileLeafRefField],
                                   item => item[InChargeField],
                                   item => item[DocumentPurposeField]);

                newItem.File.CheckIn("", CheckinType.MajorCheckIn);
                clientContext.ExecuteQuery();

                BusinessDocumentViewModel viewModel = ListItemToViewModel(newItem);
                return(Created($"/api/BusinessDocuments/{viewModel.Id}", viewModel));
            }
        }
示例#20
0
        //RetriveallFields
        //GetItems
        public List <Advertisment> GetItems(ClientContext context, string listTitle)
        {
            ListItemCollection  listItems = RetriveList2(context, listTitle);
            List <Advertisment> products  = new List <Advertisment>();

            foreach (var items in listItems)
            {
                TaxonomyFieldValue taxFieldValue = items["Kategorier"] as TaxonomyFieldValue;
                FieldUserValue     user          = (FieldUserValue)items["S_x00e4_ljare"];
                Advertisment       product       = new Advertisment
                {
                    ID           = Convert.ToInt32(items["ID"]),
                    ProductTitle = items["Title"].ToString(),
                    Description  = Convert.ToString(items["ubza"]),
                    Created      = Convert.ToDateTime(items["Created"]),
                    Price        = Convert.ToDecimal(items["Pris"]),
                    Category     = taxFieldValue.Label,
                    Seller       = user.Email,
                    SellerToken  = VerifyUser(user),
                };
                products.Add(product);
            }

            return(products);
        }
示例#21
0
 private UserInfo ConvertToUserInfo(FieldUserValue userValue) =>
 new UserInfo
 {
     Id    = userValue.LookupId,
     Login = userValue.LookupValue,
     Email = userValue.Email
 };
示例#22
0
        /// <summary>
        /// Adds a new entry to the site directory list
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="siteDirectoryProvisioningPage">Path to a page used as url when the site collection is not yet provisioned</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <param name="title">Title of the site collection</param>
        /// <param name="siteUrl">Url of the site collection</param>
        /// <param name="template">Template used to provision this site collection</param>
        /// <param name="requestor">Person that requested the provisioning</param>
        /// <param name="owner">Person that will be the primary owner of the site collection</param>
        /// <param name="backupOwners">Person(s) that will be the backup owner(s) of the site collection</param>
        /// <param name="permissions">Chosen permission model</param>
        public void AddSiteDirectoryEntry(ClientContext cc, Web web, string siteDirectoryHost, string siteDirectoryProvisioningPage, string listName, string title, string siteUrl, string template, string[] ownerLogins)
        {
            List listToInsertTo = web.Lists.GetByTitle(listName);
            ListItemCreationInformation lici = new ListItemCreationInformation();
            ListItem listItem = listToInsertTo.AddItem(lici);

            listItem["Title"] = title;

            //URL = hyperlink field
            FieldUrlValue url = new FieldUrlValue();

            url.Description       = title;
            url.Url               = String.Format("{0}/{1}", siteDirectoryHost, siteDirectoryProvisioningPage);
            listItem["SiteTitle"] = url;
            // store url also as text field to facilitate easy CAML querying afterwards
            listItem["UrlText"] = siteUrl;

            // Owners = Person field with multiple values
            FieldUserValue[] users = new FieldUserValue[ownerLogins.Length];

            int i = 0;

            foreach (string ownerLogin in ownerLogins)
            {
                FieldUserValue ownersField = FieldUserValue.FromUser(ownerLogin);
                users[i] = ownersField;
                i++;
            }
            listItem["Owners"]   = users;
            listItem["Template"] = template;
            listItem["Status"]   = "Requested";
            listItem.Update();
            cc.ExecuteQuery();
        }
        private static void BuildUserProfileMarkup(Guid listId, StringBuilder html, FieldUserValue userProfileField)
        {
            html.Append("<span class=\"user-name\">");

            var userProfileId = userProfileField.LookupId;
            var userProfile = PublicApi.UserProfiles.Get(listId, userProfileId);
            if (!string.IsNullOrEmpty(userProfile.Email))
            {
                var evolutionUser = TEApi.Users.Get(new UsersGetOptions { Email = userProfile.Email });
                if (evolutionUser != null)
                {
                    html.AppendFormat("<a href=\"{0}\" class=\"user-icon internal-link view-user-profile\">{1}</a>", HttpUtility.HtmlAttributeEncode(evolutionUser.ProfileUrl), HttpUtility.HtmlEncode(evolutionUser.DisplayName));
                }
                else
                {
                    html.AppendFormat("<span class=\"user-icon\" title=\"{0}\">{1}</span>", HttpUtility.HtmlAttributeEncode(userProfileField.LookupValue), HttpUtility.HtmlEncode(userProfileField.LookupValue));
                }
            }
            else
            {
                html.Append(HttpUtility.HtmlEncode(userProfileField.LookupValue));
            }

            html.Append("</span>");
        }
示例#24
0
        /// <summary>
        /// Adds a new entry to the site directory list
        /// </summary>
        /// <param name="siteDirectoryHost">Url to the site directory site collection</param>
        /// <param name="siteDirectoryProvisioningPage">Path to a page used as url when the site collection is not yet provisioned</param>
        /// <param name="listName">Name of the site directory list</param>
        /// <param name="title">Title of the site collection</param>
        /// <param name="siteUrl">Url of the site collection</param>
        /// <param name="template">Template used to provision this site collection</param>
        /// <param name="requestor">Person that requested the provisioning</param>
        /// <param name="owner">Person that will be the primary owner of the site collection</param>
        /// <param name="backupOwners">Person(s) that will be the backup owner(s) of the site collection</param>
        /// <param name="permissions">Chosen permission model</param>
        public void AddSiteDirectoryEntry(ClientContext cc, Web web, string siteDirectoryHost, string siteDirectoryProvisioningPage, string listName, string title, string siteUrl, string template, string[] ownerLogins)
        {
            List listToInsertTo = web.Lists.GetByTitle(listName);
            ListItemCreationInformation lici = new ListItemCreationInformation();
            ListItem listItem = listToInsertTo.AddItem(lici);
            listItem["Title"] = title;

            //URL = hyperlink field
            FieldUrlValue url = new FieldUrlValue();
            url.Description = title;
            url.Url = String.Format("{0}/{1}", siteDirectoryHost, siteDirectoryProvisioningPage);
            listItem["SiteTitle"] = url;
            // store url also as text field to facilitate easy CAML querying afterwards
            listItem["UrlText"] = siteUrl;

            // Owners = Person field with multiple values
            FieldUserValue[] users = new FieldUserValue[ownerLogins.Length];

            int i = 0;
            foreach (string ownerLogin in ownerLogins)
            {
                FieldUserValue ownersField = FieldUserValue.FromUser(ownerLogin);
                users[i] = ownersField;
                i++;
            }
            listItem["Owners"] = users;
            listItem["Template"] = template;
            listItem["Status"] = "Requested";
            listItem.Update();
            cc.ExecuteQuery();
        }
        /// <summary>
        /// User类型 单值
        /// </summary>
        /// <param name="userID">User ID </param>
        /// <returns></returns>
        public FieldUserValue UserValue(int userID)
        {
            var userValue = new FieldUserValue();

            userValue.LookupId = userID;
            return(userValue);
        }
        public static void SetMetadataFields(ClientContext cc, JObject inputFields, FieldCollection fields, ListItem item)
        {
            foreach (KeyValuePair <string, JToken> inputField in inputFields)
            {
                var field = fields.GetByInternalNameOrTitle(inputField.Key);

                cc.Load(field);
                cc.ExecuteQuery();
                Console.WriteLine(field.TypeAsString);


                if (field.TypeAsString.Equals("TaxonomyFieldType"))
                {
                    var taxKeywordField = cc.CastTo <TaxonomyField>(field);

                    Guid   _id     = taxKeywordField.TermSetId;
                    string _termID = TermHelper.GetTermIdByName(cc, inputField.Value.ToString(), _id);


                    TaxonomyFieldValue termValue = new TaxonomyFieldValue()
                    {
                        Label    = inputField.Value.ToString(),
                        TermGuid = _termID,
                        //WssId = -1
                        //WssId = (int)taxObj["WssId"]
                    };

                    taxKeywordField.SetFieldValueByValue(item, termValue);
                    taxKeywordField.Update();
                }
                else if (field.TypeAsString.Equals("User"))
                {
                    var user = FieldUserValue.FromUser(inputField.Value.ToString());
                    item[inputField.Key] = user;
                }
                else if (field.TypeAsString.Equals("DateTime") && inputField.Value.ToString() != "")
                {
                    string dateTimeStr = inputField.Value.ToString();
                    dateTimeStr          = dateTimeStr.Replace("~t", "");
                    item[inputField.Key] = Convert.ToDateTime(dateTimeStr);
                }
                else if (inputField.Value.ToString() == "")
                {
                    continue;
                }
                else
                {
                    item[inputField.Key] = inputField.Value.ToString();
                }

                // This method works but not practical
                //string termValue = "-1;#" + taxObj["Label"].ToString() + "|" + taxObj["TermGuid"].ToString();
                //item[inputField.Key] = termValue;


                item.SystemUpdate();
                //cc.ExecuteQuery();
            }
        }
        public static List <ScannedDocument> SynchronizeScannedDocuments(string url, string user, string password, string listName, string navTempPath)
        {
            List <ScannedDocument> scannedDocuments = new List <ScannedDocument>();

            string[] parts = user.Split('\\');

            using (ClientContext clientContext = new ClientContext(url))
            {
                clientContext.Credentials = new NetworkCredential(parts[1], password, parts[0]);

                Web site = clientContext.Web;

                List list = site.Lists.GetByTitle(listName);

                ListItemCollection itemColl = list.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(itemColl);
                clientContext.ExecuteQuery();

                for (int i = 0; i < itemColl.Count; ++i)
                {
                    ListItem li = itemColl[i];
                    clientContext.Load(li, f => f.File);
                    clientContext.ExecuteQuery();
                    string          fileServerRelativePath = li.File.ServerRelativeUrl;
                    FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileServerRelativePath);
                    string          filePath = Path.Combine(navTempPath, li.File.Name);

                    clientContext.Load(li);
                    clientContext.ExecuteQuery();

                    Dictionary <string, object> userValue = li.FieldValues.Where(fv => fv.Key == "IFUZustaendigePerson").ToDictionary(fv => fv.Key, fv => fv.Value);
                    FieldUserValue fuv = (FieldUserValue)userValue.First().Value;

                    clientContext.Load(site.SiteUsers);
                    clientContext.ExecuteQuery();
                    User responsibleUser = null;
                    if (fuv != null)
                    {
                        responsibleUser = site.SiteUsers.Where(u => u.Id == fuv.LookupId).First();
                        clientContext.Load(responsibleUser);
                        clientContext.ExecuteQuery();
                    }
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        fileInfo.Stream.CopyTo(fs);
                    }
                    if (responsibleUser != null)
                    {
                        scannedDocuments.Add(new ScannedDocument(li.FieldValues, filePath, responsibleUser.LoginName.Split('|')[1]));
                    }
                    else
                    {
                        scannedDocuments.Add(new ScannedDocument(li.FieldValues, filePath, String.Empty));
                    }
                }
                clientContext.ExecuteQuery();
            }
            return(scannedDocuments);
        }
示例#28
0
        public static void SetUserValue(this ListItem item, string internalName, int userID)
        {
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId = userID;

            item[internalName] = userValue;
        }
示例#29
0
        public static void SetUserValue(this ListItem item, string internalName, KeyValuePair <int, string> user)
        {
            FieldUserValue userValue = new FieldUserValue();

            userValue.LookupId = user.Key;

            item[internalName] = userValue;
        }
示例#30
0
        private FieldUserValue GetUsersDetails(User userName)
        {
            var userValue = new FieldUserValue();

            userValue.LookupId = userName.Id;

            return(userValue);
        }
 public static string ToUserEmailValue(this FieldUserValue fieldItemValue)
 {
     if (fieldItemValue != null)
     {
         return(fieldItemValue.Email);
     }
     return(string.Empty);
 }
示例#32
0
        /// <summary>
        /// Adds a new request to the SharePoint site. 
        /// </summary>
        /// <param name="input">A VpnRequest model</param>
        public void addRequest(VpnRequest input)
        {
            List spList = clientContext.Web.Lists.GetByTitle(requestNames.ListName);
            clientContext.Load(spList);

            var itemCreateInfo = new ListItemCreationInformation();
            var listItem = spList.AddItem(itemCreateInfo);

            //pulling up the current user information
            User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name);
            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();
            userValue.LookupId = user.Id;

            //pulling up the manager information
            var manager = clientContext.Web.EnsureUser(input.Manager);
            clientContext.Load(manager);
            clientContext.ExecuteQuery();
            FieldUserValue userValue2 = new FieldUserValue();
            userValue2.LookupId = manager.Id;

            listItem[requestNames.internalCreatedBy] = userValue;
            listItem[requestNames.internalVpnRecipientFirst] = input.VPN_recipientFirst;
            listItem[requestNames.internalVpnRecipientLast] = input.VPN_recipientLast;
            listItem[requestNames.internalWorkPhone] = input.Work_Phone;
            listItem[requestNames.internalEmail] = input.VPN_recipientEmail;
            listItem[requestNames.internalUserCode] = input.VPN_userCode;
            listItem[requestNames.internalManager] = userValue2;
            listItem[requestNames.internalUserDept] = input.VPN_userDept;
            listItem[requestNames.internalUserStatus] = input.VPN_userStatus;
            listItem[requestNames.internalSystemsList] = input.Systems_List;
            listItem[requestNames.internalJustification] = input.VPN_justification;
            listItem[requestNames.internalAccessStart] = input.VPN_accessStart;
            listItem[requestNames.internalAccessEnd] = input.VPN_accessEnd;
            listItem[requestNames.internalCompanyName] = input.Company_Name;
            listItem[requestNames.internalCompanyOther] = input.Company_Other;
            listItem[requestNames.internalOfficeLocation] = input.Office_Location;
            listItem[requestNames.internalOfficeAddress] = input.Office_Address;
            listItem[requestNames.internalMachineOwner] = input.Machine_Owner;
            listItem[requestNames.internalExtCode] = input.Ext_code;
            listItem[requestNames.internalAgency] = input.Agency;

            listItem.Update();
            clientContext.ExecuteQuery();
        }
示例#33
0
        public void CreateNewSiteRequest(SiteInformation siteRequest)
        {
            Log.Info("SPSiteRequestManager.CreateNewSiteRequest", "Entering CreateNewSiteRequest requested url {0}", siteRequest.Url);
            UsingContext(ctx =>
            {
                Stopwatch _timespan = Stopwatch.StartNew();
                var _web = ctx.Web;
                ctx.Load(_web);

                if (!_web.ListExists(SiteRequestList.TITLE))
                {
                    var _message = String.Format("The List {0} does not exist in Site {1}",
                         SiteRequestList.TITLE,
                         _web.Url);
                    Log.Fatal("SPSiteRequestManager.CreateNewSiteRequest", _message);
                    throw new DataStoreException(_message);
                }

                List list = _web.Lists.GetByTitle(SiteRequestList.TITLE);
                ListItemCreationInformation _listItemCreation = new ListItemCreationInformation();
                ListItem _record = list.AddItem(_listItemCreation);
                _record[SiteRequestFields.TITLE] = siteRequest.Title;
                _record[SiteRequestFields.DESCRIPTION_NAME] = siteRequest.Description;
                _record[SiteRequestFields.TEMPLATE_NAME] = siteRequest.Template;
                _record[SiteRequestFields.URL_NAME] = siteRequest.Url;
                _record[SiteRequestFields.LCID_NAME] = siteRequest.Lcid;
                _record[SiteRequestFields.TIMEZONE_NAME] = siteRequest.TimeZoneId;
                _record[SiteRequestFields.POLICY_NAME] = siteRequest.SitePolicy;
                _record[SiteRequestFields.EXTERNALSHARING_NAME] = siteRequest.EnableExternalSharing;
                _record[SiteRequestFields.ONPREM_REQUEST_NAME] = siteRequest.SharePointOnPremises;
                _record[SiteRequestFields.BC_NAME] = siteRequest.BusinessCase;
                _record[SiteRequestFields.PROPS_NAME] = siteRequest.SiteMetadataJson;
                //If Settings are set to autoapprove then automatically approve the requests
                if(_manager.GetAppSettings().AutoApprove) 
                {
                    _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Approved.ToString();
                    _record[SiteRequestFields.APPROVEDDATE_NAME] = DateTime.Now;
                }
                else 
                {
                    _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.New.ToString();
                }
                
                FieldUserValue _siteOwner = FieldUserValue.FromUser(siteRequest.SiteOwner.Name);
                _record[SiteRequestFields.OWNER_NAME] = _siteOwner;
                
                //Additional Admins
                if(siteRequest.AdditionalAdministrators != null)
                {
                    if (siteRequest.AdditionalAdministrators.Count > 0)
                    {
                        FieldUserValue[] _additionalAdmins = new FieldUserValue[siteRequest.AdditionalAdministrators.Count];
                        int _index = 0;
                        foreach (SiteUser _user in siteRequest.AdditionalAdministrators)
                        {
                            FieldUserValue _adminFieldUser = FieldUserValue.FromUser(_user.Name);
                            _additionalAdmins[_index] = _adminFieldUser;
                            _index++;
                        }
                        _record[SiteRequestFields.ADD_ADMINS_NAME] = _additionalAdmins;
                    }
                }
                _record.Update();
                ctx.ExecuteQuery();
                _timespan.Stop();

                Log.TraceApi("SharePoint", "SPSiteRequestManager.CreateNewSiteRequest", _timespan.Elapsed);
                Log.Info("SPSiteRequestManager.CreateNewSiteRequest", PCResources.SiteRequestNew_Successful, siteRequest.Url);
            }
            );
        }
示例#34
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows);

            if (template.Lists.Any())
            {
                var rootWeb = (web.Context as ClientContext).Site.RootWeb;
                if (!web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    web.Context.Load(web, w => w.ServerRelativeUrl);
                    web.Context.ExecuteQueryRetry();
                }

                web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                web.Context.ExecuteQueryRetry();
                var existingLists = web.Lists.AsEnumerable<List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                var serverRelativeUrl = web.ServerRelativeUrl;

                #region DataRows

                foreach (var listInstance in template.Lists)
                {
                    if (listInstance.DataRows != null && listInstance.DataRows.Any())
                    {
                        // Retrieve the target list
                        var list = web.Lists.GetByTitle(listInstance.Title);
                        web.Context.Load(list);

                        // Retrieve the fields' types from the list
                        FieldCollection fields = list.Fields;
                        web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind));
                        web.Context.ExecuteQueryRetry();

                        foreach (var dataRow in listInstance.DataRows)
                        {
                            var listitemCI = new ListItemCreationInformation();
                            var listitem = list.AddItem(listitemCI);

                            foreach (var dataValue in dataRow.Values)
                            {
                                Field dataField = fields.FirstOrDefault(
                                    f => f.InternalName == dataValue.Key.ToParsedString());

                                if (dataField != null)
                                {
                                    String fieldValue = dataValue.Value.ToParsedString();

                                    switch (dataField.FieldTypeKind)
                                    {
                                        case FieldType.Geolocation:
                                            // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                            var geolocationArray = fieldValue.Split(',');
                                            if (geolocationArray.Length == 4)
                                            {
                                                var geolocationValue = new FieldGeolocationValue
                                                {
                                                    Altitude = Double.Parse(geolocationArray[0]),
                                                    Latitude = Double.Parse(geolocationArray[1]),
                                                    Longitude = Double.Parse(geolocationArray[2]),
                                                    Measure = Double.Parse(geolocationArray[3]),
                                                };
                                                listitem[dataValue.Key.ToParsedString()] = geolocationValue;
                                            }
                                            else
                                            {
                                                listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            }
                                            break;
                                        case FieldType.Lookup:
                                            // FieldLookupValue - Expected format: LookupID
                                            var lookupValue = new FieldLookupValue
                                            {
                                                LookupId = Int32.Parse(fieldValue),
                                            };
                                            listitem[dataValue.Key.ToParsedString()] = lookupValue;
                                            break;
                                        case FieldType.URL:
                                            // FieldUrlValue - Expected format: URL,Description
                                            var urlArray = fieldValue.Split(',');
                                            var linkValue = new FieldUrlValue();
                                            if (urlArray.Length == 2)
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[1];
                                            }
                                            else
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[0];
                                            }
                                            listitem[dataValue.Key.ToParsedString()] = linkValue;
                                            break;
                                        case FieldType.User:
                                            // FieldUserValue - Expected format: loginName
                                            var user = web.EnsureUser(fieldValue);
                                            web.Context.Load(user);
                                            web.Context.ExecuteQueryRetry();

                                            if (user != null)
                                            {
                                                var userValue = new FieldUserValue
                                                {
                                                    LookupId = user.Id,
                                                };
                                                listitem[dataValue.Key.ToParsedString()] = userValue;
                                            }
                                            else
                                            {
                                                listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            }
                                            break;
                                        default:
                                            listitem[dataValue.Key.ToParsedString()] = fieldValue;
                                            break;
                                    }
                                }
                                listitem.Update();
                            }
                            web.Context.ExecuteQueryRetry(); // TODO: Run in batches?
                        }
                    }
                }
                #endregion
            }
        }
示例#35
0
        public void SetFileProperties(File file, IDictionary<string, string> properties, bool checkoutIfRequired = true)
        {
            var context = file.Context;
            if (properties != null && properties.Count > 0)
            {
                // Get a reference to the target list, if any
                // and load file item properties
                var parentList = file.ListItemAllFields.ParentList;
                context.Load(parentList);
                context.Load(file.ListItemAllFields);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (ServerException ex)
                {
                    // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties)
                    if (ex.Message != "The object specified does not belong to a list.")
                    {
                        throw;
                    }
                }

                // Loop through and detect changes first, then, check out if required and apply
                foreach (var kvp in properties)
                {
                    var propertyName = kvp.Key;
                    var propertyValue = kvp.Value;

                    var targetField = parentList.Fields.GetByInternalNameOrTitle(propertyName);
                    targetField.EnsureProperties(f => f.TypeAsString, f => f.ReadOnlyField);

                    // Changed by PaoloPia because there are fields like PublishingPageLayout
                    // which are marked as read-only, but have to be overwritten while uploading
                    // a publishing page file and which in reality can still be written
                    if (!targetField.ReadOnlyField || WriteableReadOnlyFields.Contains(propertyName.ToLower()))
                    {
                        switch (propertyName.ToUpperInvariant())
                        {
                            case "CONTENTTYPE":
                                {
                                    Microsoft.SharePoint.Client.ContentType targetCT = parentList.GetContentTypeByName(propertyValue);
                                    context.ExecuteQueryRetry();

                                    if (targetCT != null)
                                    {
                                        file.ListItemAllFields["ContentTypeId"] = targetCT.StringId;
                                    }
                                    else
                                    {
                                        Log.Error(Constants.LOGGING_SOURCE, "Content Type {0} does not exist in target list!", propertyValue);
                                    }
                                    break;
                                }
                            default:
                                {
                                    switch (targetField.TypeAsString)
                                    {
                                        case "User":
                                            var user = parentList.ParentWeb.EnsureUser(propertyValue);
                                            context.Load(user);
                                            context.ExecuteQueryRetry();

                                            if (user != null)
                                            {
                                                var userValue = new FieldUserValue
                                                {
                                                    LookupId = user.Id,
                                                };
                                                file.ListItemAllFields[propertyName] = userValue;
                                            }
                                            break;
                                        case "URL":
                                            var urlArray = propertyValue.Split(',');
                                            var linkValue = new FieldUrlValue();
                                            if (urlArray.Length == 2)
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[1];
                                            }
                                            else
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[0];
                                            }
                                            file.ListItemAllFields[propertyName] = linkValue;
                                            break;
                                        case "MultiChoice":
                                            var multiChoice = JsonUtility.Deserialize<String[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = multiChoice;
                                            break;
                                        case "LookupMulti":
                                            var lookupMultiValue = JsonUtility.Deserialize<FieldLookupValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = lookupMultiValue;
                                            break;
                                        case "TaxonomyFieldType":
                                            var taxonomyValue = JsonUtility.Deserialize<TaxonomyFieldValue>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValue;
                                            break;
                                        case "TaxonomyFieldTypeMulti":
                                            var taxonomyValueArray = JsonUtility.Deserialize<TaxonomyFieldValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValueArray;
                                            break;
                                        default:
                                            file.ListItemAllFields[propertyName] = propertyValue;
                                            break;
                                    }
                                    break;
                                }
                        }
                    }
                    file.ListItemAllFields.Update();
                    context.ExecuteQueryRetry();
                }
            }
        }
 /// <summary>
 /// Bulk resolves the specified users.
 /// </summary>
 /// <param name="clientContext">Client context</param>
 /// <param name="userNames">Name of the users to be resolved</param>
 /// <returns>List of resolved users</returns>
 public static IList<FieldUserValue> ResolveUserNames(ClientContext clientContext, IList<string> userNames)
 {
     List<FieldUserValue> userList = new List<FieldUserValue>();
     if (null != clientContext && null != userNames)
     {
         foreach (string userName in userNames)
         {
             if (!string.IsNullOrWhiteSpace(userName))
             {
                 User user = clientContext.Web.EnsureUser(userName.Trim());
                 ///// Only Fetch the User ID which is required
                 clientContext.Load(user, u => u.Id);
                 clientContext.ExecuteQuery();
                 ///// Add the user to the first element of the FieldUserValue array.
                 FieldUserValue tempUser = new FieldUserValue();
                 tempUser.LookupId = user.Id;
                 userList.Add(tempUser);
             }
         }
     }
     return userList;
 }      
        internal static IList<FieldUserValue> ResolveUserNames(Dictionary<string, string> configVal, string tempUserNames)
        {
            IList<string> userNames = new List<string>();
            if (!string.IsNullOrEmpty(tempUserNames) && string.Empty != tempUserNames.Split(';')[0].Trim())
            {
                foreach (string temp in tempUserNames.Split(';'))
                {
                    userNames.Add(temp);
                }

                List<FieldUserValue> userList = new List<FieldUserValue>();
                if (null != userNames)
                {
                    foreach (string userName in userNames)
                    {
                        if (!string.IsNullOrWhiteSpace(userName))
                        {
                            using (ClientContext clientContext = GetClientContext(configVal["CatalogSiteURL"], configVal))
                            {
                                User user = clientContext.Web.EnsureUser(userName.Trim());
                                // Only Fetch the User ID which is required
                                clientContext.Load(user); //, u => u.Id);
                                clientContext.ExecuteQuery();
                                // Add the user to the first element of the FieldUserValue array.
                                FieldUserValue tempUser = new FieldUserValue();
                                tempUser.LookupId = user.Id;
                                userList.Add(tempUser);
                            }
                        }
                    }
                }
                return userList;
            }
            return null;
        }
示例#38
0
        /// <summary>
        /// Grabs all VPN Requests created by the current user. Queries the SharePoint backend. 
        /// </summary>
        /// <returns>A list of all VPN Requests created by the current user.</returns>
        public List<VpnRequest> getAllMyRequests()
        {
            List spList = clientContext.Web.Lists.GetByTitle(requestNames.ListName);
            clientContext.Load(spList);

            //pulling the current user's name
            User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name);
            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();
            userValue.LookupId = user.Id;

            //querying all requests created by the user
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"
                <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='Author' LookupId='True'/>
                                <Value Type='Lookup'>" + userValue.LookupId + @"</Value>
                            </Eq>
                        </Where>
                    </Query>
                </View>";

            ListItemCollection col = spList.GetItems(camlQuery);
            clientContext.Load(col);
            clientContext.ExecuteQuery();

            //modeling the query data into VpnRequest model
            List<VpnRequest> currentRequests = new List<VpnRequest>();
            currentRequests = loadList(currentRequests, col);

            return currentRequests;
        }
示例#39
0
        /// <summary>
        /// Grabs a list of all requests that have been previously rejected by the current user. 
        /// </summary>
        /// <returns>A list of VPN Requests previously rejected by the current user.</returns>
        public List<VpnRequest> getRejectedReviews()
        {
            List<VpnRequest> returnList = new List<VpnRequest>();

            List vpnRequestList = clientContext.Web.Lists.GetByTitle(requestNames.ListName);
            List taskList = clientContext.Web.Lists.GetByTitle(taskNames.TaskListName);
            clientContext.Load(vpnRequestList);
            clientContext.Load(taskList);

            //pulling the current user's name
            User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name);
            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();
            userValue.LookupId = user.Id;

            //querying the tasklist for all tasks where current user = assigned to AND where outcome = approved
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"
                <View>
                    <Query>
                        <Where>
                            <And>
                                <Eq>
                                    <FieldRef Name='AssignedTo' LookupId='True'/>
                                    <Value Type='Lookup'>" + userValue.LookupId + @"</Value>
                                </Eq>
                                <Eq>
                                    <FieldRef Name='WorkflowOutcome' LookupId ='True'/>
                                    <Value Type = 'Text'>Rejected</Value>
                                </Eq>
                            </And>
                        </Where>
                    </Query>
                </View>";

            ListItemCollection col = taskList.GetItems(camlQuery);
            clientContext.Load(col);
            clientContext.ExecuteQuery();

            //using the results from the query, a list containing the ID of the VPN Requests is created
            List<string> fetchIds = new List<string>();
            foreach (ListItem current in col)
            {
                string[] pieces = ((string)current[taskNames.internalTaskTitle]).Split('/');
                string vpnRequestID = pieces[2];
                fetchIds.Add(vpnRequestID);
            }

            //fetching all VPN Requests that have that have that ID
            returnList = loadList(returnList, fetchIds);
            return returnList;
        }
示例#40
0
        /// <summary>
        /// Grabs all VPN Requests currently waiting to be reviewed by the current user. 
        /// The status of the current user is checked first, then based on that, VPN Requests are queried. 
        /// 1. Grabs all VPN Requests currently in status 'Pending Manager Approval' and assigned to current user 
        /// 2. Checks if the current user is an IT Manager or Security Officer 
        /// 3. If security officer, grab all VPN Requests currently in status 'Pending Security Officer' 
        /// 4. if IT manager, grab all VPN Requests currently in status 'Pending IT Manager' 
        /// </summary>
        /// <returns>A list of all requests pending the approval of the current manager</returns>
        public List<VpnRequest> getPendingReviews()
        {
            List vpnRequestList = clientContext.Web.Lists.GetByTitle(requestNames.ListName);
            List approversList = clientContext.Web.Lists.GetByTitle(requestNames.ApproversListName);
            clientContext.Load(vpnRequestList);
            clientContext.Load(approversList);

            //pulling the current user's name
            User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name);
            clientContext.Load(user);
            clientContext.ExecuteQuery();
            FieldUserValue userValue = new FieldUserValue();
            userValue.LookupId = user.Id;

            List<VpnRequest> pendingRequests = new List<VpnRequest>();

            //Querying all requests where Manager = Current User AND where Request Status = Pending Manager Approval
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"
                <View>
                    <Query>
                        <Where>
                            <And>
                                <Eq>
                                    <FieldRef Name='" + requestNames.internalManager + @"' LookupId='True'/>
                                    <Value Type='Lookup'>" + userValue.LookupId + @"</Value>
                                </Eq>
                                <Eq>
                                    <FieldRef Name='" + requestNames.internalRequestStatus + @"' LookupId ='True'/>
                                    <Value Type = 'Text'>" + requestNames.pendingManager + @"</Value>
                                </Eq>
                            </And>
                        </Where>
                    </Query>
                </View>";
            ListItemCollection col = vpnRequestList.GetItems(camlQuery);
            clientContext.Load(col);
            clientContext.ExecuteQuery();
            pendingRequests = loadList(pendingRequests, col);

            //Querying the approver list to see if the current user is either an IT Manager or Security Manager
            bool isSecurity = false;
            bool isItManager = false;
            camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"
            <View>
                <Query>
                    <Where>
                        <Eq>
                            <FieldRef Name = 'Users' LookupId ='True'/>
                            <Value Type ='Lookup'>" + userValue.LookupId + @"</Value>
                        </Eq>
                    </Where>
                </Query>
            </View>";
            col = approversList.GetItems(camlQuery);
            clientContext.Load(col);
            clientContext.ExecuteQuery();

            foreach (ListItem current in col)
            {
                if (current[requestNames.internalApproversTitle].Equals(requestNames.spNameForITManager))
                {
                    isItManager = true;
                }

                if (current[requestNames.internalApproversTitle].Equals(requestNames.spNameForSecurity))
                {
                    isSecurity = true;
                }
            }
            if (isSecurity == true)
            {
                camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"
               <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='" + requestNames.internalRequestStatus + @"' LookupId ='True'/>
                                <Value Type = 'Text'>" + requestNames.pendingSecurity + @"</Value>
                            </Eq>
                        </Where>
                    </Query>
                </View>";
                col = vpnRequestList.GetItems(camlQuery);
                clientContext.Load(col);
                clientContext.ExecuteQuery();

                pendingRequests = loadList(pendingRequests, col);
            }

            if (isItManager == true)
            {
                camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"
               <View>
                    <Query>
                        <Where>
                            <Eq>
                                <FieldRef Name='" + requestNames.internalRequestStatus + @"' LookupId ='True'/>
                                <Value Type = 'Text'>" + requestNames.pendingITManager + @"</Value>
                            </Eq>
                        </Where>
                    </Query>
                </View>";
                col = vpnRequestList.GetItems(camlQuery);
                clientContext.Load(col);
                clientContext.ExecuteQuery();

                pendingRequests = loadList(pendingRequests, col);
            }

            return orderList(pendingRequests);
        }
示例#41
0
        protected override void ExecuteCmdlet()
        {
            List list = null;
            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                var item = Identity.GetListItem(list);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
                var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title, f => f.FieldTypeKind));
                ClientContext.ExecuteQueryRetry();

                foreach (var key in Values.Keys)
                {
                    var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                    if (field != null)
                    {
                        switch (field.FieldTypeKind)
                        {
                            case FieldType.User:
                                {
                                    List<FieldUserValue> userValues = new List<FieldUserValue>();

                                    var value = Values[key];
                                    if (value.GetType().IsArray)
                                    {
                                        foreach (var arrayItem in value as object[])
                                        {
                                            int userId;
                                            if (!int.TryParse(arrayItem as string, out userId))
                                            {
                                                var user = SelectedWeb.EnsureUser(arrayItem as string);
                                                ClientContext.Load(user);
                                                ClientContext.ExecuteQueryRetry();
                                                userValues.Add(new FieldUserValue() {LookupId = user.Id});
                                            }
                                            else
                                            {
                                                userValues.Add(new FieldUserValue() { LookupId = userId });
                                            }
                                        }
                                        item[key as string] = userValues.ToArray();
                                    }
                                    else
                                    {
                                        int userId;
                                        if (!int.TryParse(value as string, out userId))
                                        {
                                            var user = SelectedWeb.EnsureUser(value as string);
                                            ClientContext.Load(user);
                                            ClientContext.ExecuteQueryRetry();
                                            item[key as string] = new FieldUserValue() {LookupId = user.Id};
                                        }
                                        else
                                        {
                                            item[key as string] = new FieldUserValue() { LookupId = userId };
                                        }
                                    }
                                    break;
                                }
                            default:
                                {
                                    item[key as string] = Values[key];
                                    break;
                                }
                        }
                    }
                    else
                    {
                        throw new Exception("Field not present in list");
                    }
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
示例#42
0
        private static FieldUserValue GetUserFieldValue(string userName, ClientContext clientContext)
        {
            //Returns first principal match based on user identifier (display name, email, etc.)
            ClientResult<PrincipalInfo> principalInfo = Utility.ResolvePrincipal(
                clientContext, //context
                clientContext.Web, //web
                userName, //input
                PrincipalType.User, //scopes
                PrincipalSource.All, //sources
                null, //usersContainer
                false); //inputIsEmailOnly
            clientContext.ExecuteQuery();
            PrincipalInfo person = principalInfo.Value;

            if (person != null)
            {
                //Get User field from login name
                User validatedUser = clientContext.Web.EnsureUser(person.LoginName);
                clientContext.Load(validatedUser);
                clientContext.ExecuteQuery();

                if (validatedUser != null && validatedUser.Id > 0)
                {
                    //Sets lookup ID for user field to the appropriate user ID
                    FieldUserValue userFieldValue = new FieldUserValue();
                    userFieldValue.LookupId = validatedUser.Id;
                    return userFieldValue;
                }
            }
            return null;
        }
示例#43
0
        /// <summary>
        /// Get the email taht sahrpoint has picked up from AD
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public String getUserEmail(FieldUserValue UserName)
        {
            User _getUser = _context.Web.SiteUsers.GetById(UserName.LookupId);
            _context.Load(_getUser, u => u.Email);
            _context.ExecuteQuery();
            return _getUser.Email;

        }
示例#44
0
            private string GetUserLoginById(FieldUserValue userValue)
            {
                string loginName = "";

                if (null == m_dictUserCache)
                {
                    m_dictUserCache = new Dictionary<int, string>();
                }
                string dictValue = "";
                if (m_dictUserCache.TryGetValue(userValue.LookupId, out dictValue))
                {
                    loginName = dictValue;
                }
                else
                {
                    try
                    {
                        var user = this.Web.GetUserById(userValue.LookupId);

                        this.Context.Load(user, u => u.LoginName);
                        this.Context.ExecuteQuery();
                        loginName = user.LoginName;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, Constants.LOGGING_SOURCE, "Failed to get user by id. User Title: '{0}', User ID:{1}", userValue.LookupValue, userValue.LookupId);
                    }
                    m_dictUserCache.Add(userValue.LookupId, loginName);
                }
                return loginName;
            }
示例#45
0
        /// <summary>
        /// Gets the user access.
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        //public bool GetUserAccess(Client client) => spList.CheckPermissionOnList(client, listNames.SendMailListName, PermissionKind.EditListItems);


        public IList<FieldUserValue> ResolveUserNames(ClientContext clientContext, IList<string> userNames)
        {
            List<FieldUserValue> userList = new List<FieldUserValue>();
            foreach (string userName in userNames)
            {
                //Check has been made to check whether the user is present in the system as part of external sharing implementation
                if (!string.IsNullOrWhiteSpace(userName) && 
                    CheckUserPresentInMatterCenter(clientContext, userName))
                {
                    User user = clientContext.Web.EnsureUser(userName.Trim());
                    ///// Only Fetch the User ID which is required
                    clientContext.Load(user, u => u.Id);
                    clientContext.ExecuteQuery();
                    ///// Add the user to the first element of the FieldUserValue array.
                    FieldUserValue tempUser = new FieldUserValue();
                    tempUser.LookupId = user.Id;
                    userList.Add(tempUser);
                }
            }
            return userList;
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {

                if (template.Lists.Any())
                {
                    var rootWeb = (web.Context as ClientContext).Site.RootWeb;

                    web.EnsureProperties(w => w.ServerRelativeUrl);

                    web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                    web.Context.ExecuteQueryRetry();
                    var existingLists = web.Lists.AsEnumerable<List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                    var serverRelativeUrl = web.ServerRelativeUrl;

                    #region DataRows

                    foreach (var listInstance in template.Lists)
                    {
                        if (listInstance.DataRows != null && listInstance.DataRows.Any())
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title);
                            // Retrieve the target list
                            var list = web.Lists.GetByTitle(listInstance.Title);
                            web.Context.Load(list);

                            // Retrieve the fields' types from the list
                            FieldCollection fields = list.Fields;
                            web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind));
                            web.Context.ExecuteQueryRetry();

                            foreach (var dataRow in listInstance.DataRows)
                            {
                                try
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1);
                                    var listitemCI = new ListItemCreationInformation();
                                    var listitem = list.AddItem(listitemCI);

                                    foreach (var dataValue in dataRow.Values)
                                    {
                                        Field dataField = fields.FirstOrDefault(
                                            f => f.InternalName == parser.ParseString(dataValue.Key));

                                        if (dataField != null)
                                        {
                                            String fieldValue = parser.ParseString(dataValue.Value);

                                            switch (dataField.FieldTypeKind)
                                            {
                                                case FieldType.Geolocation:
                                                    // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                                    var geolocationArray = fieldValue.Split(',');
                                                    if (geolocationArray.Length == 4)
                                                    {
                                                        var geolocationValue = new FieldGeolocationValue
                                                        {
                                                            Altitude = Double.Parse(geolocationArray[0]),
                                                            Latitude = Double.Parse(geolocationArray[1]),
                                                            Longitude = Double.Parse(geolocationArray[2]),
                                                            Measure = Double.Parse(geolocationArray[3]),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = geolocationValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;
                                                case FieldType.Lookup:
                                                    // FieldLookupValue - Expected format: LookupID
                                                    var lookupValue = new FieldLookupValue
                                                    {
                                                        LookupId = Int32.Parse(fieldValue),
                                                    };
                                                    listitem[parser.ParseString(dataValue.Key)] = lookupValue;
                                                    break;
                                                case FieldType.URL:
                                                    // FieldUrlValue - Expected format: URL,Description
                                                    var urlArray = fieldValue.Split(',');
                                                    var linkValue = new FieldUrlValue();
                                                    if (urlArray.Length == 2)
                                                    {
                                                        linkValue.Url = urlArray[0];
                                                        linkValue.Description = urlArray[1];
                                                    }
                                                    else
                                                    {
                                                        linkValue.Url = urlArray[0];
                                                        linkValue.Description = urlArray[0];
                                                    }
                                                    listitem[parser.ParseString(dataValue.Key)] = linkValue;
                                                    break;
                                                case FieldType.User:
                                                    // FieldUserValue - Expected format: loginName
                                                    var user = web.EnsureUser(fieldValue);
                                                    web.Context.Load(user);
                                                    web.Context.ExecuteQueryRetry();

                                                    if (user != null)
                                                    {
                                                        var userValue = new FieldUserValue
                                                        {
                                                            LookupId = user.Id,
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = userValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;
                                                default:
                                                    listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    break;
                                            }
                                        }
                                        listitem.Update();
                                    }
                                    web.Context.ExecuteQueryRetry(); // TODO: Run in batches?

                                    if (dataRow.Security != null)
                                    {
                                        listitem.SetSecurity(parser, dataRow.Security);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace);
                                    throw;
                                }
                            }
                        }
                    }

                    #endregion
                }
            }

            return parser;
        }
示例#47
0
 public Usuario(FieldUserValue usuario)
 {
     this.ID = usuario.LookupId;
     this.Nome = usuario.LookupValue;
 }