private static List GetList(ClientRuntimeContext context, Web web, string listTitle)
 {
     var sourceList = web.Lists.GetByTitle(listTitle);
     context.Load(sourceList);
     context.ExecuteQuery();
     return sourceList;
 }
        public override void ExecuteQuery(ClientRuntimeContext context)
        {
            var currentRetryCount = 0;
            var currentRetryDelayInMilliseconds = ExecuteQueryDelayInMilliseconds;

            Exception lastException = null;

            while (currentRetryCount < ExecuteQueryRetryAttempts)
            {
                try
                {
                    InternalExecuteQuery(context);
                    return;
                }
                catch (Exception ex)
                {
                    lastException = ex;

                    if (ShouldRetryExecuteQuery(ex))
                    {
                        currentRetryCount++;
                        currentRetryDelayInMilliseconds = GetNextExecuteQueryDelayInMilliseconds(currentRetryDelayInMilliseconds);

                        Thread.Sleep(currentRetryDelayInMilliseconds);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            var message = string.Format("ClientRuntimeContext.ExecuteQuery() exceeded [{0}] retry attempts. Check InnerException for the last returned exception.", ExecuteQueryRetryAttempts);
            throw new SPMeta2Exception(message, lastException);
        }
        public override void ExecuteQuery(ClientRuntimeContext context)
        {
            var currentRetryCount = 0;
            var currentRetryDelayInMilliseconds = ExecuteQueryDelayInMilliseconds;

            while (currentRetryCount < ExecuteQueryRetryAttempts)
            {
                try
                {
                    InternalExecuteQuery(context);
                    return;
                }
                catch (Exception ex)
                {
                    if (ShouldRetryExecuteQuery(ex))
                    {
                        currentRetryCount++;
                        currentRetryDelayInMilliseconds = GetNextExecuteQueryDelayInMilliseconds(currentRetryDelayInMilliseconds);

                        Thread.Sleep(currentRetryDelayInMilliseconds);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            throw new SPMeta2Exception(string.Format("ClientRuntimeContext.ExecuteQuery() exceeded [{0}] retry attempts.", ExecuteQueryDelayInMilliseconds));
        }
示例#4
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();
     }
 }
 /// <summary>
 /// Check if all tokens where replaced. If the field is a taxonomy field then we will check for the values of the referenced termstore and termset. 
 /// </summary>
 /// <param name="fieldXml">The xml to parse</param>
 /// <param name="parser"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 protected static bool IsFieldXmlValid(string fieldXml, TokenParser parser, ClientRuntimeContext context)
 {
     var isValid = true;
     var leftOverTokens = parser.GetLeftOverTokens(fieldXml);
     if (!leftOverTokens.Any())
     {
         var fieldElement = XElement.Parse(fieldXml);
         if (fieldElement.Attribute("Type").Value == "TaxonomyFieldType")
         {
             var termStoreIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='SspId']/Value");
             if (termStoreIdElement != null)
             {
                 var termStoreId = Guid.Parse(termStoreIdElement.Value);
                 TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(context);
                 try
                 {
                     taxSession.EnsureProperty(t => t.TermStores);
                     var store = taxSession.TermStores.GetById(termStoreId);
                     context.Load(store);
                     context.ExecuteQueryRetry();
                     if (store.ServerObjectIsNull.HasValue && !store.ServerObjectIsNull.Value)
                     {
                         var termSetIdElement = fieldElement.XPathSelectElement("//ArrayOfProperty/Property[Name='TermSetId']/Value");
                         if (termSetIdElement != null)
                         {
                             var termSetId = Guid.Parse(termSetIdElement.Value);
                             try
                             {
                                 var termSet = store.GetTermSet(termSetId);
                                 context.Load(termSet);
                                 context.ExecuteQueryRetry();
                                 isValid = termSet.ServerObjectIsNull.HasValue && !termSet.ServerObjectIsNull.Value;
                             }
                             catch (Exception)
                             {
                                 isValid = false;
                             }
                         }
                     }
                 }
                 catch (Exception)
                 {
                     isValid = false;
                 }
             }
             else
             {
                 isValid = false;
             }
         }
     }
     else
     {
         //Some tokens where not replaced
         isValid = false;
     }
     return isValid;
 }
示例#6
0
        /// <summary>
        /// Returns the current search configuration for the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchSettingsObjectLevel"></param>
        /// <returns></returns>
        private static string GetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchSettingsObjectLevel)
        {
            SearchConfigurationPortability sconfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchSettingsObjectLevel);

            ClientResult<string> configresults = sconfig.ExportSearchConfiguration(owner);
            context.ExecuteQueryRetry();

            return configresults.Value;
        }
示例#7
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;
 }
示例#8
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;
 }
 protected virtual void InternalExecuteQuery(ClientRuntimeContext context)
 {
     if (CustomExecuteQueryHandler != null)
     {
         CustomExecuteQueryHandler(context);
     }
     else
     {
         context.ExecuteQuery();
     }
 }
示例#10
0
        private static KeywordQuery GetKeywordQuery(string location, ClientRuntimeContext context)
        {
            KeywordQuery keywordQuery = new KeywordQuery(context);

            keywordQuery.QueryText = string.Format(CultureInfo.InvariantCulture, "Path=\"{0}\"", new object[]
            {
                location
            });
            keywordQuery.RowLimit = 5;
            keywordQuery.SelectProperties.Add("WebId");
            keywordQuery.SelectProperties.Add("SiteId");
            keywordQuery.SelectProperties.Add("contentclass");
            keywordQuery.SelectProperties.Add("Path");
            keywordQuery.SelectProperties.Add("Title");
            SharepointCsomProvider.PopulateQueryDefaults(keywordQuery);
            return(keywordQuery);
        }
 private static bool IsTenantAdminSite(ClientRuntimeContext clientContext)
 {
     try
     {
         var tenant = new Tenant(clientContext);
         clientContext.ExecuteQueryRetry();
         return(true);
     }
     catch (ClientRequestException)
     {
         return(false);
     }
     catch (ServerException)
     {
         return(false);
     }
 }
示例#12
0
        /// <summary>
        /// Sets the search configuration at the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchObjectLevel"></param>
        /// <param name="searchConfiguration"></param>
        private static void SetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration)
        {
#if CLIENTSDKV15
            if (searchObjectLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
#endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel);

            // Import search configuration
            searchConfig.ImportSearchConfiguration(owner, searchConfiguration);
            context.Load(searchConfig);
            context.ExecuteQueryRetry();
        }
示例#13
0
        public Folder AddWithOverwrite(string url, bool overwrite)
        {
            ClientRuntimeContext context = base.Context;
            Folder folder = new Folder(context, new ObjectPathMethod(context, base.Path, "AddWithOverwrite", new object[]
            {
                url,
                overwrite
            }));

            folder.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(folder.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, folder);
            context.AddQuery(objectIdentityQuery);
            base.AddChild(folder);
            return(folder);
        }
示例#14
0
        /// <summary>
        /// Checks if the used ClientContext is app-only
        /// </summary>
        /// <param name="clientContext">The ClientContext to inspect</param>
        /// <returns>True if app-only, false otherwise</returns>
        public static bool IsAppOnlyWithDelegation(this ClientRuntimeContext clientContext)
        {
            // Set initial result to false
            var result = false;

            // Try to get an access token from the current context
            var accessToken = clientContext.GetAccessToken();

            // If any
            if (!String.IsNullOrEmpty(accessToken))
            {
                // Try to decode the access token
                try
                {
                    var token = new JwtSecurityToken(accessToken);

                    if (token.Audiences.Any(x => x.StartsWith(TokenHelper.SharePointPrincipal)))
                    {
                    }

                    // Search for the UPN claim, to see if we have user's delegation
                    var upn = token.Claims.FirstOrDefault(claim => claim.Type == "upn")?.Value;
                    if (!String.IsNullOrEmpty(upn))
                    {
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Maybe Newtonsoft.Json assembly is not loaded?", ex);
                }
            }
            else if (clientContext.Credentials == null)
            {
                result = false;
            }

            // As a final check, do we have the auth cookies?
            if (clientContext.HasAuthCookies())
            {
                result = false;
            }

            return(result);
        }
示例#15
0
        private static string ExtractResourceFolderServerRelativeUrl(Web web, ClientRuntimeContext context, ContentType currentContentType)
        {
            if (!currentContentType.IsPropertyAvailable("SchemaXml") || !web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                context.Load(web, w => w.ServerRelativeUrl);
                currentContentType.Context.Load(currentContentType, c => c.SchemaXml);
                currentContentType.Context.ExecuteQueryWithTrace();
            }

            var ctDocument    = XDocument.Parse(currentContentType.SchemaXml);
            var folderUrlNode = ctDocument.Descendants().FirstOrDefault(d => d.Name == "Folder");

            var webRelativeFolderUrl    = folderUrlNode.Attribute("TargetName").Value;
            var serverRelativeFolderUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, webRelativeFolderUrl);

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "webRelativeFolderUrl is: [{0}]", webRelativeFolderUrl);
            return(serverRelativeFolderUrl);
        }
示例#16
0
        public Field AddDependentLookup(string displayName, Field primaryLookupField, string lookupField)
        {
            ClientRuntimeContext context = base.Context;
            Field field = new Field(context, new ObjectPathMethod(context, base.Path, "AddDependentLookup", new object[]
            {
                displayName,
                primaryLookupField,
                lookupField
            }));

            field.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(field.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, field);
            context.AddQuery(objectIdentityQuery);
            base.AddChild(field);
            return(field);
        }
示例#17
0
        /// <summary>
        /// Set permission to the specified list item
        /// </summary>
        /// <param name="clientContext">Client context object</param>
        /// <param name="assignUserName">Users 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> > assignUserName, 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 != assignUserName && permissions.Count == assignUserName.Count)
                {
                    int position = 0;
                    foreach (string roleName in permissions)
                    {
                        IList <string> userName = assignUserName[position];
                        if (!string.IsNullOrWhiteSpace(roleName) && null != userName)
                        {
                            RoleDefinition roleDefinition = clientContext.Web.RoleDefinitions.GetByName(roleName);
                            foreach (string user in userName)
                            {
                                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);
        }
示例#18
0
        /// <summary>
        /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance
        /// </summary>
        /// <param name="clientContext">ClientContext to be cloned</param>
        /// <param name="siteUrl">Site url to be used for cloned ClientContext</param>
        /// <returns>A ClientContext object created for the passed site url</returns>
        public static ClientContext Clone(this ClientRuntimeContext clientContext, Uri siteUrl)
        {
            if (siteUrl == null)
            {
                throw new ArgumentException("siteUrl");
            }

            ClientContext clonedClientContext = new ClientContext(siteUrl)
            {
                AuthenticationMode = clientContext.AuthenticationMode,
                ClientTag          = clientContext.ClientTag,
                //DisableReturnValueCache = clientContext.DisableReturnValueCache
            };

//#if !ONPREMISES
//#elif SP2016
//            //clonedClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache;
//#endif


            // In case of using networkcredentials in on premises or SharePointOnlineCredentials in Office 365
            if (clientContext.Credentials != null)
            {
                clonedClientContext.Credentials = clientContext.Credentials;
            }
            else
            {
                //Take over the form digest handling setting
                clonedClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled;

                // In case of app only or SAML
                clonedClientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                {
                    // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of
                    // the new delegate method
                    MethodInfo methodInfo      = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
                    object[]   parametersArray = { webRequestEventArgs };
                    methodInfo.Invoke(clientContext, parametersArray);
                };
            }

            return(clonedClientContext);
        }
        public ClientResult <BasePermissions> GetUserEffectivePermissions(string userName)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && userName == null)
            {
                throw ClientUtility.CreateArgumentNullException("userName");
            }
            ClientAction clientAction = new ClientActionInvokeMethod(this, "GetUserEffectivePermissions", new object[]
            {
                userName
            });

            context.AddQuery(clientAction);
            ClientResult <BasePermissions> clientResult = new ClientResult <BasePermissions>();

            context.AddQueryIdAndResultObject(clientAction.Id, clientResult);
            return(clientResult);
        }
        /// <summary>
        /// Gets an access token from a <see cref="ClientContext"/> instance. Only works when using an add-in or app-only authentication flow.
        /// </summary>
        /// <param name="clientContext"><see cref="ClientContext"/> instance to obtain an access token for</param>
        /// <returns>Access token for the given <see cref="ClientContext"/> instance</returns>
        public static string GetAccessToken(this 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.ExecuteQueryRetry();
            clientContext.ExecutingWebRequest -= handler;

            return(accessToken);
        }
示例#21
0
        public ContentType GetById(string contentTypeId)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (contentTypeId == null)
                {
                    throw ClientUtility.CreateArgumentNullException("contentTypeId");
                }
                if (contentTypeId != null && !Regex.Match(contentTypeId, "0x(([1-9a-fA-F][0-9a-fA-F])|(0[1-9a-fA-F]))*(00([0-9a-fA-F][0-9a-fA-F]){16})*").Success)
                {
                    throw ClientUtility.CreateArgumentException("contentTypeId");
                }
            }
            object obj;
            Dictionary <string, ContentType> dictionary;

            if (base.ObjectData.MethodReturnObjects.TryGetValue("GetById", out obj))
            {
                dictionary = (Dictionary <string, ContentType>)obj;
            }
            else
            {
                dictionary = new Dictionary <string, ContentType>();
                base.ObjectData.MethodReturnObjects["GetById"] = dictionary;
            }
            ContentType contentType = null;

            if (!context.DisableReturnValueCache && dictionary.TryGetValue(contentTypeId, out contentType))
            {
                return(contentType);
            }
            contentType = new ContentType(context, new ObjectPathMethod(context, base.Path, "GetById", new object[]
            {
                contentTypeId
            }));
            if (!context.DisableReturnValueCache)
            {
                dictionary[contentTypeId] = contentType;
            }
            return(contentType);
        }
        /// <summary>
        /// Returns the number of pending requests
        /// </summary>
        /// <param name="clientContext">Client context to check the pending requests for</param>
        /// <returns>The number of pending requests</returns>
        public static int PendingRequestCount(this ClientRuntimeContext clientContext)
        {
            int count = 0;

            if (clientContext.HasPendingRequest)
            {
                var result = clientContext.PendingRequest.GetType().GetProperty("Actions", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
                if (result != null)
                {
                    var propValue = result.GetValue(clientContext.PendingRequest);
                    if (propValue != null)
                    {
                        count = (propValue as System.Collections.Generic.List <ClientAction>).Count;
                    }
                }
            }

            return(count);
        }
        public ClientResult <string> ExportWebPart(Guid webPartId)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && webPartId == Guid.Empty)
            {
                throw ClientUtility.CreateArgumentException("webPartId");
            }
            ClientAction clientAction = new ClientActionInvokeMethod(this, "ExportWebPart", new object[]
            {
                webPartId
            });

            context.AddQuery(clientAction);
            ClientResult <string> clientResult = new ClientResult <string>();

            context.AddQueryIdAndResultObject(clientAction.Id, clientResult);
            return(clientResult);
        }
示例#24
0
 public override WebRequestExecutor CreateWebRequestExecutor(ClientRuntimeContext context, string requestUrl)
 {
     if (RunAsIntegrationTest)
     {
         ComposedWebRequestExecutor executor = new ComposedWebRequestExecutor(new SPWebRequestExecutor(context, requestUrl));
         executor.OnRequestExecuted += OnRequestExecuted;
         executor.OnRequestExecuted += delegate(object sender, RequestExecutedArgs e)
         {
             IntegrationResponses.Add(new MockResponse()
             {
                 Body     = e.RequestBody,
                 Response = e.ResponseBody,
                 Verb     = "POST"
             });
         };
         return(executor);
     }
     return(new MockWebRequestExecutor(requestUrl, ResponseProvider));
 }
        protected virtual bool DetectSharePointOnlineContext(ClientRuntimeContext context)
        {
#if NET35
            return(false);
#endif

#if !NET35
            // checking based on the current assembly version
            // using hash to avoid performance degradation

            if (!Context2SharePointOnlineHash.ContainsKey(context))
            {
                Context2SharePointOnlineHash.Add(context, false);

                try
                {
                    // by assembly version
                    var version = AssemblyVersionService.GetAssemblyFileVersion(context.GetType().Assembly);

                    // 16.1.0.0 for SharePoint Online
                    // 16.0.0.0 for SharePoint 2016, we should be safe
                    // Major.Minor.Build.Revision
                    // currrent assembly? at least 16 (O365 / SharePoint 2016)
                    Context2SharePointOnlineHash[context] = version.Major == 16;

                    // if we talk to SharePoint 2016 from old, SP2013 CSOM
                    // SP2016 CSOM - taxonomy group cannot be found after provision #1103
                    // https://github.com/SubPointSolutions/spmeta2/issues/1103
                    if (context.ServerLibraryVersion.Major == 16)
                    {
                        Context2SharePointOnlineHash[context] = version.Major == 16;
                    }
                }
                catch (Exception e)
                {
                    // fallback
                    Context2SharePointOnlineHash[context] = context.Credentials is SharePointOnlineCredentials;
                }
            }

            return(Context2SharePointOnlineHash[context]);
#endif
        }
示例#26
0
        public Field GetByTitle(string title)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (title == null)
                {
                    throw ClientUtility.CreateArgumentNullException("title");
                }
                if (title != null && title.Length == 0)
                {
                    throw ClientUtility.CreateArgumentException("title");
                }
            }
            object obj;
            Dictionary <string, Field> dictionary;

            if (base.ObjectData.MethodReturnObjects.TryGetValue("GetByTitle", out obj))
            {
                dictionary = (Dictionary <string, Field>)obj;
            }
            else
            {
                dictionary = new Dictionary <string, Field>();
                base.ObjectData.MethodReturnObjects["GetByTitle"] = dictionary;
            }
            Field field = null;

            if (!context.DisableReturnValueCache && dictionary.TryGetValue(title, out field))
            {
                return(field);
            }
            field = new Field(context, new ObjectPathMethod(context, base.Path, "GetByTitle", new object[]
            {
                title
            }));
            if (!context.DisableReturnValueCache)
            {
                dictionary[title] = field;
            }
            return(field);
        }
        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));
        }
        /// <summary>
        /// Returns exception based on ClientRunTimeContext and ExceptionOptions objects
        /// </summary>
        /// <param name="exception">Exception object</param>
        /// <param name="cc">ClientRuntimeContext object</param>
        /// <param name="options">ExceptionOptions object</param>
        /// <returns>Returns exception as a string</returns>
        public static string ToDetailedString(this Exception exception, ClientRuntimeContext cc, ExceptionOptions options)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            var stringBuilder = new StringBuilder();

            AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);

            if (cc != null && !String.IsNullOrEmpty(cc.TraceCorrelationId))
            {
                AppendValue(stringBuilder, "TraceCorrelationId", cc.TraceCorrelationId, options);
            }

            foreach (PropertyInfo property in exception
                     .GetType()
                     .GetProperties()
                     .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
                     .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
                     .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
                     .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
            {
                var value = property.GetValue(exception, null);
                if (value == null && options.OmitNullProperties)
                {
                    if (options.OmitNullProperties)
                    {
                        continue;
                    }
                    else
                    {
                        value = string.Empty;
                    }
                }

                AppendValue(stringBuilder, property.Name, value, options);
            }

            return(stringBuilder.ToString().TrimEnd('\r', '\n'));
        }
        public RoleAssignment GetByPrincipal(Principal principalToFind)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && principalToFind == null)
            {
                throw ClientUtility.CreateArgumentNullException("principalToFind");
            }
            RoleAssignment roleAssignment = new RoleAssignment(context, new ObjectPathMethod(context, base.Path, "GetByPrincipal", new object[]
            {
                principalToFind
            }));

            roleAssignment.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(roleAssignment.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, roleAssignment);
            context.AddQuery(objectIdentityQuery);
            return(roleAssignment);
        }
示例#30
0
        public File Add(FileCreationInformation parameters)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (parameters == null)
                {
                    throw ClientUtility.CreateArgumentNullException("parameters");
                }
                if (parameters != null)
                {
                    if (parameters.Url == null)
                    {
                        throw ClientUtility.CreateArgumentNullException("parameters.Url");
                    }
                    Uri uri;
                    if (parameters.Url != null && !Uri.TryCreate(parameters.Url, UriKind.RelativeOrAbsolute, out uri))
                    {
                        throw ClientUtility.CreateArgumentException("parameters.Url");
                    }
                    if (parameters.Url != null && parameters.Url.Length < 1)
                    {
                        throw ClientUtility.CreateArgumentException("parameters.Url");
                    }
                }
            }
            File file = new File(context, new ObjectPathMethod(context, base.Path, "Add", new object[]
            {
                parameters
            }));

            file.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(file.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, file);
            context.AddQuery(objectIdentityQuery);
            base.AddChild(file);
            file.InitFromCreationInformation(parameters);
            return(file);
        }
        public WebPartDefinition AddWebPart(WebPart webPart, string zoneId, int zoneIndex)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (webPart == null)
                {
                    throw ClientUtility.CreateArgumentNullException("webPart");
                }
                if (zoneId == null)
                {
                    throw ClientUtility.CreateArgumentNullException("zoneId");
                }
                if (zoneId != null && zoneId.Length == 0)
                {
                    throw ClientUtility.CreateArgumentException("zoneId");
                }
                if (zoneId != null && zoneId.Length > 64)
                {
                    throw ClientUtility.CreateArgumentException("zoneId");
                }
                if (zoneIndex < 0)
                {
                    throw ClientUtility.CreateArgumentException("zoneIndex");
                }
            }
            WebPartDefinition webPartDefinition = new WebPartDefinition(context, new ObjectPathMethod(context, base.Path, "AddWebPart", new object[]
            {
                webPart,
                zoneId,
                zoneIndex
            }));

            webPartDefinition.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(webPartDefinition.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, webPartDefinition);
            context.AddQuery(objectIdentityQuery);
            return(webPartDefinition);
        }
示例#32
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);
        }
示例#33
0
 private static bool IsTenantAdminSite(ClientRuntimeContext clientContext)
 {
     if (clientContext.Url.ToLower().Contains(".sharepoint."))
     {
         return(clientContext.Url.ToLower().Contains("-admin.sharepoint."));
     }
     else
     {
         // fall back to old code in case of vanity domains
         try
         {
             var tenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(clientContext);
             clientContext.ExecuteQueryRetry();
             return(true);
         }
         catch (ServerException)
         {
             return(false);
         }
     }
 }
示例#34
0
        public Field Add(Field field)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && field == null)
            {
                throw ClientUtility.CreateArgumentNullException("field");
            }
            Field field2 = new Field(context, new ObjectPathMethod(context, base.Path, "Add", new object[]
            {
                field
            }));

            field2.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(field2.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, field2);
            context.AddQuery(objectIdentityQuery);
            base.AddChild(field2);
            return(field2);
        }
示例#35
0
        public Attachment AddUsingPath(ResourcePath filename, Stream contentStream)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient)
            {
                if (filename == null)
                {
                    throw ClientUtility.CreateArgumentNullException("filename");
                }
                if (contentStream == null)
                {
                    throw ClientUtility.CreateArgumentNullException("contentStream");
                }
            }
            return(new Attachment(context, new ObjectPathMethod(context, base.Path, "AddUsingPath", new object[]
            {
                filename,
                contentStream
            })));
        }
示例#36
0
        public ContentType AddExistingContentType(ContentType contentType)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && contentType == null)
            {
                throw ClientUtility.CreateArgumentNullException("contentType");
            }
            ContentType contentType2 = new ContentType(context, new ObjectPathMethod(context, base.Path, "AddExistingContentType", new object[]
            {
                contentType
            }));

            contentType2.Path.SetPendingReplace();
            ObjectIdentityQuery objectIdentityQuery = new ObjectIdentityQuery(contentType2.Path);

            context.AddQueryIdAndResultObject(objectIdentityQuery.Id, contentType2);
            context.AddQuery(objectIdentityQuery);
            base.AddChild(contentType2);
            return(contentType2);
        }
        public IList <ListItemFormUpdateValue> ValidateUpdateListItem(IList <ListItemFormUpdateValue> formValues, bool bNewDocumentUpdate, string checkInComment)
        {
            ClientRuntimeContext context = base.Context;

            if (base.Context.ValidateOnClient && formValues == null)
            {
                throw ClientUtility.CreateArgumentNullException("formValues");
            }
            ClientAction clientAction = new ClientActionInvokeMethod(this, "ValidateUpdateListItem", new object[]
            {
                formValues,
                bNewDocumentUpdate,
                checkInComment
            });

            context.AddQuery(clientAction);
            IList <ListItemFormUpdateValue> list = new List <ListItemFormUpdateValue>();

            context.AddQueryIdAndResultObject(clientAction.Id, new ClientListResultHandler <ListItemFormUpdateValue>(list));
            return(list);
        }
示例#38
0
        /// <summary>
        /// SharePointConnector constructor. Allows to directly set root folder and sub folder
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="connectionString">Site collection URL (e.g. https://yourtenant.sharepoint.com/sites/dev) </param>
        /// <param name="container">Library + folder that holds the files (mydocs/myfolder)</param>
        public SharePointConnector(ClientRuntimeContext clientContext, string connectionString, string container)
            : base()
        {
            if (clientContext == null)
            {
                throw new ArgumentNullException("clientContext");
            }

            if (String.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("connectionString");
            }

            if (String.IsNullOrEmpty(container))
            {
                throw new ArgumentException("container");
            }
            this.AddParameter(CLIENTCONTEXT, clientContext);
            this.AddParameterAsString(CONNECTIONSTRING, connectionString);
            this.AddParameterAsString(CONTAINER, container);
        }
示例#39
0
        public static async Task ExecuteQueryAsync(this ClientRuntimeContext clientContext, Action onSucceed,
                                                   Action <Exception> onFailed)
        {
            try
            {
                await ExecuteQueryAsync(clientContext);

                onSucceed?.Invoke();
            }
            catch (Exception ex)
            {
                if (onFailed != null)
                {
                    onFailed(ex);
                }
                else
                {
                    throw;
                }
            }
        }
示例#40
0
        /// <summary>
        /// SharePointConnector constructor. Allows to directly set root folder and sub folder
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="connectionString">Site collection URL (e.g. https://yourtenant.sharepoint.com/sites/dev) </param>
        /// <param name="container">Library + folder that holds the files (mydocs/myfolder)</param>
        public SharePointConnector(ClientRuntimeContext clientContext, string connectionString, string container)
            : base()
        {
            if (clientContext == null)
            {
                throw new ArgumentNullException("clientContext");
            }

            if (String.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("connectionString");
            }

            if (String.IsNullOrEmpty(container))
            {
                throw new ArgumentException("container");
            }
            this.AddParameter(CLIENTCONTEXT, clientContext);
            this.AddParameterAsString(CONNECTIONSTRING, connectionString);
            this.AddParameterAsString(CONTAINER, container);
        }
        /// <summary>
        /// Gets an access token from a <see cref="ClientContext"/> instance. Only works when using an add-in or app-only authentication flow.
        /// </summary>
        /// <param name="clientContext"><see cref="ClientContext"/> instance to obtain an access token for</param>
        /// <returns>Access token for the given <see cref="ClientContext"/> instance</returns>
        public static string GetAccessToken(this ClientRuntimeContext clientContext)
        {
            string accessToken = null;

            if (PnPProvisioningContext.Current != null)
            {
                accessToken = PnPProvisioningContext.Current.AcquireToken(new Uri(clientContext.Url).Authority, null);
            }
            else
            {
                if (clientContext.GetContextSettings().AuthenticationManager != null)
                {
                    var contextSettings = clientContext.GetContextSettings();
                    if (contextSettings.Type == ClientContextType.SharePointACSAppOnly)
                    {
                    }
                    else
                    {
                        accessToken = contextSettings.AuthenticationManager.GetAccessTokenAsync(clientContext.Url).GetAwaiter().GetResult();
                    }
                }
                else
                {
                    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);
        }
示例#42
0
        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();
        }
示例#43
0
        /// <summary>
        /// Get all sites that match the passed query. Batching is done in batches of 500 as this is compliant for both Office 365 as SharePoint on-premises
        /// </summary>
        /// <param name="cc">ClientContext object of an arbitrary site collection accessible by the defined enumeration username and password</param>
        /// <param name="keywordQueryValue">Query string</param>
        /// <returns>List of found site collections</returns>
        private static List<String> SiteSearch(ClientRuntimeContext cc, string keywordQueryValue)
        {
            List<String> sites = new List<String>();

            KeywordQuery keywordQuery = new KeywordQuery(cc);
            // Important to avoid trimming "similar" site collections
            keywordQuery.TrimDuplicates = false;

            if (keywordQueryValue.Length == 0)
            {
                keywordQueryValue = "contentclass:\"STS_Site\"";
            }

            int startRow = 0;
            int totalRows = 0;

            totalRows = ProcessQuery(cc, keywordQueryValue, sites, keywordQuery, startRow);

            if (totalRows > 0)
            {
                while (totalRows >= sites.Count)
                {
                    startRow += 500;
                    totalRows = ProcessQuery(cc, keywordQueryValue, sites, keywordQuery, startRow);
                }
            }

            return sites;
        }
示例#44
0
 protected string GetCurrentWebUrl(ClientRuntimeContext context, Web parentWeb, WebDefinition webModel)
 {
     var result = UrlUtility.CombineUrl(parentWeb.ServerRelativeUrl, webModel.Url);
     return result.ToLower();
 }
示例#45
0
        /// <summary>
        /// Sets the search configuration at the specified object level
        /// </summary>
        /// <param name="context"></param>
        /// <param name="searchObjectLevel"></param>
        /// <param name="searchConfiguration"></param>
        private static void SetSearchConfigurationImplementation(ClientRuntimeContext context, SearchObjectLevel searchObjectLevel, string searchConfiguration)
        {
#if CLIENTSDKV15
            if (searchObjectLevel == SearchObjectLevel.Ssa)
            {
                // Reference: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.search.portability.searchconfigurationportability_members.aspx
                throw new Exception("You cannot import customized search configuration settings to a Search service application (SSA).");
            }
#endif
            SearchConfigurationPortability searchConfig = new SearchConfigurationPortability(context);
            SearchObjectOwner owner = new SearchObjectOwner(context, searchObjectLevel);

            // Import search configuration
            searchConfig.ImportSearchConfiguration(owner, searchConfiguration);
            context.Load(searchConfig);
            context.ExecuteQueryRetry();
        }
示例#46
0
 private void SetCounter(ClientRuntimeContext ctx)
 {
     ctx.ExecutingWebRequest += (sender, args) =>
     {
         var counter = (int)SessionState.PSVariable.Get("WebRequestCounter").Value;
         counter++;
         SessionState.PSVariable.Set("WebRequestCounter", counter);
     };
 }
        private static string ExtractResourceFolderServerRelativeUrl(Web web, ClientRuntimeContext context, ContentType currentContentType)
        {
            if (!currentContentType.IsPropertyAvailable("SchemaXml")
                || !web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                context.Load(web, w => w.ServerRelativeUrl);
                currentContentType.Context.Load(currentContentType, c => c.SchemaXml);
                currentContentType.Context.ExecuteQueryWithTrace();
            }

            var ctDocument = XDocument.Parse(currentContentType.SchemaXml);
            var folderUrlNode = ctDocument.Descendants().FirstOrDefault(d => d.Name == "Folder");

            var webRelativeFolderUrl = folderUrlNode.Attribute("TargetName").Value;
            var serverRelativeFolderUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, webRelativeFolderUrl);

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "webRelativeFolderUrl is: [{0}]", webRelativeFolderUrl);
            return serverRelativeFolderUrl;
        }
示例#48
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;
        }
示例#49
0
        private Field EnsureField(ClientRuntimeContext context, Field currentField, FieldCollection fieldCollection,
            FieldDefinition fieldModel)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "EnsureField()");

            if (currentField == null)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionProcessingNewObject, "Current field is NULL. Creating new");

                var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel);

                var addFieldOptions = (AddFieldOptions)(int)fieldModel.AddFieldOptions;
                var resultField = fieldCollection.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions);

                if (PreloadProperties(resultField))
                {
                    context.ExecuteQueryWithTrace();
                }

                ProcessFieldProperties(resultField, fieldModel);

                return resultField;
            }
            else
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field");

                ProcessFieldProperties(currentField, fieldModel);

                return currentField;
            }
        }
        protected virtual Group ResolveSecurityGroup(SecurityGroupLinkDefinition securityGroupLinkModel, Web web, ClientRuntimeContext context)
        {
            Group securityGroup = null;

            if (securityGroupLinkModel.IsAssociatedMemberGroup)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedMemberGroup = true. Resolving AssociatedMemberGroup");

                context.Load(web, w => w.AssociatedMemberGroup);
                context.ExecuteQueryWithTrace();

                securityGroup = web.AssociatedMemberGroup;
            }
            else if (securityGroupLinkModel.IsAssociatedOwnerGroup)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedOwnerGroup = true. Resolving IsAssociatedOwnerGroup");

                context.Load(web, w => w.AssociatedOwnerGroup);
                context.ExecuteQueryWithTrace();

                securityGroup = web.AssociatedOwnerGroup;
            }
            else if (securityGroupLinkModel.IsAssociatedVisitorGroup)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "IsAssociatedVisitorGroup = true. Resolving IsAssociatedVisitorGroup");

                context.Load(web, w => w.AssociatedVisitorGroup);
                context.ExecuteQueryWithTrace();

                securityGroup = web.AssociatedVisitorGroup;
            }
            else if (!string.IsNullOrEmpty(securityGroupLinkModel.SecurityGroupName))
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving group by name: [{0}]", securityGroupLinkModel.SecurityGroupName);

                securityGroup = WebExtensions.FindGroupByName(web.SiteGroups, securityGroupLinkModel.SecurityGroupName);
            }
            else
            {
                TraceService.Error((int)LogEventId.ModelProvisionCoreCall,
                    "IsAssociatedMemberGroup/IsAssociatedOwnerGroup/IsAssociatedVisitorGroup/SecurityGroupName should be defined. Throwing SPMeta2Exception");

                throw new SPMeta2Exception("securityGroupLinkModel");
            }

            return securityGroup;
        }
示例#51
0
        private Field EnsureField(ClientRuntimeContext context, FieldCollection fieldCollection, FieldDefinition fieldModel)
        {
            var currentField = FindExistingField(fieldCollection, fieldModel.InternalName);

            if (currentField == null)
            {
                var fieldDef = string.Format(SiteFieldXmlTemplate,
                                             new string[]
                                                 {
                                                     fieldModel.Id.ToString("B"),
                                                     fieldModel.InternalName,
                                                     fieldModel.Title,
                                                     fieldModel.Title,
                                                     fieldModel.InternalName,
                                                     fieldModel.FieldType,
                                                     fieldModel.Group
                                                 });

                currentField = fieldCollection.AddFieldAsXml(fieldDef, false, AddFieldOptions.DefaultValue);
            }

            currentField.Title = fieldModel.Title;
            currentField.Description = fieldModel.Description ?? string.Empty;
            currentField.Group = fieldModel.Group ?? string.Empty;

            return currentField;
        }
        public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore,
            Site site,
            string termGroupName, Guid? termGroupId, bool? isSiteCollectionGroup,
            string termSetName, Guid? termSetId, int termSetLCID)
        {
            var storeContext = context;

            TermGroup currenGroup = null;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }

            if (!string.IsNullOrEmpty(termSetName))
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetByName(termSetName);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID);

                    storeContext.Load(termSets);
                    storeContext.ExecuteQueryWithTrace();

                    return termSets.FirstOrDefault();
                }
            }

            if (termSetId.HasGuidValue())
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetById(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = termStore.GetTermSet(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
            }

            return null;
        }
        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));
        }
示例#54
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cc">ClientContext object of an arbitrary site collection accessible by the defined enumeration username and password</param>
        /// <param name="keywordQueryValue">Query to execute</param>
        /// <param name="sites">List of found site collections</param>
        /// <param name="keywordQuery">KeywordQuery instance that will perform the actual queries</param>
        /// <param name="startRow">Row as of which we want to see the results</param>
        /// <returns>Total result rows of the query</returns>
        private static int ProcessQuery(ClientRuntimeContext cc, string keywordQueryValue, List<string> sites, KeywordQuery keywordQuery, int startRow)
        {
            int totalRows = 0;

            keywordQuery.QueryText = keywordQueryValue;
            keywordQuery.RowLimit = 500;
            keywordQuery.StartRow = startRow;
            keywordQuery.SelectProperties.Add("SPSiteUrl");
            keywordQuery.SortList.Add("SPSiteUrl", SortDirection.Ascending);
            SearchExecutor searchExec = new SearchExecutor(cc);
            ClientResult<ResultTableCollection> results = searchExec.ExecuteQuery(keywordQuery);
            cc.ExecuteQueryRetry();

            if (results != null)
            {
                if (results.Value[0].RowCount > 0)
                {
                    totalRows = results.Value[0].TotalRows;

                    foreach (var row in results.Value[0].ResultRows)
                    {
                        if (row["SPSiteUrl"] != null)
                        {
                            sites.Add(row["SPSiteUrl"].ToString());
                        }
                    }
                }
            }

            return totalRows;
        }
        private static Field CreateField(XElement fieldElement, ListInfo listInfo, TokenParser parser, string originalFieldXml, ClientRuntimeContext context, PnPMonitoredScope scope)
        {
            Field field = null;
            fieldElement = PrepareField(fieldElement);

            var fieldXml = parser.ParseString(fieldElement.ToString(), "~sitecollection", "~site");
            if (IsFieldXmlValid(parser.ParseString(originalFieldXml), parser, context))
            {
                field = listInfo.SiteList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddFieldInternalNameHint);
                listInfo.SiteList.Context.Load(field);
                listInfo.SiteList.Context.ExecuteQueryRetry();

                bool isDirty = false;
            #if !SP2013
                if (originalFieldXml.ContainsResourceToken())
                {
                    var originalFieldElement = XElement.Parse(originalFieldXml);
                    var nameAttributeValue = originalFieldElement.Attribute("DisplayName") != null ? originalFieldElement.Attribute("DisplayName").Value : "";
                    if (nameAttributeValue.ContainsResourceToken())
                    {
                        if (field.TitleResource.SetUserResourceValue(nameAttributeValue, parser))
                        {
                            isDirty = true;
                        }
                    }
                    var descriptionAttributeValue = originalFieldElement.Attribute("Description") != null ? originalFieldElement.Attribute("Description").Value : "";
                    if (descriptionAttributeValue.ContainsResourceToken())
                    {
                        if (field.DescriptionResource.SetUserResourceValue(descriptionAttributeValue, parser))
                        {
                            isDirty = true;
                        }
                    }
                }
            #endif
                if (isDirty)
                {
                    field.Update();
                    listInfo.SiteList.Context.ExecuteQueryRetry();
                }
            }
            else
            {
                // The field Xml was found invalid
                var tokenString = parser.GetLeftOverTokens(originalFieldXml).Aggregate(String.Empty, (acc, i) => acc + " " + i);
                scope.LogError("The field was found invalid: {0}", tokenString);
                throw new Exception(string.Format("The field was found invalid: {0}", tokenString));
            }
            return field;
        }
        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));
        }
 public static TermSet LookupTermSet(ClientRuntimeContext context, Site site,
     TermStore termStore, TaxonomyFieldDefinition taxFieldModel)
 {
     return LookupTermSet(context, termStore, site,
         taxFieldModel.TermGroupName, taxFieldModel.TermGroupId, taxFieldModel.IsSiteCollectionGroup,
         taxFieldModel.TermSetName, taxFieldModel.TermSetId, taxFieldModel.TermSetLCID);
 }
        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.ExecuteQueryWithTrace();

                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.ExecuteQueryWithTrace();

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

            return result;
        }
 public SharePointFolderErrorEntry(ClientRuntimeContext cc, ObjectPath op)
     : base(cc, op)
 {
 }
 public JsonSharePointTemplateProvider(ClientRuntimeContext cc, string connectionString, string container) :
     base(new SharePointConnector(cc, connectionString, container))
 {
 }