public static void DeleteLists(Web web)
        {
            ClientRuntimeContext context = web.Context;

            try
            {
                var lessonslearned = web.Lists.GetByTitle(LESSONSLEARNEDLISTTITLE);
                context.Load(lessonslearned);
                lessonslearned.DeleteObject();
                context.ExecuteQuery();
            }
            catch { }



            try
            {
                var projects = web.Lists.GetByTitle(PROJECTSLISTTITLE);
                context.Load(projects);
                projects.DeleteObject();
                context.ExecuteQuery();
            }
            catch { }


            try
            {
                var keywords = web.Lists.GetByTitle(KEYWORDSLISTTITLE);
                context.Load(keywords);
                keywords.DeleteObject();
                context.ExecuteQuery();
            }
            catch { }
        }
Beispiel #2
0
        private long GetWebSize(Web currentWeb)
        {
            long tmpSize = 0;

            ClientRuntimeContext clientContext = currentWeb.Context;

            clientContext.Load(currentWeb);
            clientContext.ExecuteQuery();

            //ListCollection lists = currentWeb.Lists;
            //clientContext.Load(lists);
            //clientContext.ExecuteQuery();

            var Libraries = clientContext.LoadQuery(currentWeb.Lists.Where(l => l.BaseTemplate == 101));

            clientContext.ExecuteQuery();

            foreach (List tmpList in Libraries)
            {
                clientContext.Load(tmpList);
                clientContext.ExecuteQuery();

                string Query = String.Concat(
                    "<View>",
                    "<ViewFields>",
                    "<FieldRef Name='Title'/>",
                    "<FieldRef Name='ID'/>",
                    "<FieldRef Name='File_x0020_Size'/>",
                    "</ViewFields>",
                    "</View>");

                CamlQuery          oQuery        = new CamlQuery();
                ListItemCollection collListItems = tmpList.GetItems(oQuery);
                clientContext.Load(collListItems);

                //FileCollection listFiles = tmpList.RootFolder.Files;
                //clientContext.Load(listFiles,
                //	files => files.Include(file => file.ETag),
                //	files => files.Include(file => file.ListItemAllFields["File_x0020_Size"]));

                clientContext.ExecuteQuery();

                foreach (ListItem oListItem in collListItems)
                {
                    clientContext.Load(oListItem);
                    clientContext.ExecuteQuery();

                    var fileSize = (string)oListItem["File_x0020_Size"];

                    int itemFileSize = String.IsNullOrEmpty(fileSize) ? 0 : int.Parse(fileSize);

                    tmpSize += itemFileSize;
                }
            }

            return(tmpSize);
        }
Beispiel #3
0
        public Folder EnsureFolder(ClientRuntimeContext context, Folder ParentFolder, string FolderPath)
        {
            if (string.IsNullOrEmpty(FolderPath))
            {
                return(ParentFolder);
            }

            //Split up the incoming path so we have the first element as the a new sub-folder name
            //and add it to ParentFolder folders collection
            string[] PathElements = FolderPath.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
            string   Head         = PathElements[0];

            var NewFolder = ParentFolder.Folders.GetByUrl(Head);

            try
            {
                context.ExecuteQuery();
            }
            catch (Exception e)
            {
                NewFolder = ParentFolder.Folders.Add(Head);
                context.Load(NewFolder);
                try
                {
                    context.ExecuteQuery();
                }
                catch (Exception eee)
                {
                    throw;
                }
            }

            //If we have subfolders to create then the length of PathElements will be greater than 1
            if (PathElements.Length > 1)
            {
                //If we have more nested folders to create then reassemble the folder path using what we have left i.e. the tail
                string Tail = string.Empty;
                for (int i = 1; i < PathElements.Length; i++)
                {
                    Tail = Tail + "/" + PathElements[i];
                }

                //Then make a recursive call to create the next subfolder
                return(EnsureFolder(context, NewFolder, Tail));
            }
            else
            {
                //This ensures that the folder at the end of the chain gets returned
                return(NewFolder);
            }
        }
Beispiel #4
0
 /// <summary>
 /// Assigns item level permission
 /// </summary>
 /// <param name="clientContext">Client context object</param>
 /// <param name="listName">List name</param>
 /// <param name="listItemId">List item id</param>
 internal static void AssignItemPermission(ClientContext clientContext, string listName, int listItemId)
 {
     try
     {
         if (null != clientContext && !string.IsNullOrEmpty(listName))
         {
             ListItem listItem = clientContext.Web.Lists.GetByTitle(listName).GetItemById(listItemId);
             clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
             clientContext.ExecuteQuery();
             if (listItem.HasUniqueRoleAssignments)
             {
                 SecurableObject      listItemObject       = listItem;
                 ClientRuntimeContext clientRuntimeContext = clientContext;
                 // get the user object
                 Principal      userPrincipal  = clientContext.Web.AssociatedOwnerGroup;
                 string         roleName       = ConfigurationManager.AppSettings["Role"];
                 RoleDefinition roleDefinition = clientContext.Web.RoleDefinitions.GetByName(roleName);
                 // create the role definition binding collection
                 RoleDefinitionBindingCollection roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(clientRuntimeContext);
                 // add the role definition to the collection
                 roleDefinitionBindingCollection.Add(roleDefinition);
                 // create a RoleAssigment with the user and role definition
                 listItemObject.RoleAssignments.Add(userPrincipal, roleDefinitionBindingCollection);
                 clientRuntimeContext.ExecuteQuery();
             }
         }
     }
     catch (Exception exception)
     {
         ErrorLogger.DisplayErrorMessage(string.Format(CultureInfo.InvariantCulture, Constants.AssigningPermissionsExceptionMessage, Constants.SettingsPage, exception.Message));
     }
 }
Beispiel #5
0
        public void Execute()
        {
            ClientRuntimeContext tenantClientContext = this.GetTenantClientContext();

            if (tenantClientContext == null)
            {
                SharePointNotification.Tracer.TraceDebug((long)this.GetHashCode(), "No ClientContext, skipping call to SharePoint");
                return;
            }
            using (tenantClientContext)
            {
                SharePointDirectoryProvider sharePointDirectoryProvider = new SharePointDirectoryProvider(tenantClientContext);
                if (this.notificationType == SharePointNotification.NotificationType.Create)
                {
                    this.directoryObjectData.Version = -1L;
                    sharePointDirectoryProvider.CreateDirectoryObject(this.directoryObjectData);
                }
                else if (this.notificationType == SharePointNotification.NotificationType.Update)
                {
                    sharePointDirectoryProvider.NotifyDataChanges(this.directoryObjectData);
                }
                else if (this.notificationType == SharePointNotification.NotificationType.Delete)
                {
                    sharePointDirectoryProvider.DeleteDirectoryObject(this.directoryObjectData);
                }
                tenantClientContext.RequestTimeout = 180000;
                tenantClientContext.ExecuteQuery();
            }
        }
        private Principal ResolvePrincipal(ClientRuntimeContext context, Web web, string owner)
        {
            Principal result = null;

            var targetSources = new Dictionary <PrincipalType, PrincipalInfo>();

            // owner might be only a user or sharepoint group
            // making a few attempts and checking NULL ref later in the code
            targetSources.Add(PrincipalType.SharePointGroup, null);
            targetSources.Add(PrincipalType.User, null);

            foreach (var targetSource in targetSources.Keys)
            {
                // ResolvePrincipal != SearchPrincipals, at all!

                //var principalInfos = Utility.ResolvePrincipal(context, web, owner, targetSource, PrincipalSource.All, null, false);
                var principalInfos = Utility.SearchPrincipals(context, web, owner, targetSource, PrincipalSource.All, null, 2);
                context.ExecuteQuery();

                if (principalInfos.Count > 0)
                //if (principalInfos.Value != null)
                {
                    var info = principalInfos[0];
                    //var info = principalInfos.Value;

                    targetSources[targetSource] = info;

                    if (targetSource == PrincipalType.User || targetSource == PrincipalType.SecurityGroup)
                    {
                        result = web.EnsureUser(info.LoginName);
                    }

                    if (targetSource == PrincipalType.SharePointGroup)
                    {
                        result = web.SiteGroups.GetById(info.PrincipalId);
                    }

                    context.Load(result);
                    context.ExecuteQuery();

                    // nic, found, break, profit!
                    break;
                }
            }

            return(result);
        }
Beispiel #7
0
 /// <summary>
 /// Loads values within a specified SharePoint object from the server.
 /// </summary>
 /// <param name="context">The Client Rutime Context object representing the client connection with the server.</param>
 /// <param name="obj">The object to populate the values of.</param>
 static public void Load(ClientRuntimeContext context, ClientObject obj)
 {
     if (context != null && obj != null)
     {
         context.Load(obj);
         context.ExecuteQuery();
     }
 }
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500)
        {
            if (clientContext is PnPClientContext)
            {
                retryCount = (clientContext as PnPClientContext).RetryCount;
                delay      = (clientContext as PnPClientContext).Delay;
            }

            int retryAttempts   = 0;
            int backoffInterval = delay;

            if (retryCount <= 0)
            {
                throw new ArgumentException("Provide a retry count greater than zero.");
            }

            if (delay <= 0)
            {
                throw new ArgumentException("Provide a delay greater than zero.");
            }

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    // If the customer is not using the clienttag then fill with the PnP Core library tag
                    if (String.IsNullOrEmpty(clientContext.ClientTag))
                    {
                        clientContext.ClientTag = GetCoreVersionTag();
                    }
                    clientContext.ExecuteQuery();
                    return;
                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        Debug.WriteLine("CSOM request frequency exceeded usage limits. Sleeping for {0} seconds before retrying.", backoffInterval);

                        //Add delay for retry
                        Thread.Sleep(backoffInterval);

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
        }
Beispiel #9
0
 /// <summary>
 /// Check if the property is loaded on the site object, if not the site object will be reloaded
 /// </summary>
 /// <param name="cc">Context to execute upon</param>
 /// <param name="site">Site to execute upon</param>
 /// <param name="propertyToCheck">Property to check</param>
 /// <returns>A reloaded site object</returns>
 public static Site EnsureSite(ClientRuntimeContext cc, Site site, string propertyToCheck)
 {
     if (!site.IsObjectPropertyInstantiated(propertyToCheck))
     {
         // get instances to root web, since we are processing currently sub site
         cc.Load(site);
         cc.ExecuteQuery();
     }
     return site;
 }
Beispiel #10
0
 /// <summary>
 /// Check if the property is loaded on the web object, if not the web object will be reloaded
 /// </summary>
 /// <param name="cc">Context to execute upon</param>
 /// <param name="web">Web to execute upon</param>
 /// <param name="propertyToCheck">Property to check</param>
 /// <returns>A reloaded web object</returns>
 public static Web EnsureWeb(ClientRuntimeContext cc, Web web, string propertyToCheck)
 {
     if (!web.IsObjectPropertyInstantiated(propertyToCheck))
     {
         // get instances to root web, since we are processing currently sub site
         cc.Load(web);
         cc.ExecuteQuery();
     }
     return web;
 }
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500)
        {
            if (clientContext is PnPClientContext)
            {
                retryCount = (clientContext as PnPClientContext).RetryCount;
                delay      = (clientContext as PnPClientContext).Delay;
            }

            int retryAttempts   = 0;
            int backoffInterval = delay;

            if (retryCount <= 0)
            {
                throw new ArgumentException("Provide a retry count greater than zero.");
            }

            if (delay <= 0)
            {
                throw new ArgumentException("Provide a delay greater than zero.");
            }

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    // Make CSOM request more reliable by disabling the return value cache. Given we
                    // often clone context objects and the default value is
                    clientContext.DisableReturnValueCache = true;

                    clientContext.ExecuteQuery();
                    return;
                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        //Add delay for retry
                        Thread.Sleep(backoffInterval);

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
        }
 protected virtual void InternalExecuteQuery(ClientRuntimeContext context)
 {
     if (CustomExecuteQueryHandler != null)
     {
         CustomExecuteQueryHandler(context);
     }
     else
     {
         context.ExecuteQuery();
     }
 }
Beispiel #13
0
        public static List <string> ShowAllLists(this Web web)
        {
            ClientRuntimeContext ctx = web.Context;

            ctx.Load(web.Lists);
            ctx.ExecuteQuery();

            var listTitles = web.Lists.Select(l => l.Title).ToList();

            return(listTitles);
        }
Beispiel #14
0
        /// <summary>
        /// Gets the CookieCollection by the cookie name. If no cookieNames are passed in it returns all cookies
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="cookieNames"></param>
        /// <returns></returns>
        internal static CookieCollection GetCookieCollection(this ClientRuntimeContext clientContext, IReadOnlyCollection <string> cookieNames)
        {
            CookieCollection cookieCollection = null;

            void Handler(object sender, WebRequestEventArgs e)
            => cookieCollection = HandleWebRequest(e, cookieNames);

            clientContext.ExecutingWebRequest += Handler;
            clientContext.ExecuteQuery();
            clientContext.ExecutingWebRequest -= Handler;

            return(cookieCollection);
        }
Beispiel #15
0
        private static bool CheckForDefaultTimeSlotList(ClientRuntimeContext clientContext, List spList)
        {
            var query = new CamlQuery()
            {
                ViewXml = "<View><Query><Where><IsNotNull><FieldRef Name='TimeSlot'/></IsNotNull></Where></Query><RowLimit>25</RowLimit><ViewFields><FieldRef Name='ID'/></ViewFields></View>"
            };
            var listItems = spList.GetItems(query);

            clientContext.Load(listItems);
            clientContext.ExecuteQuery();

            return(listItems.Count != 0);
        }
Beispiel #16
0
        /// <summary>
        /// Set permission to the specified list item
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="AssignUserEmails">User emails to give permission</param>
        /// <param name="listName">List name</param>
        /// <param name="listItemId">Unique list item id to break item level permission</param>
        /// <param name="permissions">Permissions for the users</param>
        /// <returns>Status of the unique item level permission assignment operation</returns>
        public static bool SetItemPermission(ClientContext clientContext, IList <IList <string> > AssignUserEmails, string listName, int listItemId, IList <string> permissions)
        {
            bool result = false;

            if (null != clientContext)
            {
                ClientRuntimeContext clientRuntimeContext = clientContext;
                ListItem             listItem             = clientContext.Web.Lists.GetByTitle(listName).GetItemById(listItemId);
                clientContext.Load(listItem, item => item.HasUniqueRoleAssignments);
                clientContext.ExecuteQuery();
                if (listItem.HasUniqueRoleAssignments && null != permissions && null != AssignUserEmails && permissions.Count == AssignUserEmails.Count)
                {
                    int position = 0;
                    foreach (string roleName in permissions)
                    {
                        IList <string> assignUserEmails = AssignUserEmails[position];
                        if (!string.IsNullOrWhiteSpace(roleName) && null != assignUserEmails)
                        {
                            RoleDefinition roleDefinition = clientContext.Web.RoleDefinitions.GetByName(roleName);
                            foreach (string user in assignUserEmails)
                            {
                                if (!string.IsNullOrWhiteSpace(user))
                                {
                                    /////get the user object
                                    Principal userPrincipal = clientContext.Web.EnsureUser(user.Trim());
                                    /////create the role definition binding collection
                                    RoleDefinitionBindingCollection roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(clientRuntimeContext);
                                    /////add the role definition to the collection
                                    roleDefinitionBindingCollection.Add(roleDefinition);
                                    /////create a RoleAssigment with the user and role definition
                                    listItem.RoleAssignments.Add(userPrincipal, roleDefinitionBindingCollection);
                                }
                            }
                            /////execute the query to add everything
                            clientRuntimeContext.ExecuteQuery();
                        }
                        position++;
                    }
                    ///// Success. Return a success code
                    result = false;
                }
            }
            return(result);
        }
Beispiel #17
0
        public static string GetAccessToken(ClientRuntimeContext clientContext)
        {
            string accessToken = null;
            EventHandler <WebRequestEventArgs> handler = (s, e) =>
            {
                string authorization = e.WebRequestExecutor.RequestHeaders["Authorization"];
                if (!string.IsNullOrEmpty(authorization))
                {
                    accessToken = authorization.Replace("Bearer ", string.Empty);
                }
            };

            // Issue a dummy request to get it from the Authorization header
            clientContext.ExecutingWebRequest += handler;
            clientContext.ExecuteQuery();
            clientContext.ExecutingWebRequest -= handler;

            return(accessToken);
        }
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500)
        {
            int retryAttempts = 0;
            int backoffInterval = delay;
            if (retryCount <= 0)
                throw new ArgumentException("Provide a retry count greater than zero.");

            if (delay <= 0)
                throw new ArgumentException("Provide a delay greater than zero.");

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    clientContext.ExecuteQuery();
                    return;

                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        Debug.WriteLine("CSOM request frequency exceeded usage limits. Sleeping for {0} seconds before retrying.", backoffInterval);

                        //Add delay for retry
                        Thread.Sleep(backoffInterval);

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
        }
Beispiel #19
0
        private static List <TimeregWithTimeslot> GetTopTimeregsWithTimeslot(ClientRuntimeContext clientContext, List spList, Toolkit tk)
        {
            var rowLimit = 250;
            var query    = new CamlQuery()
            {
                ViewXml = $@"<View><Query><Where><IsNotNull><FieldRef Name='{tk.TimeslotFieldName}'/></IsNotNull></Where><OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy></Query><ViewFields><FieldRef Name='Sag_x003a_Sags_x0020_Id' /><FieldRef Name='{tk.TimeslotFieldName}' /></ViewFields><RowLimit>{rowLimit}</RowLimit></View>"
            };

            var listItems = spList.GetItems(query);

            clientContext.Load(listItems);
            clientContext.ExecuteQuery();

            var listOfTimeregsWithTimelots = new List <TimeregWithTimeslot>();

            foreach (var item in listItems)
            {
                var timeregWithTimeslot = new TimeregWithTimeslot
                {
                    Timeslot = tk.TimeslotIsFieldLookup
                        ? (from field in item.FieldValues
                           where field.Key == tk.TimeslotFieldName
                           select((FieldLookupValue)field.Value).LookupValue).Single()
                        : (from field in item.FieldValues
                           where field.Key == tk.TimeslotFieldName
                           select field.Value.ToString()).Single(),
                    TimeslotId = tk.TimeslotIsFieldLookup
                        ? (from field in item.FieldValues
                           where field.Key == tk.TimeslotFieldName
                           select((FieldLookupValue)field.Value).LookupId).Single()
                        : -1,
                    CaseId = (from field in item.FieldValues
                              where field.Key == "Sag_x003a_Sags_x0020_Id"
                              select ExtractCaseIdFromField(((FieldLookupValue)field.Value).LookupValue)).Single()
                };

                listOfTimeregsWithTimelots.Add(timeregWithTimeslot);
            }

            return(listOfTimeregsWithTimelots);
        }
        private static IList<ListItem> GetAllItems(ClientRuntimeContext context, List list, int pageSize = MaxListPageSize)
        {
            ListItemCollectionPosition position = null;
            IEnumerable<ListItem> results = Enumerable.Empty<ListItem>();

            do
            {
                var query = new CamlQuery
                {
                    ListItemCollectionPosition = position,
                    ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query></Query><RowLimit>{0}</RowLimit></View>", pageSize)
                };

                var items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQuery();

                position = items.ListItemCollectionPosition;
                results = results.Concat(items);
            }
            while (position != null);

            return results.ToList();
        }
Beispiel #21
0
        private static List<string> ParseSubTerms(string subTermPath, Term term, bool includeId, string delimiter, ClientRuntimeContext clientContext)
        {
            List<string> items = new List<string>();
            if (term.ServerObjectIsNull == null || term.ServerObjectIsNull == false)
            {
                clientContext.Load(term.Terms);
                clientContext.ExecuteQuery();
            }

            foreach (Term subTerm in term.Terms)
            {
                //ClientResult<string> termName = TaxonomyItem.NormalizeName(clientContext, subTerm.Name);
                //clientContext.ExecuteQuery();
                string termName = DenormalizeName(subTerm.Name);
                string termPath = string.Format("{0}{3}{1}{2}", subTermPath, termName, (includeId) ? string.Format(";#{0}", subTerm.Id.ToString()) : "", delimiter);

                items.Add(termPath);

                if (term.TermsCount > 0)
                {
                    items.AddRange(ParseSubTerms(termPath, subTerm, includeId, delimiter, clientContext));
                }

            }
            return items;
        }
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500)
        {
            int retryAttempts = 0;
            int backoffInterval = delay;
            if (retryCount <= 0)
                throw new ArgumentException("Provide a retry count greater than zero.");

            if (delay <= 0)
                throw new ArgumentException("Provide a delay greater than zero.");

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    // Make CSOM request more reliable by disabling the return value cache. Given we
                    // often clone context objects and the default value is
            #if !ONPREMISES
                    clientContext.DisableReturnValueCache = true;
            #elif SP2016
                    clientContext.DisableReturnValueCache = true;
            #endif
                    clientContext.ExecuteQuery();
                    return;
                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        //Add delay for retry
                        Thread.Sleep(backoffInterval);

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
        }
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500)
        {
            var clientTag = string.Empty;
            if (clientContext is PnPClientContext)
            {
                retryCount = (clientContext as PnPClientContext).RetryCount;
                delay = (clientContext as PnPClientContext).Delay;
                clientTag = (clientContext as PnPClientContext).ClientTag;
            }

            int retryAttempts = 0;
            int backoffInterval = delay;
            if (retryCount <= 0)
                throw new ArgumentException("Provide a retry count greater than zero.");

            if (delay <= 0)
                throw new ArgumentException("Provide a delay greater than zero.");

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    // ClientTag property is limited to 32 chars
                    if (string.IsNullOrEmpty(clientTag))
                    {
                        clientTag = $"{PnPCoreUtilities.PnPCoreVersionTag}:{GetCallingPnPMethod()}";
                    }
                    if (clientTag.Length > 32)
                    {
                        clientTag = clientTag.Substring(0, 32);
                    }
                    clientContext.ClientTag = clientTag;

                    // Make CSOM request more reliable by disabling the return value cache. Given we
                    // often clone context objects and the default value is
            #if !ONPREMISES
                    clientContext.DisableReturnValueCache = true;
            #elif SP2016
                    clientContext.DisableReturnValueCache = true;
            #endif
                    clientContext.ExecuteQuery();
                    return;
                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        Log.Warning(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetry, backoffInterval);

                        //Add delay for retry
                        Thread.Sleep(backoffInterval);

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetryException, wex.ToString());
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
        }
        private void ProcessFeature(
                    object modelHost,
                    ClientRuntimeContext context,
                    FeatureCollection features,
                    FeatureDefinition featureModel,
                    Microsoft.SharePoint.Client.FeatureDefinitionScope scope)
        {
            var currentFeature = GetFeature(features, featureModel);
            var featureActivated = IsFeatureActivated(features, featureModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentFeature,
                ObjectType = typeof(Feature),
                ObjectDefinition = featureModel,
                ModelHost = modelHost
            });

            if (!featureActivated)
            {
                Feature tmpFeature;

                if (featureModel.Enable)
                {
                    tmpFeature = features.Add(featureModel.Id, featureModel.ForceActivate, scope);
                    context.ExecuteQuery();
                }
                else
                {
                    tmpFeature = GetFeature(features, featureModel);
                }

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = tmpFeature,
                    ObjectType = typeof(Feature),
                    ObjectDefinition = featureModel,
                    ModelHost = modelHost
                });
            }
            else
            {
                if (featureModel.Enable && featureModel.ForceActivate)
                {
                    var f = features.Add(featureModel.Id, featureModel.ForceActivate, scope);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = f,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });

                    context.ExecuteQuery();
                }
                else if (!featureModel.Enable)
                {
                    features.Remove(featureModel.Id, featureModel.ForceActivate);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = null,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });

                    context.ExecuteQuery();
                }
                else
                {
                    var tmpFeature = GetFeature(features, featureModel);

                    InvokeOnModelEvent(this, new ModelEventArgs
                    {
                        CurrentModelNode = null,
                        Model = null,
                        EventType = ModelEventType.OnProvisioned,
                        Object = tmpFeature,
                        ObjectType = typeof(Feature),
                        ObjectDefinition = featureModel,
                        ModelHost = modelHost
                    });
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// Assign permissions to the list
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="list">List object</param>
        /// <param name="userList">User list object</param>
        internal static void AssignListPermissions(ClientContext clientContext, List list, List <string> userList)
        {
            if (null != clientContext && null != list)
            {
                try
                {
                    Web web = clientContext.Web;
                    clientContext.Load(web, item => item.SiteGroups);
                    clientContext.Load(list, l => l.HasUniqueRoleAssignments);
                    clientContext.ExecuteQuery();
                    if (list.HasUniqueRoleAssignments)
                    {
                        ClientRuntimeContext clientRuntimeContext = clientContext;
                        Principal            userPrincipal        = clientContext.Web.AssociatedOwnerGroup;
                        string         roleName       = ConfigurationManager.AppSettings["Role"];
                        RoleDefinition roleDefinition = clientContext.Web.RoleDefinitions.GetByName(roleName);
                        RoleDefinitionBindingCollection roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(clientRuntimeContext);
                        /////add the role definition to the collection
                        roleDefinitionBindingCollection.Add(roleDefinition);
                        /////create a RoleAssigment with the owner group and role definition
                        list.RoleAssignments.Add(userPrincipal, roleDefinitionBindingCollection);
                        clientRuntimeContext.ExecuteQuery();
                    }

                    // Assign permissions to users
                    if (null != userList && 0 < userList.Count)
                    {
                        string roleName = ConfigurationManager.AppSettings["ReadRole"];
                        foreach (string userItem in userList)
                        {
                            try
                            {
                                Principal user = null;
                                user = web.SiteGroups.Where(groupItem => groupItem.Title == userItem).FirstOrDefault <Principal>();
                                if (null == user)
                                {
                                    user = web.EnsureUser(userItem);
                                }

                                if (null != user)
                                {
                                    RoleDefinition roleDefinition = clientContext.Web.RoleDefinitions.GetByName(roleName);
                                    RoleDefinitionBindingCollection roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(clientContext);
                                    // add the role definition to the collection
                                    roleDefinitionBindingCollection.Add(roleDefinition);
                                    list.RoleAssignments.Add(user, roleDefinitionBindingCollection);
                                    clientContext.ExecuteQuery();
                                }
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, Constants.AssigningPermissionsUsersExceptionMessage, userItem, exception.Message));
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    ErrorLogger.DisplayErrorMessage(string.Format(CultureInfo.InvariantCulture, Constants.AssigningPermissionsExceptionMessage, Constants.ConfigurationList, exception.Message));
                }
            }
        }
Beispiel #26
0
        private static void ExecuteQueryImplementation(ClientRuntimeContext clientContext, int retryCount = 10, int delay = 500, string userAgent = null)
#endif
        {
#if !ONPREMISES
            await new SynchronizationContextRemover();
#endif

            var clientTag = string.Empty;
            if (clientContext is PnPClientContext)
            {
                retryCount = (clientContext as PnPClientContext).RetryCount;
                delay      = (clientContext as PnPClientContext).Delay;
                clientTag  = (clientContext as PnPClientContext).ClientTag;
            }

            int retryAttempts   = 0;
            int backoffInterval = delay;
            if (retryCount <= 0)
            {
                throw new ArgumentException("Provide a retry count greater than zero.");
            }

            if (delay <= 0)
            {
                throw new ArgumentException("Provide a delay greater than zero.");
            }

            // Do while retry attempt is less than retry count
            while (retryAttempts < retryCount)
            {
                try
                {
                    clientContext.ClientTag = SetClientTag(clientTag);

                    // Make CSOM request more reliable by disabling the return value cache. Given we
                    // often clone context objects and the default value is
#if !ONPREMISES
                    clientContext.DisableReturnValueCache = true;
#elif SP2016
                    clientContext.DisableReturnValueCache = true;
#endif
                    // Add event handler to "insert" app decoration header to mark the PnP Sites Core library as a known application
                    EventHandler <WebRequestEventArgs> appDecorationHandler = AttachRequestUserAgent(userAgent);

                    clientContext.ExecutingWebRequest += appDecorationHandler;

                    // DO NOT CHANGE THIS TO EXECUTEQUERYRETRY
#if !ONPREMISES
#if !NETSTANDARD2_0
                    await clientContext.ExecuteQueryAsync();
#else
                    clientContext.ExecuteQuery();
#endif
#else
                    clientContext.ExecuteQuery();
#endif

                    // Remove the app decoration event handler after the executequery
                    clientContext.ExecutingWebRequest -= appDecorationHandler;

                    return;
                }
                catch (WebException wex)
                {
                    var response = wex.Response as HttpWebResponse;
                    // Check if request was throttled - http status code 429
                    // Check is request failed due to server unavailable - http status code 503
                    if (response != null && (response.StatusCode == (HttpStatusCode)429 || response.StatusCode == (HttpStatusCode)503))
                    {
                        Log.Warning(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetry, backoffInterval);
                        //Add delay for retry
#if !ONPREMISES
                        await Task.Delay(backoffInterval);
#else
                        Thread.Sleep(backoffInterval);
#endif

                        //Add to retry count and increase delay.
                        retryAttempts++;
                        backoffInterval = backoffInterval * 2;
                    }
                    else
                    {
                        Log.Error(Constants.LOGGING_SOURCE, CoreResources.ClientContextExtensions_ExecuteQueryRetryException, wex.ToString());
                        throw;
                    }
                }
            }
            throw new MaximumRetryAttemptedException($"Maximum retry attempts {retryCount}, has be attempted.");
        }
Beispiel #27
0
 /// <summary>
 /// Loads values within a specified SharePoint object from the server.
 /// </summary>
 /// <param name="context">The Client Rutime Context object representing the client connection with the server.</param>
 /// <param name="obj">The object to populate the values of.</param>
 public static void Load(ClientRuntimeContext context, ClientObject obj)
 {
     if (context != null && obj != null)
     {
         context.Load(obj);
         context.ExecuteQuery();
     }
 }
        private Principal ResolvePrincipal(ClientRuntimeContext context, Web web, string owner)
        {
            Principal result = null;

            var targetSources = new Dictionary<PrincipalType, PrincipalInfo>();

            // owner might be only a user or sharepoint group
            // making a few attempts and checking NULL ref later in the code
            targetSources.Add(PrincipalType.SharePointGroup, null);
            targetSources.Add(PrincipalType.User, null);

            foreach (var targetSource in targetSources.Keys)
            {
                // ResolvePrincipal != SearchPrincipals, at all!

                //var principalInfos = Utility.ResolvePrincipal(context, web, owner, targetSource, PrincipalSource.All, null, false);
                var principalInfos = Utility.SearchPrincipals(context, web, owner, targetSource, PrincipalSource.All, null, 2);
                context.ExecuteQuery();

                if (principalInfos.Count > 0)
                //if (principalInfos.Value != null)
                {
                    var info = principalInfos[0];
                    //var info = principalInfos.Value;

                    targetSources[targetSource] = info;

                    if (targetSource == PrincipalType.User || targetSource == PrincipalType.SecurityGroup)
                        result = web.EnsureUser(info.LoginName);

                    if (targetSource == PrincipalType.SharePointGroup)
                        result = web.SiteGroups.GetById(info.PrincipalId);

                    context.Load(result);
                    context.ExecuteQuery();

                    // nic, found, break, profit!
                    break;
                }
            }

            return result;
        }
        private static Field GetLookupField(ClientRuntimeContext sourceContext, List sourceList, string lookupName)
        {
            var sourceFields = sourceList.Fields;
            sourceContext.Load(sourceFields);
            sourceContext.ExecuteQuery();

            return sourceFields.ToList().SingleOrDefault(f => f.Title == lookupName);
        }
 private static List GetList(ClientRuntimeContext context, Web web, Guid listId)
 {
     var sourceList = web.Lists.GetById(listId);
     context.Load(sourceList);
     context.ExecuteQuery();
     return sourceList;
 }
 private static List GetList(ClientRuntimeContext context, Web web, string listTitle)
 {
     var sourceList = web.Lists.GetByTitle(listTitle);
     context.Load(sourceList);
     context.ExecuteQuery();
     return sourceList;
 }