Skip to content

Commit

Permalink
New Core.Throttling sample for general throttling handling reference …
Browse files Browse the repository at this point in the history
…and few adjustments to other samples.
  • Loading branch information
VesaJuvonen committed Dec 1, 2014
1 parent c4100d2 commit d50100c
Show file tree
Hide file tree
Showing 27 changed files with 2,806 additions and 139 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Temp doc
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ClientId" value="9f88386f-a9b0-47ba-b59d-dd9902239c4e" />
<add key="ClientId" value="6d424fdc-a08d-4661-8a65-5205324cdc5e" />
<add key="ClientSecret" value="zT5KFBowr0H9Ptt6hPd9KJJFEQkPK3VXR2WNbbXfRc4=" />
</appSettings>
<system.serviceModel>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ClientId" value="943d8a7a-ca9c-4149-b580-8fdd199f44da" />
<add key="ClientId" value="f23277b8-9d46-4638-ac10-b2db8c7004b3" />
<add key="ClientSecret" value="g2L88vAVFSs2GjYVF+SLl9y7KcMG8/PKL/5K3ZF2ExM=" />
</appSettings>
<system.serviceModel>
Expand Down
22 changes: 22 additions & 0 deletions Samples/Core.Throttling/Core.Throttling.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Throttling", "Core.Throttling\Core.Throttling.csproj", "{F2228F43-CCDD-48BC-9808-B49CE412B513}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F2228F43-CCDD-48BC-9808-B49CE412B513}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F2228F43-CCDD-48BC-9808-B49CE412B513}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F2228F43-CCDD-48BC-9808-B49CE412B513}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F2228F43-CCDD-48BC-9808-B49CE412B513}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
74 changes: 74 additions & 0 deletions Samples/Core.Throttling/Core.Throttling/ClientContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;

namespace Core.Throttling
{
public static class ClientContextExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
/// <summary>
/// Extension method to invoke execute query with retry and exponential back off.
/// </summary>
/// <param name="context"></param>
/// <param name="retryCount">Maximum amount of retries before giving up.</param>
/// <param name="delay">Initial delay in milliseconds.</param>
public static void ExecuteQueryWithExponentialRetry(this ClientContext context, int retryCount, int 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
{
context.ExecuteQuery();
return;

}
catch (WebException wex)
{
var response = wex.Response as HttpWebResponse;
// Check if request was throttled - http status code 429
if (response != null && response.StatusCode == (HttpStatusCode)429)
{
// Output status to console. Should be changed as Debug.WriteLine for production usage.
Console.WriteLine(string.Format("CSOM request frequency exceeded usage limits. Sleeping for {0} seconds before retrying.",
backoffInterval));

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

//Add to retry count and increase delay.
retryAttempts++;
backoffInterval = backoffInterval * 2;
}
}
}
throw new MaximumRetryAttemptedException(string.Format("Maximum retry attempts {0}, has be attempted.", retryCount));
}
}


public class MaximumRetryAttemptedException : Exception
{
public MaximumRetryAttemptedException(string message)
: base(message)
{

}
}
}
103 changes: 103 additions & 0 deletions Samples/Core.Throttling/Core.Throttling/Core.Throttling.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{F2228F43-CCDD-48BC-9808-B49CE412B513}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Core.Throttling</RootNamespace>
<AssemblyName>Core.Throttling</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.IdentityModel.Extensions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=69c3241e6f0468ca, processorArchitecture=MSIL">
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Office.Client.Policy, Version=16.0.0.0" />
<Reference Include="Microsoft.Office.Client.TranslationServices, Version=16.0.0.0" />
<Reference Include="Microsoft.Online.SharePoint.Client.Tenant, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\OfficeDevPnPCore16.0.5.1030.7\lib\net45\Microsoft.Online.SharePoint.Client.Tenant.dll</HintPath>
</Reference>
<Reference Include="Microsoft.SharePoint.Client, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.DocumentManagement, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.Publishing, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.Search, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.Search.Applications, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.Taxonomy, Version=16.0.0.0" />
<Reference Include="Microsoft.SharePoint.Client.UserProfiles, Version=16.0.0.0" />
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="OfficeDevPnP.Core">
<HintPath>..\packages\OfficeDevPnPCore16.0.5.1030.7\lib\net45\OfficeDevPnP.Core.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IdentityModel" />
<Reference Include="System.IdentityModel.Selectors" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.2\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.ServiceModel" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Http, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.2\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SharePointContext.cs" />
<Compile Include="TokenHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
53 changes: 53 additions & 0 deletions Samples/Core.Throttling/Core.Throttling/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Core.Throttling
{
class Program
{
static void Main(string[] args)
{
string serverUrl = "<URL>";
String login = "<USERNAME>";
String password = "<PASSWORD>";
string listUrlName = "Shared%20Documents";

using (var ctx = new ClientContext(serverUrl))
{
//Provide acocunt and pwd for connecting to the source
var passWord = new SecureString();
foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials(login, passWord);

try
{
int number = 0;
// This loop will be executed 1000 times, which will cause throttling to occur
while (number < 1000)
{
// Let's try to create new folder based on Ticks to the given list as an example process
var folder = ctx.Site.RootWeb.GetFolderByServerRelativeUrl(listUrlName);
ctx.Load(folder);
folder = folder.Folders.Add(DateTime.Now.Ticks.ToString());
// Extension method for executing query with throttling checks
ctx.ExecuteQueryWithExponentialRetry(5, 30000); //5 retries, with a base delay of 10 secs.
// Status indication for execution.
Console.WriteLine("CSOM request successful.");
// For loop handling.
number = number + 1;
}
}
catch (MaximumRetryAttemptedException mex)
{
// Exception handling for the Maximum Retry Attempted
Console.WriteLine(mex.Message);
}
}
}
}
}
36 changes: 36 additions & 0 deletions Samples/Core.Throttling/Core.Throttling/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Core.Throttling")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Core.Throttling")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("073d095c-2593-4253-a1e9-b9b1edd3f9ee")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading

0 comments on commit d50100c

Please sign in to comment.