├── .gitignore ├── .nuget ├── NuGet.Config ├── NuGet.exe └── NuGet.targets ├── CONTRIBUTING.markdown ├── LICENSE.txt ├── README.markdown ├── RestSharp.IntegrationTests ├── App.config ├── Assets │ └── Koala.jpg ├── AsyncTests.cs ├── AuthenticationTests.cs ├── CompressionTests.cs ├── FileTests.cs ├── Helpers │ ├── Extensions.cs │ ├── Handlers.cs │ └── SimpleServer.cs ├── Models │ └── LinkedINMemberProfile.cs ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.IntegrationTests.csproj ├── StatusCodeTests.cs ├── oAuth1Tests.cs └── packages.config ├── RestSharp.Mono.sln ├── RestSharp.MonoDroid ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.MonoDroid.csproj └── RestSharp.MonoDroid.sln ├── RestSharp.MonoTouch ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.MonoTouch.csproj └── RestSharp.MonoTouch.sln ├── RestSharp.Net4 ├── Extensions │ └── RestClientExtensions.cs ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.Net4.csproj └── packages.config ├── RestSharp.Silverlight ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.Silverlight.csproj └── packages.config ├── RestSharp.Tests ├── CultureChange.cs ├── Fakes │ └── NullHttp.cs ├── JsonTests.cs ├── NamespacedXmlTests.cs ├── Properties │ └── AssemblyInfo.cs ├── RestRequestTests.cs ├── RestSharp.Tests.csproj ├── SampleClasses │ ├── BooleanTest.cs │ ├── JsonLists.cs │ ├── Lastfm.cs │ ├── ListSamples.cs │ ├── SOUser.cs │ ├── TwilioCallList.cs │ ├── eventful.cs │ ├── foursq.cs │ ├── googleweather.cs │ ├── misc.cs │ ├── nullables.cs │ └── twitter.cs ├── SampleData │ ├── 4sq.txt │ ├── GenericWithList.txt │ ├── GoogleWeather.xml │ ├── InlineListSample.xml │ ├── Lastfm.xml │ ├── ListWithAttributes.xml │ ├── NestedListSample.xml │ ├── boolean_from_number.xml │ ├── boolean_from_string.xml │ ├── datetimes.txt │ ├── directlists.xml │ ├── eventful.xml │ ├── iso8601datetimes.txt │ ├── jsonarray.txt │ ├── jsonenums.txt │ ├── jsonlists.txt │ ├── person.json.txt │ ├── sojson.txt │ ├── timespans.txt │ ├── underscore_prefix.txt │ └── xmllists.xml ├── SerializerTests.cs ├── SimpleJson.cs ├── UrlBuilderTests.cs ├── XmlTests.cs └── packages.config ├── RestSharp.WindowsPhone.Mango ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.WindowsPhone.Mango.csproj ├── RestSharp.WindowsPhone.Mango.sln └── packages.config ├── RestSharp.WindowsPhone ├── Properties │ └── AssemblyInfo.cs ├── RestSharp.WindowsPhone.csproj └── packages.config ├── RestSharp.sln ├── RestSharp ├── Authenticators │ ├── HttpBasicAuthenticator.cs │ ├── IAuthenticator.cs │ ├── NtlmAuthenticator.cs │ ├── OAuth │ │ ├── Extensions │ │ │ ├── CollectionExtensions.cs │ │ │ ├── OAuthExtensions.cs │ │ │ ├── StringExtensions.cs │ │ │ └── TimeExtensions.cs │ │ ├── HttpPostParameter.cs │ │ ├── HttpPostParameterType.cs │ │ ├── OAuthParameterHandling.cs │ │ ├── OAuthSignatureMethod.cs │ │ ├── OAuthSignatureTreatment.cs │ │ ├── OAuthTools.cs │ │ ├── OAuthType.cs │ │ ├── OAuthWebQueryInfo.cs │ │ ├── OAuthWorkflow.cs │ │ ├── WebPair.cs │ │ ├── WebPairCollection.cs │ │ ├── WebParameter.cs │ │ └── WebParameterCollection.cs │ ├── OAuth1Authenticator.cs │ ├── OAuth2Authenticator.cs │ └── SimpleAuthenticator.cs ├── Compression │ └── ZLib │ │ ├── Crc32.cs │ │ ├── FlushType.cs │ │ ├── GZipStream.cs │ │ ├── InfTree.cs │ │ ├── Inflate.cs │ │ ├── ZLib.cs │ │ ├── ZLibCodec.cs │ │ ├── ZLibConstants.cs │ │ └── ZLibStream.cs ├── Deserializers │ ├── DeserializeAsAttribute.cs │ ├── DotNetXmlDeserializer.cs │ ├── IDeserializer.cs │ ├── JsonDeserializer.cs │ ├── XmlAttributeDeserializer.cs │ └── XmlDeserializer.cs ├── Enum.cs ├── Extensions │ ├── MiscExtensions.cs │ ├── MonoHttp │ │ ├── Helpers.cs │ │ ├── HtmlEncoder.cs │ │ └── HttpUtility.cs │ ├── ReflectionExtensions.cs │ ├── ResponseExtensions.cs │ ├── StringExtensions.cs │ └── XmlExtensions.cs ├── FileParameter.cs ├── Http.Async.cs ├── Http.Sync.cs ├── Http.cs ├── HttpCookie.cs ├── HttpFile.cs ├── HttpHeader.cs ├── HttpParameter.cs ├── HttpResponse.cs ├── IHttp.cs ├── IHttpFactory.cs ├── IHttpResponse.cs ├── IRestClient.cs ├── IRestRequest.cs ├── IRestResponse.cs ├── Parameter.cs ├── Properties │ └── AssemblyInfo.cs ├── RestClient.Async.cs ├── RestClient.Sync.cs ├── RestClient.cs ├── RestClientExtensions.cs ├── RestRequest.cs ├── RestRequestAsyncHandle.cs ├── RestResponse.cs ├── RestResponseCookie.cs ├── RestSharp.csproj ├── Serializers │ ├── DotNetXmlSerializer.cs │ ├── ISerializer.cs │ ├── JsonSerializer.cs │ ├── SerializeAsAttribute.cs │ └── XmlSerializer.cs ├── SharedAssemblyInfo.cs ├── SimpleJson.cs ├── T4Helper │ ├── T4Helper.tt │ └── T4Toolbox.tt ├── Validation │ ├── Require.cs │ └── Validate.cs └── packages.config ├── Tools └── NuGet.exe ├── package.cmd ├── readme.txt ├── releasenotes.markdown └── restsharp.nuspec /.gitignore: -------------------------------------------------------------------------------- 1 | packages 2 | 3 | #ignore thumbnails created by windows 4 | Thumbs.db 5 | #Ignore files build by Visual Studio 6 | *.obj 7 | *.pdb 8 | *.user 9 | *.aps 10 | *.pch 11 | *.vspscc 12 | *_i.c 13 | *_p.c 14 | *.ncb 15 | *.suo 16 | *.tlb 17 | *.tlh 18 | *.bak 19 | *.cache 20 | *.ilk 21 | *.log 22 | ClientBin 23 | [Bb]in 24 | [Dd]ebug*/ 25 | *.lib 26 | *.sbr 27 | obj/ 28 | [Rr]elease*/ 29 | _ReSharper*/ 30 | [Tt]est[Rr]esult* 31 | Examples*/ 32 | SerializerTest*/ 33 | *.csproj.user 34 | *.resharper* 35 | Download/ 36 | #Ignore files from MonoDevelop 37 | *.pidb 38 | *.userprefs 39 | -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cratesmith/RestSharp-for-unity3d/86c9403eccafe4acb3ad0121baea3f1836e1d057/.nuget/NuGet.exe -------------------------------------------------------------------------------- /.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 8 | $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) 9 | $([System.IO.Path]::Combine($(SolutionDir), "packages")) 10 | 11 | 12 | $(SolutionDir).nuget 13 | packages.config 14 | $(SolutionDir)packages 15 | 16 | 17 | $(NuGetToolsPath)\nuget.exe 18 | "$(NuGetExePath)" 19 | mono --runtime=v4.0.30319 $(NuGetExePath) 20 | 21 | $(TargetDir.Trim('\\')) 22 | 23 | 24 | "" 25 | 26 | 27 | false 28 | 29 | 30 | false 31 | 32 | 33 | $(NuGetCommand) install "$(PackagesConfig)" -source $(PackageSources) -o "$(PackagesDir)" 34 | $(NuGetCommand) pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols 35 | 36 | 37 | 38 | RestorePackages; 39 | $(BuildDependsOn); 40 | 41 | 42 | 43 | 44 | $(BuildDependsOn); 45 | BuildPackage; 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 57 | 58 | 61 | 62 | 63 | 64 | 66 | 67 | 70 | 71 | -------------------------------------------------------------------------------- /CONTRIBUTING.markdown: -------------------------------------------------------------------------------- 1 | Follow these guidelines, in no particular order, to improve your chances of having a pull request merged in. 2 | 3 | ### Before you do anything else 4 | 5 | * Before reporting an issue or creating a pull request, discuss it in the Google Group http://groups.google.com/group/restsharp 6 | 7 | ### Once a contribution is ready to be submitted 8 | 9 | * Make each pull request atomic and exclusive; don't send pull requests for a laundry list of changes. 10 | * Even better, commit in small manageable chunks. 11 | * Tabs, not spaces. Bracket style doesn't matter. Do not reformat code you didn't touch. 12 | * Changes to XmlDeserializer or JsonDeserializer must be accompanied by a unit test covering the change. 13 | * No regions except for license header 14 | * Code must build for .NET 3.5 Client Profile, Silverlight 4 and Windows Phone 7 15 | * If you didn't write the code you must provide a reference to where you obtained it and preferably the license. 16 | * Use autocrlf=true `git config --global core.autocrlf true` http://help.github.com/dealing-with-lineendings/ -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # RestSharp - Simple .NET REST Client 2 | 3 | ### [Official Site/Blog][1] - [@RestSharp][2] 4 | ### Please use the [Google Group][3] for feature requests and troubleshooting usage. 5 | ### License: Apache License 2.0 6 | 7 | ### Features 8 | 9 | * Supports .NET 3.5+, Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android 10 | * Easy installation using [NuGet](http://nuget.org/packages/RestSharp) for most .NET flavors 11 | * Automatic XML and JSON deserialization 12 | * Supports custom serialization and deserialization via ISerializer and IDeserializer 13 | * Fuzzy element name matching ('product_id' in XML/JSON will match C# property named 'ProductId') 14 | * Automatic detection of type of content returned 15 | * GET, POST, PUT, HEAD, OPTIONS, DELETE supported 16 | * Other non-standard HTTP methods also supported 17 | * oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators included 18 | * Supports custom authentication schemes via IAuthenticator 19 | * Multi-part form/file uploads 20 | * T4 Helper to generate C# classes from an XML document 21 | 22 | ```csharp 23 | var client = new RestClient("http://example.com"); 24 | // client.Authenticator = new HttpBasicAuthenticator(username, password); 25 | 26 | var request = new RestRequest("resource/{id}", Method.POST); 27 | request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method 28 | request.AddUrlSegment("id", 123); // replaces matching token in request.Resource 29 | 30 | // add parameters for all properties on an object 31 | request.AddObject(object); 32 | 33 | // or just whitelisted properties 34 | request.AddObject(object, "PersonId", "Name", ...); 35 | 36 | // easily add HTTP Headers 37 | request.AddHeader("header", "value"); 38 | 39 | // add files to upload (works with compatible verbs) 40 | request.AddFile(path); 41 | 42 | // execute the request 43 | RestResponse response = client.Execute(request); 44 | var content = response.Content; // raw content as string 45 | 46 | // or automatically deserialize result 47 | // return content type is sniffed but can be explicitly set via RestClient.AddHandler(); 48 | RestResponse response2 = client.Execute(request); 49 | var name = response2.Data.Name; 50 | 51 | // or download and save file to disk 52 | client.DownloadData(request).SaveAs(path); 53 | 54 | // easy async support 55 | client.ExecuteAsync(request, response => { 56 | Console.WriteLine(response.Content); 57 | }); 58 | 59 | // async with deserialization 60 | var asyncHandle = client.ExecuteAsync(request, response => { 61 | Console.WriteLine(response.Data.Name); 62 | }); 63 | 64 | // abort the request on demand 65 | asyncHandle.Abort(); 66 | ``` 67 | 68 | [1]: http://restsharp.org 69 | [2]: http://twitter.com/RestSharp 70 | [3]: http://groups.google.com/group/RestSharp -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Assets/Koala.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cratesmith/RestSharp-for-unity3d/86c9403eccafe4acb3ad0121baea3f1836e1d057/RestSharp.IntegrationTests/Assets/Koala.jpg -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/AsyncTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading; 6 | using RestSharp.IntegrationTests.Helpers; 7 | using Xunit; 8 | 9 | namespace RestSharp.IntegrationTests 10 | { 11 | public class AsyncTests 12 | { 13 | [Fact] 14 | public void Can_Perform_GET_Async() 15 | { 16 | const string baseUrl = "http://localhost:8080/"; 17 | const string val = "Basic async test"; 18 | var resetEvent = new ManualResetEvent(false); 19 | using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) 20 | { 21 | var client = new RestClient(baseUrl); 22 | var request = new RestRequest(""); 23 | 24 | client.ExecuteAsync(request, (response, asyncHandle) => 25 | { 26 | Assert.NotNull(response.Content); 27 | Assert.Equal(val, response.Content); 28 | resetEvent.Set(); 29 | }); 30 | resetEvent.WaitOne(); 31 | } 32 | } 33 | 34 | [Fact] 35 | public void Can_Perform_GET_Async_Without_Async_Handle() 36 | { 37 | const string baseUrl = "http://localhost:8080/"; 38 | const string val = "Basic async test"; 39 | var resetEvent = new ManualResetEvent(false); 40 | using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) 41 | { 42 | var client = new RestClient(baseUrl); 43 | var request = new RestRequest(""); 44 | 45 | client.ExecuteAsync(request, response => 46 | { 47 | Assert.NotNull(response.Content); 48 | Assert.Equal(val, response.Content); 49 | resetEvent.Set(); 50 | }); 51 | resetEvent.WaitOne(); 52 | } 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/AuthenticationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Net; 4 | using System.Text; 5 | using RestSharp.Authenticators; 6 | using RestSharp.Contrib; 7 | using RestSharp.IntegrationTests.Helpers; 8 | using Xunit; 9 | 10 | namespace RestSharp.IntegrationTests 11 | { 12 | public class AuthenticationTests 13 | { 14 | [Fact] 15 | public void Can_Authenticate_With_Basic_Http_Auth() 16 | { 17 | const string baseUrl = "http://localhost:8080/"; 18 | using(SimpleServer.Create(baseUrl, UsernamePasswordEchoHandler)) 19 | { 20 | var client = new RestClient(baseUrl); 21 | client.Authenticator = new HttpBasicAuthenticator("testuser", "testpassword"); 22 | 23 | var request = new RestRequest("test"); 24 | var response = client.Execute(request); 25 | 26 | Assert.Equal("testuser|testpassword", response.Content); 27 | } 28 | } 29 | 30 | private static void UsernamePasswordEchoHandler(HttpListenerContext context) 31 | { 32 | var header = context.Request.Headers["Authorization"]; 33 | 34 | var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':'); 35 | context.Response.OutputStream.WriteStringUtf8(string.Join("|", parts)); 36 | } 37 | 38 | //[Fact] 39 | public void Can_Authenticate_With_OAuth() 40 | { 41 | var baseUrl = "https://api.twitter.com"; 42 | var client = new RestClient(baseUrl); 43 | client.Authenticator = OAuth1Authenticator.ForRequestToken( 44 | "CONSUMER_KEY", "CONSUMER_SECRET" 45 | ); 46 | var request = new RestRequest("oauth/request_token"); 47 | var response = client.Execute(request); 48 | 49 | Assert.NotNull(response); 50 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 51 | 52 | var qs = HttpUtility.ParseQueryString(response.Content); 53 | var oauth_token = qs["oauth_token"]; 54 | var oauth_token_secret = qs["oauth_token_secret"]; 55 | Assert.NotNull(oauth_token); 56 | Assert.NotNull(oauth_token_secret); 57 | 58 | request = new RestRequest("oauth/authorize?oauth_token=" + oauth_token); 59 | var url = client.BuildUri(request).ToString(); 60 | Process.Start(url); 61 | 62 | var verifier = "123456"; // <-- Breakpoint here (set verifier in debugger) 63 | request = new RestRequest("oauth/access_token"); 64 | client.Authenticator = OAuth1Authenticator.ForAccessToken( 65 | "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret, verifier 66 | ); 67 | response = client.Execute(request); 68 | 69 | Assert.NotNull(response); 70 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 71 | 72 | qs = HttpUtility.ParseQueryString(response.Content); 73 | oauth_token = qs["oauth_token"]; 74 | oauth_token_secret = qs["oauth_token_secret"]; 75 | Assert.NotNull(oauth_token); 76 | Assert.NotNull(oauth_token_secret); 77 | 78 | request = new RestRequest("account/verify_credentials.xml"); 79 | client.Authenticator = OAuth1Authenticator.ForProtectedResource( 80 | "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret 81 | ); 82 | 83 | response = client.Execute(request); 84 | 85 | Assert.NotNull(response); 86 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 87 | } 88 | 89 | //[Fact] 90 | //public void Can_Obtain_OAuth_Request_Token() 91 | //{ 92 | // var baseUrl = "http://term.ie/oauth/example"; 93 | // var client = new RestClient(baseUrl); 94 | // client.Authenticator = new OAuthAuthenticator(baseUrl, "key", "secret"); 95 | // var request = new RestRequest("request_token.php"); 96 | // var response = client.Execute(request); 97 | 98 | // Assert.NotNull(response); 99 | // Assert.Equal("oauth_token=requestkey&oauth_token_secret=requestsecret", response.Content); 100 | //} 101 | 102 | //[Fact] 103 | //public void Can_Obtain_OAuth_Access_Token() 104 | //{ 105 | // var baseUrl = "http://term.ie/oauth/example"; 106 | // var client = new RestClient(baseUrl); 107 | // client.Authenticator = new OAuthAuthenticator(baseUrl, "key", "secret", "requestkey", "requestsecret"); 108 | // var request = new RestRequest("access_token.php"); 109 | // var response = client.Execute(request); 110 | 111 | // Assert.NotNull(response); 112 | // Assert.Equal("oauth_token=accesskey&oauth_token_secret=accesssecret", response.Content); 113 | 114 | //} 115 | 116 | //[Fact] 117 | //public void Can_Make_Authenticated_OAuth_Call_With_Parameters() 118 | //{ 119 | // var baseUrl = "http://term.ie/oauth/example"; 120 | // var client = new RestClient(baseUrl); 121 | // client.Authenticator = new OAuthAuthenticator(baseUrl, "key", "secret", "accesskey", "accesssecret"); 122 | // var request = new RestRequest("echo_api.php"); 123 | // request.AddParameter("foo", "bar"); 124 | // request.AddParameter("fizz", "pop"); 125 | // var response = client.Execute(request); 126 | 127 | // Assert.NotNull(response); 128 | // Assert.Equal("fizz=pop&foo=bar", response.Content); 129 | //} 130 | 131 | //[Fact] 132 | //public void Can_Make_Authenticated_OAuth_Call() 133 | //{ 134 | // var baseUrl = "http://term.ie/oauth/example"; 135 | // var client = new RestClient(baseUrl); 136 | // client.Authenticator = new OAuthAuthenticator(baseUrl, "key", "secret", "accesskey", "accesssecret"); 137 | // var request = new RestRequest("echo_api.php"); 138 | // var response = client.Execute(request); 139 | 140 | // Assert.NotNull(response); 141 | // Assert.Equal(string.Empty, response.Content); 142 | 143 | //} 144 | 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/CompressionTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO.Compression; 3 | using System.Net; 4 | using RestSharp.IntegrationTests.Helpers; 5 | using Xunit; 6 | 7 | namespace RestSharp.IntegrationTests 8 | { 9 | public class CompressionTests 10 | { 11 | [Fact] 12 | public void Can_Handle_Gzip_Compressed_Content() 13 | { 14 | const string baseUrl = "http://localhost:8080/"; 15 | using(SimpleServer.Create(baseUrl, GzipEchoValue("This is some gzipped content"))) 16 | { 17 | var client = new RestClient(baseUrl); 18 | var request = new RestRequest(""); 19 | var response = client.Execute(request); 20 | 21 | Assert.Equal("This is some gzipped content", response.Content); 22 | } 23 | } 24 | 25 | [Fact] 26 | public void Can_Handle_Deflate_Compressed_Content() 27 | { 28 | const string baseUrl = "http://localhost:8080/"; 29 | using(SimpleServer.Create(baseUrl, DeflateEchoValue("This is some deflated content"))) 30 | { 31 | var client = new RestClient(baseUrl); 32 | var request = new RestRequest(""); 33 | var response = client.Execute(request); 34 | 35 | Assert.Equal("This is some deflated content", response.Content); 36 | } 37 | } 38 | 39 | [Fact] 40 | public void Can_Handle_Uncompressed_Content() 41 | { 42 | const string baseUrl = "http://localhost:8080/"; 43 | using(SimpleServer.Create(baseUrl, Handlers.EchoValue("This is some sample content"))) 44 | { 45 | var client = new RestClient(baseUrl); 46 | var request = new RestRequest(""); 47 | var response = client.Execute(request); 48 | 49 | Assert.Equal("This is some sample content", response.Content); 50 | } 51 | } 52 | 53 | static Action GzipEchoValue(string value) 54 | { 55 | return context => 56 | { 57 | context.Response.Headers.Add("Content-encoding", "gzip"); 58 | using (var gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true)) 59 | { 60 | gzip.WriteStringUtf8(value); 61 | } 62 | }; 63 | } 64 | 65 | static Action DeflateEchoValue(string value) 66 | { 67 | return context => 68 | { 69 | context.Response.Headers.Add("Content-encoding", "deflate"); 70 | using(var gzip = new DeflateStream(context.Response.OutputStream, CompressionMode.Compress, true)) 71 | { 72 | gzip.WriteStringUtf8(value); 73 | } 74 | }; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/FileTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using RestSharp.IntegrationTests.Helpers; 4 | using Xunit; 5 | 6 | namespace RestSharp.IntegrationTests 7 | { 8 | public class FileTests 9 | { 10 | [Fact] 11 | public void Handles_Binary_File_Download() 12 | { 13 | const string baseUrl = "http://localhost:8080/"; 14 | using (SimpleServer.Create(baseUrl, Handlers.FileHandler)) 15 | { 16 | var client = new RestClient(baseUrl); 17 | var request = new RestRequest("Assets/Koala.jpg"); 18 | var response = client.DownloadData(request); 19 | 20 | var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); 21 | Assert.Equal(expected, response); 22 | } 23 | } 24 | 25 | [Fact] 26 | public void Writes_Response_To_Stream() 27 | { 28 | const string baseUrl = "http://localhost:8080/"; 29 | using (SimpleServer.Create(baseUrl, Handlers.FileHandler)) 30 | { 31 | string tempFile = Path.GetTempFileName(); 32 | using (var writer = File.OpenWrite(tempFile)) 33 | { 34 | var client = new RestClient(baseUrl); 35 | var request = new RestRequest("Assets/Koala.jpg"); 36 | request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer); 37 | var response = client.DownloadData(request); 38 | Assert.Null(response); 39 | } 40 | var fromTemp = File.ReadAllBytes(tempFile); 41 | var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); 42 | Assert.Equal(expected, fromTemp); 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Helpers/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | 4 | namespace RestSharp.IntegrationTests.Helpers 5 | { 6 | public static class Extensions 7 | { 8 | public static void WriteStringUtf8(this Stream target, string value) 9 | { 10 | var encoded = Encoding.UTF8.GetBytes(value); 11 | target.Write(encoded, 0, encoded.Length); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Helpers/Handlers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Reflection; 6 | 7 | namespace RestSharp.IntegrationTests.Helpers 8 | { 9 | public static class Handlers 10 | { 11 | /// 12 | /// Echoes the request input back to the output. 13 | /// 14 | public static void Echo(HttpListenerContext context) 15 | { 16 | context.Request.InputStream.CopyTo(context.Response.OutputStream); 17 | } 18 | 19 | /// 20 | /// Echoes the given value back to the output. 21 | /// 22 | public static Action EchoValue(string value) 23 | { 24 | return ctx => ctx.Response.OutputStream.WriteStringUtf8(value); 25 | } 26 | 27 | /// 28 | /// Response to a request like this: http://localhost:8080/assets/koala.jpg 29 | /// by streaming the file located at "assets\koala.jpg" back to the client. 30 | /// 31 | public static void FileHandler(HttpListenerContext context) 32 | { 33 | var pathToFile = Path.Combine(context.Request.Url.Segments.Select(s => s.Replace("/", "")).ToArray()); 34 | 35 | using(var reader = new StreamReader(pathToFile)) 36 | reader.BaseStream.CopyTo(context.Response.OutputStream); 37 | } 38 | 39 | /// 40 | /// T should be a class that implements methods whose names match the urls being called, and take one parameter, an HttpListenerContext. 41 | /// e.g. 42 | /// urls exercised: "http://localhost:8080/error" and "http://localhost:8080/get_list" 43 | /// 44 | /// class MyHandler 45 | /// { 46 | /// void error(HttpListenerContext ctx) 47 | /// { 48 | /// // do something interesting here 49 | /// } 50 | /// 51 | /// void get_list(HttpListenerContext ctx) 52 | /// { 53 | /// // do something interesting here 54 | /// } 55 | /// } 56 | /// 57 | public static Action Generic() where T : new() 58 | { 59 | return ctx => 60 | { 61 | var methodName = ctx.Request.Url.Segments.Last(); 62 | var method = typeof(T).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); 63 | 64 | if(method.IsStatic) 65 | { 66 | method.Invoke(null, new object[] { ctx }); 67 | } 68 | else 69 | { 70 | method.Invoke(new T(), new object[] { ctx }); 71 | } 72 | }; 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Helpers/SimpleServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Threading; 4 | 5 | namespace RestSharp.IntegrationTests.Helpers 6 | { 7 | public class SimpleServer : IDisposable 8 | { 9 | readonly HttpListener _listener; 10 | readonly Action _handler; 11 | Thread _processor; 12 | 13 | public static SimpleServer Create(string url, Action handler) 14 | { 15 | var server = new SimpleServer(new HttpListener { Prefixes = { url } }, handler); 16 | server.Start(); 17 | return server; 18 | } 19 | 20 | SimpleServer(HttpListener listener, Action handler) 21 | { 22 | _listener = listener; 23 | _handler = handler; 24 | } 25 | 26 | public void Start() 27 | { 28 | if(!_listener.IsListening) 29 | { 30 | _listener.Start(); 31 | 32 | _processor = new Thread(() => 33 | { 34 | var context = _listener.GetContext(); 35 | _handler(context); 36 | context.Response.Close(); 37 | }) { Name = "WebServer" }; 38 | _processor.Start(); 39 | } 40 | } 41 | 42 | public void Dispose() 43 | { 44 | _processor.Abort(); 45 | _listener.Stop(); 46 | _listener.Close(); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Models/LinkedINMemberProfile.cs: -------------------------------------------------------------------------------- 1 | namespace RestSharp.IntegrationTests.Models 2 | { 3 | /// 4 | /// Model for used by the LinkedIN integration tests. . 5 | /// 6 | public class LinkedINMemberProfile 7 | { 8 | public string Id { get; set; } 9 | public string FirstName { get; set; } 10 | public string LastName { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.IntegrationTests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("RestSharp.IntegrationTests")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d1867cb5-67ee-49c2-afd5-3c9f371b9b4c")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/RestSharp.IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | 9.0.30729 7 | 2.0 8 | {47D3EBB9-0300-4AF8-BAC5-740D51454A63} 9 | Library 10 | Properties 11 | RestSharp.IntegrationTests 12 | RestSharp.IntegrationTests 13 | v4.0 14 | 512 15 | 16 | 17 | 3.5 18 | 19 | 20 | ..\ 21 | true 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | AllRules.ruleset 32 | 33 | 34 | pdbonly 35 | true 36 | bin\Release\ 37 | TRACE 38 | prompt 39 | 4 40 | AllRules.ruleset 41 | bin\Release\RestSharp.IntegrationTests.xml 42 | 43 | 44 | 45 | 46 | 3.5 47 | 48 | 49 | 3.5 50 | 51 | 52 | 53 | 54 | False 55 | ..\packages\xunit.1.9.0.1566\lib\xunit.dll 56 | 57 | 58 | False 59 | ..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | Always 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2} 87 | RestSharp 88 | 89 | 90 | 91 | 92 | 99 | -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/StatusCodeTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using RestSharp.IntegrationTests.Helpers; 3 | using Xunit; 4 | using System.Net; 5 | 6 | namespace RestSharp.IntegrationTests 7 | { 8 | public class StatusCodeTests 9 | { 10 | [Fact] 11 | public void Handles_GET_Request_404_Error() 12 | { 13 | const string baseUrl = "http://localhost:8080/"; 14 | using(SimpleServer.Create(baseUrl, UrlToStatusCodeHandler)) 15 | { 16 | var client = new RestClient(baseUrl); 17 | var request = new RestRequest("404"); 18 | var response = client.Execute(request); 19 | 20 | Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 21 | } 22 | } 23 | 24 | void UrlToStatusCodeHandler(HttpListenerContext obj) 25 | { 26 | obj.Response.StatusCode = int.Parse(obj.Request.Url.Segments.Last()); 27 | } 28 | 29 | /// 30 | /// Success of this test is based largely on the behavior of your current DNS. 31 | /// For example, if you're using OpenDNS this will test will fail; ResponseStatus will be Completed. 32 | /// 33 | [Fact] 34 | public void Handles_Non_Existent_Domain() 35 | { 36 | var client = new RestClient("http://nonexistantdomainimguessing.org"); 37 | var request = new RestRequest("foo"); 38 | var response = client.Execute(request); 39 | Assert.Equal(ResponseStatus.Error, response.ResponseStatus); 40 | } 41 | 42 | [Fact] 43 | public void Handles_Different_Root_Element_On_Error() 44 | { 45 | const string baseUrl = "http://localhost:8080/"; 46 | using(SimpleServer.Create(baseUrl, Handlers.Generic())) 47 | { 48 | var client = new RestClient(baseUrl); 49 | var request = new RestRequest("error"); 50 | request.RootElement = "Success"; 51 | request.OnBeforeDeserialization = resp => 52 | { 53 | if(resp.StatusCode == HttpStatusCode.BadRequest) 54 | { 55 | request.RootElement = "Error"; 56 | } 57 | }; 58 | 59 | var response = client.Execute(request); 60 | 61 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 62 | Assert.Equal("Not found!", response.Data.Message); 63 | } 64 | } 65 | 66 | [Fact] 67 | public void Handles_Default_Root_Element_On_No_Error() 68 | { 69 | const string baseUrl = "http://localhost:8080/"; 70 | using(SimpleServer.Create(baseUrl, Handlers.Generic())) 71 | { 72 | var client = new RestClient(baseUrl); 73 | var request = new RestRequest("success"); 74 | request.RootElement = "Success"; 75 | request.OnBeforeDeserialization = resp => 76 | { 77 | if(resp.StatusCode == HttpStatusCode.NotFound) 78 | { 79 | request.RootElement = "Error"; 80 | } 81 | }; 82 | 83 | var response = client.Execute(request); 84 | 85 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 86 | Assert.Equal("Works!", response.Data.Message); 87 | } 88 | } 89 | } 90 | 91 | public class ResponseHandler 92 | { 93 | void error(HttpListenerContext context) 94 | { 95 | context.Response.StatusCode = 400; 96 | context.Response.Headers.Add("Content-Type", "application/xml"); 97 | context.Response.OutputStream.WriteStringUtf8( 98 | @" 99 | 100 | 101 | Not found! 102 | 103 | "); 104 | } 105 | void success(HttpListenerContext context) 106 | { 107 | context.Response.OutputStream.WriteStringUtf8( 108 | @" 109 | 110 | 111 | Works! 112 | 113 | "); 114 | } 115 | } 116 | 117 | public class Response 118 | { 119 | public string Message { get; set; } 120 | } 121 | } -------------------------------------------------------------------------------- /RestSharp.IntegrationTests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /RestSharp.Mono.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp", "RestSharp\RestSharp.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests", "RestSharp.Tests\RestSharp.Tests.csproj", "{1464E4AC-18BB-4F23-8A0B-68196F9E1871}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{E709A928-A45C-4622-A35C-CCD8EE44CA80}" 9 | ProjectSection(SolutionItems) = preProject 10 | restsharp.nuspec = restsharp.nuspec 11 | EndProjectSection 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Debug|Mixed Platforms = Debug|Mixed Platforms 17 | Debug|x86 = Debug|x86 18 | Release|Any CPU = Release|Any CPU 19 | Release|Mixed Platforms = Release|Mixed Platforms 20 | Release|x86 = Release|x86 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU 26 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU 27 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|x86.ActiveCfg = Debug|Any CPU 28 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU 31 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.Build.0 = Release|Any CPU 32 | {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|x86.ActiveCfg = Release|Any CPU 33 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU 36 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU 37 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU 38 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU 41 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU 42 | {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(NestedProjects) = preSolution 45 | EndGlobalSection 46 | GlobalSection(MonoDevelopProperties) = preSolution 47 | StartupItem = RestSharp\RestSharp.csproj 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | EndGlobal 53 | -------------------------------------------------------------------------------- /RestSharp.MonoDroid/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.MonoDroid")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("A7B3BEB4-1B9B-4EDF-98BC-DF9EC82390BF")] -------------------------------------------------------------------------------- /RestSharp.MonoDroid/RestSharp.MonoDroid.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.MonoDroid", "RestSharp.MonoDroid.csproj", "{1B662C38-984F-4B6A-89B5-AFF7FCBE43A2}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {1B662C38-984F-4B6A-89B5-AFF7FCBE43A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {1B662C38-984F-4B6A-89B5-AFF7FCBE43A2}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {1B662C38-984F-4B6A-89B5-AFF7FCBE43A2}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {1B662C38-984F-4B6A-89B5-AFF7FCBE43A2}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /RestSharp.MonoTouch/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.MonoTouch")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("0F11B2CA-D65D-4B63-92B2-E4C0B1AACB6E")] -------------------------------------------------------------------------------- /RestSharp.MonoTouch/RestSharp.MonoTouch.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.MonoTouch", "RestSharp.MonoTouch.csproj", "{E9A9D1C5-4E06-4D31-9809-A97188C70B2C}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|iPhone = Debug|iPhone 9 | Debug|iPhoneSimulator = Debug|iPhoneSimulator 10 | Release|iPhone = Release|iPhone 11 | Release|iPhoneSimulator = Release|iPhoneSimulator 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Debug|iPhone.ActiveCfg = Debug|iPhone 15 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Debug|iPhone.Build.0 = Debug|iPhone 16 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Debug|iPhoneSimulator.ActiveCfg = Debug|iPhoneSimulator 17 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Debug|iPhoneSimulator.Build.0 = Debug|iPhoneSimulator 18 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Release|iPhone.ActiveCfg = Release|iPhone 19 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Release|iPhone.Build.0 = Release|iPhone 20 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator 21 | {E9A9D1C5-4E06-4D31-9809-A97188C70B2C}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | GlobalSection(MonoDevelopProperties) = preSolution 27 | StartupItem = RestSharp.MonoTouch.csproj 28 | EndGlobalSection 29 | EndGlobal 30 | -------------------------------------------------------------------------------- /RestSharp.Net4/Extensions/RestClientExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp 7 | { 8 | public static partial class RestClientExtensions 9 | { 10 | public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) 11 | { 12 | var response = client.Execute(request); 13 | 14 | var generic = (RestResponse)response; 15 | dynamic content = SimpleJson.DeserializeObject(response.Content); 16 | generic.Data = content; 17 | 18 | return generic; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /RestSharp.Net4/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("97044cbf-6c9d-4b08-87e3-bf30fbde1933")] 17 | 18 | [assembly: InternalsVisibleTo("RestSharp.IntegrationTests")] -------------------------------------------------------------------------------- /RestSharp.Net4/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /RestSharp.Silverlight/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.Silverlight")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("2314f291-c979-46b1-932c-f3ae123a3cef")] -------------------------------------------------------------------------------- /RestSharp.Silverlight/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /RestSharp.Tests/CultureChange.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Threading; 4 | 5 | namespace RestSharp.Tests 6 | { 7 | public class CultureChange : IDisposable 8 | { 9 | public CultureInfo PreviousCulture { get; private set; } 10 | 11 | public CultureChange(string culture) 12 | { 13 | if (culture == null) 14 | throw new ArgumentNullException("culture"); 15 | 16 | PreviousCulture = Thread.CurrentThread.CurrentCulture; 17 | 18 | Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); 19 | } 20 | 21 | #region IDisposable Members 22 | 23 | public void Dispose() 24 | { 25 | if (PreviousCulture != null) 26 | { 27 | Thread.CurrentThread.CurrentCulture = PreviousCulture; 28 | 29 | PreviousCulture = null; 30 | } 31 | } 32 | 33 | #endregion 34 | } 35 | } -------------------------------------------------------------------------------- /RestSharp.Tests/Fakes/NullHttp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.Fakes 7 | { 8 | public class NullHttp : Http 9 | { 10 | public new HttpResponse Get() 11 | { 12 | return new HttpResponse(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharp.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Microsoft")] 12 | [assembly: AssemblyProduct("RestSharp.Tests")] 13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2009")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("82c9d878-3d67-40fe-ac6b-6842605a04be")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /RestSharp.Tests/RestRequestTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Xunit; 6 | using System.Globalization; 7 | 8 | namespace RestSharp.Tests { 9 | public class RestRequestTests { 10 | public RestRequestTests() { 11 | System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; 12 | System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; 13 | } 14 | 15 | [Fact] 16 | public void Can_Add_Object_With_IntegerArray_property() { 17 | var request = new RestRequest(); 18 | request.AddObject(new { Items = new int[] { 2, 3, 4 } }); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/BooleanTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class BooleanTest 9 | { 10 | public bool Value { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/JsonLists.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class JsonLists 9 | { 10 | public List Names { get; set; } 11 | public List Numbers { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/Lastfm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses.Lastfm 7 | { 8 | public class Event : LastfmBase 9 | { 10 | public string id { get; set; } 11 | public string title { get; set; } 12 | public EventArtistList artists { get; set; } 13 | public Venue venue { get; set; } 14 | public DateTime startDate { get; set; } 15 | public string description { get; set; } 16 | public int attendance { get; set; } 17 | public int reviews { get; set; } 18 | public string tag { get; set; } 19 | public string url { get; set; } 20 | public string headliner { get; set; } 21 | public int cancelled { get; set; } 22 | } 23 | 24 | public class EventArtistList : List 25 | { 26 | } 27 | 28 | public class artist 29 | { 30 | public string Value { get; set; } 31 | } 32 | 33 | public abstract class LastfmBase 34 | { 35 | public string status { get; set; } 36 | public Error error { get; set; } 37 | } 38 | 39 | public class Error 40 | { 41 | public string Value { get; set; } 42 | public int code { get; set; } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/ListSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class SimpleTypesListSample 9 | { 10 | public List Names { get; set; } 11 | public List Numbers { get; set; } 12 | } 13 | 14 | public class InlineListSample 15 | { 16 | public int Count { get; set; } 17 | public List images { get; set; } 18 | public List Images { get; set; } 19 | } 20 | 21 | public class NestedListSample 22 | { 23 | public List images { get; set; } 24 | public List Images { get; set; } 25 | } 26 | 27 | public class EmptyListSample 28 | { 29 | public List images { get; set; } 30 | public List Images { get; set; } 31 | } 32 | 33 | public class Image 34 | { 35 | public string Src { get; set; } 36 | public string Value { get; set; } 37 | } 38 | 39 | public class image 40 | { 41 | public string Src { get; set; } 42 | public string Value { get; set; } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/SOUser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class SOUser 9 | { 10 | public int Id { get; set; } 11 | public int Reputation { get; set; } 12 | public long CreationDate { get; set; } 13 | public string DisplayName { get; set; } 14 | public string EmailHash { get; set; } 15 | public string Age { get; set; } 16 | public long LastAccessDate { get; set; } 17 | public string WebsiteUrl { get; set; } 18 | public string Location { get; set; } 19 | public string AboutMe { get; set; } 20 | public int Views { get; set; } 21 | public int UpVotes { get; set; } 22 | public int DownVotes { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/TwilioCallList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class TwilioCallList : List 9 | { 10 | public int Page { get; set; } 11 | public int NumPages { get; set; } 12 | } 13 | 14 | public class Call 15 | { 16 | public string Sid { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/eventful.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class VenueSearch 9 | { 10 | public string total_items { get; set; } 11 | public string page_size { get; set; } 12 | public string page_count { get; set; } 13 | public string page_number { get; set; } 14 | public string page_items { get; set; } 15 | public string first_item { get; set; } 16 | public string last_item { get; set; } 17 | public string search_time { get; set; } 18 | public List venues { get; set; } 19 | } 20 | 21 | public class PerformerSearch 22 | { 23 | public string total_items { get; set; } 24 | public string page_size { get; set; } 25 | public string page_count { get; set; } 26 | public string page_number { get; set; } 27 | public string page_items { get; set; } 28 | public string first_item { get; set; } 29 | public string last_item { get; set; } 30 | public string search_time { get; set; } 31 | public List performers { get; set; } 32 | } 33 | 34 | public class Performer 35 | { 36 | public string id { get; set; } 37 | public string url { get; set; } 38 | public string name { get; set; } 39 | public string short_bio { get; set; } 40 | public DateTime? created { get; set; } 41 | public string creator { get; set; } 42 | public string demand_count { get; set; } 43 | public string demand_member_count { get; set; } 44 | public string event_count { get; set; } 45 | public ServiceImage image { get; set; } 46 | } 47 | 48 | public class Venue 49 | { 50 | public string id { get; set; } 51 | public string url { get; set; } 52 | public string name { get; set; } 53 | public string venue_name { get; set; } 54 | public string description { get; set; } 55 | public string venue_type { get; set; } 56 | public string address { get; set; } 57 | public string city_name { get; set; } 58 | public string region_name { get; set; } 59 | public string postal_code { get; set; } 60 | public string country_name { get; set; } 61 | public string longitude { get; set; } 62 | public string latitude { get; set; } 63 | public string event_count { get; set; } 64 | } 65 | 66 | public class ServiceImage 67 | { 68 | public ServiceImage1 thumb { get; set; } 69 | public ServiceImage1 small { get; set; } 70 | public ServiceImage1 medium { get; set; } 71 | } 72 | 73 | public class ServiceImage1 74 | { 75 | public string url { get; set; } 76 | public string width { get; set; } 77 | public string height { get; set; } 78 | } 79 | 80 | public class Event 81 | { 82 | public string id { get; set; } 83 | public string url { get; set; } 84 | public string title { get; set; } 85 | public string description { get; set; } 86 | public string start_time { get; set; } 87 | public string venue_name { get; set; } 88 | public string venue_id { get; set; } 89 | public List performers { get; set; } 90 | } 91 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/foursq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class VenuesResponse 9 | { 10 | public List Groups { get; set; } 11 | } 12 | 13 | public class Group 14 | { 15 | public string Name { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/googleweather.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class xml_api_reply 9 | { 10 | public string version { get; set; } 11 | public Weather weather { get; set; } 12 | } 13 | 14 | public class Weather : List 15 | { 16 | public string module_id { get; set; } 17 | public string tab_id { get; set; } 18 | public string mobile_row { get; set; } 19 | public string mobile_zipped { get; set; } 20 | public string row { get; set; } 21 | public string section { get; set; } 22 | public Forecast_information forecast_information { get; set; } 23 | public Current_conditions current_conditions { get; set; } 24 | //public T forecast_conditions { get; set; } 25 | } 26 | 27 | public class DataElement 28 | { 29 | public string data { get; set; } 30 | } 31 | 32 | public class Forecast_information 33 | { 34 | public DataElement city { get; set; } 35 | public DataElement postal_code { get; set; } 36 | public DataElement forecast_date { get; set; } 37 | public DataElement unit_system { get; set; } 38 | } 39 | 40 | public class Current_conditions 41 | { 42 | public DataElement condition { get; set; } 43 | public DataElement temp_c { get; set; } 44 | public DataElement humidity { get; set; } 45 | public DataElement icon { get; set; } 46 | public DataElement wind_condition { get; set; } 47 | } 48 | 49 | public class forecast_conditions 50 | { 51 | public DataElement day_of_week { get; set; } 52 | public DataElement condition { get; set; } 53 | public DataElement low { get; set; } 54 | public DataElement high { get; set; } 55 | public DataElement icon { get; set; } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/misc.cs: -------------------------------------------------------------------------------- 1 | #region Licensed 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using RestSharp.Serializers; 20 | 21 | namespace RestSharp.Tests 22 | { 23 | public class PersonForXml 24 | { 25 | public string Name { get; set; } 26 | public DateTime StartDate { get; set; } 27 | public int Age { get; set; } 28 | public decimal Percent { get; set; } 29 | public long BigNumber { get; set; } 30 | public bool IsCool { get; set; } 31 | public List Friends { get; set; } 32 | public Friend BestFriend { get; set; } 33 | 34 | protected string Ignore { get; set; } 35 | public string IgnoreProxy { get { return Ignore; } } 36 | 37 | protected string ReadOnly { get { return null; } } 38 | public string ReadOnlyProxy { get { return ReadOnly; } } 39 | 40 | public FoeList Foes { get; set; } 41 | 42 | public Guid UniqueId { get; set; } 43 | public Guid EmptyGuid { get; set; } 44 | 45 | public Uri Url { get; set; } 46 | public Uri UrlPath { get; set; } 47 | 48 | public Order Order { get; set; } 49 | 50 | public Disposition Disposition { get; set; } 51 | 52 | } 53 | 54 | public class IncomingInvoice 55 | { 56 | public int ConceptId { get; set; } 57 | } 58 | 59 | public class PersonForJson 60 | { 61 | public string Name { get; set; } 62 | public DateTime StartDate { get; set; } 63 | public int Age { get; set; } 64 | public decimal Percent { get; set; } 65 | public long BigNumber { get; set; } 66 | public bool IsCool { get; set; } 67 | public List Friends { get; set; } 68 | public Friend BestFriend { get; set; } 69 | public Guid Guid { get; set; } 70 | public Guid EmptyGuid { get; set; } 71 | public Uri Url { get; set; } 72 | public Uri UrlPath { get; set; } 73 | 74 | protected string Ignore { get; set; } 75 | public string IgnoreProxy { get { return Ignore; } } 76 | 77 | protected string ReadOnly { get { return null; } } 78 | public string ReadOnlyProxy { get { return ReadOnly; } } 79 | 80 | public Dictionary Foes { get; set; } 81 | 82 | public Order Order { get; set; } 83 | 84 | public Disposition Disposition { get; set; } 85 | } 86 | 87 | public enum Order 88 | { 89 | First, 90 | Second, 91 | Third 92 | } 93 | 94 | public enum Disposition 95 | { 96 | Friendly, 97 | SoSo, 98 | SteerVeryClear 99 | } 100 | 101 | public class Friend 102 | { 103 | public string Name { get; set; } 104 | public int Since { get; set; } 105 | } 106 | 107 | public class Foe 108 | { 109 | public string Nickname { get; set; } 110 | } 111 | 112 | public class FoeList : List 113 | { 114 | public string Team { get; set; } 115 | } 116 | 117 | public class Birthdate 118 | { 119 | public DateTime Value { get; set; } 120 | } 121 | 122 | public class OrderedProperties 123 | { 124 | [SerializeAs(Index = 2)] 125 | public string Name { get; set; } 126 | [SerializeAs(Index = 3)] 127 | public int Age { get; set; } 128 | [SerializeAs(Index = 1)] 129 | public DateTime StartDate { get; set; } 130 | } 131 | 132 | public class DatabaseCollection : List 133 | { 134 | } 135 | 136 | public class Database 137 | { 138 | public string Name { get; set; } 139 | public string InitialCatalog { get; set; } 140 | public string DataSource { get; set; } 141 | } 142 | 143 | public class Generic 144 | { 145 | public T Data { get; set; } 146 | } 147 | 148 | public class GenericWithList 149 | { 150 | public List Items { get; set; } 151 | } 152 | 153 | public class GuidList 154 | { 155 | public List Ids { get; set; } 156 | } 157 | 158 | public class DateTimeTestStructure 159 | { 160 | public DateTime DateTime { get; set; } 161 | public DateTime? NullableDateTimeWithNull { get; set; } 162 | public DateTime? NullableDateTimeWithValue { get; set; } 163 | public DateTimeOffset DateTimeOffset { get; set; } 164 | public DateTimeOffset? NullableDateTimeOffsetWithNull { get; set; } 165 | public DateTimeOffset? NullableDateTimeOffsetWithValue { get; set; } 166 | } 167 | 168 | public class Iso8601DateTimeTestStructure 169 | { 170 | public DateTime DateTimeLocal { get; set; } 171 | public DateTime DateTimeUtc { get; set; } 172 | public DateTime DateTimeWithOffset { get; set; } 173 | } 174 | 175 | public class TimeSpanTestStructure 176 | { 177 | public TimeSpan Tick { get; set; } 178 | public TimeSpan Millisecond { get; set; } 179 | public TimeSpan Second { get; set; } 180 | public TimeSpan Minute { get; set; } 181 | public TimeSpan Hour { get; set; } 182 | public TimeSpan? NullableWithoutValue { get; set; } 183 | public TimeSpan? NullableWithValue { get; set; } 184 | } 185 | 186 | public class JsonEnumsTestStructure 187 | { 188 | public Disposition Upper { get; set; } 189 | public Disposition Lower { get; set; } 190 | public Disposition CamelCased { get; set; } 191 | public Disposition Underscores { get; set; } 192 | public Disposition LowerUnderscores { get; set; } 193 | public Disposition Dashes { get; set; } 194 | public Disposition LowerDashes { get; set; } 195 | public Disposition Integer { get; set; } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/nullables.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests 7 | { 8 | public class NullableValues 9 | { 10 | public int? Id { get; set; } 11 | public DateTime? StartDate { get; set; } 12 | public Guid? UniqueId { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleClasses/twitter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Tests.SampleClasses 7 | { 8 | public class status 9 | { 10 | public bool truncated { get; set; } 11 | public string created_at { get; set; } 12 | public string source { get; set; } 13 | public bool favorited { get; set; } 14 | public string in_reply_to_user_id { get; set; } 15 | public string in_reply_to_status_id { get; set; } 16 | public string in_reply_to_screen_name { get; set; } 17 | // ignore contributors for now 18 | public user user { get; set; } 19 | // ignore geo 20 | public long id { get; set; } 21 | public string text { get; set; } 22 | } 23 | 24 | public class user 25 | { 26 | public string url { get; set; } 27 | public string description { get; set; } 28 | public string profile_text_color { get; set; } 29 | public int followers_count { get; set; } 30 | public int statuses_count { get; set; } 31 | public bool geo_enabled { get; set; } 32 | public string profile_background_image_url { get; set; } 33 | public bool notifications { get; set; } 34 | public string created_at { get; set; } 35 | public int friends_count { get; set; } 36 | public string profile_link_color { get; set; } 37 | public bool contributors_enabled { get; set; } 38 | public bool profile_background_tile { get; set; } 39 | public int favourites_count { get; set; } 40 | public string profile_background_color { get; set; } 41 | public string profile_image_url { get; set; } 42 | public string lang { get; set; } 43 | public bool verified { get; set; } 44 | public string profile_sidebar_fill_color { get; set; } 45 | public bool @protected { get; set; } 46 | public string screen_name { get; set; } 47 | public bool following { get; set; } 48 | public string location { get; set; } 49 | public string name { get; set; } 50 | public string time_zone { get; set; } 51 | public string profile_sidebar_border_color { get; set; } 52 | public long id { get; set; } 53 | public int utc_offset { get; set; } 54 | 55 | } 56 | 57 | public class StatusList : List 58 | { 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/4sq.txt: -------------------------------------------------------------------------------- 1 | { 2 | "meta":{ 3 | "code":200 4 | }, 5 | "response":{ 6 | "groups":[ 7 | { 8 | "type":"trending", 9 | "name":"Trending Now", 10 | "items":[ 11 | { 12 | "id":"4846c5acf964a5206f501fe3", 13 | "name":"Santos Party House", 14 | "contact":{ 15 | "twitter":"SantosPartyHaus" 16 | }, 17 | "location":{ 18 | "address":"96 Lafayette St", 19 | "crossStreet":"btw Walker & White", 20 | "city":"New York", 21 | "distance":1962 22 | }, 23 | "categories":[ 24 | { 25 | "id":"4bf58dd8d48988d11f941735" 26 | } 27 | ] 28 | } 29 | ] 30 | }, 31 | { 32 | "type":"nearby", 33 | "name":"Nearby", 34 | "items":[ 35 | { 36 | "id":"42377700f964a52024201fe3", 37 | "name":"Brooklyn Heights Promenade", 38 | "contact":{ 39 | 40 | }, 41 | "location":{ 42 | "address":"Columbia Heights", 43 | "crossStreet":"btw Montague and Middagh", 44 | "city":"Brooklyn", 45 | "distance":342 46 | }, 47 | "categories":[ 48 | { 49 | "id":"4bf58dd8d48988d163941735", 50 | "name":"Park", 51 | "parents":[ 52 | "Great Outdoors" 53 | ], 54 | "primary":true 55 | } 56 | ] 57 | } 58 | ] 59 | } 60 | ] 61 | } 62 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/GenericWithList.txt: -------------------------------------------------------------------------------- 1 | { 2 | "Data": 3 | { 4 | "Items": 5 | [ 6 | {"Nickname":"Foe sho"} 7 | ] 8 | } 9 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/GoogleWeather.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/InlineListSample.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 4 | value1 5 | value2 6 | value3 7 | value4 8 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/Lastfm.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 328799 4 | Philip Glass 5 | 6 | Philip Glass 7 | Orchestra and Chorus of Erfurt Theatre 8 | Philip Glass 9 | 10 | 11 | 8777860 12 | Barbican Centre 13 | 14 | London 15 | United Kingdom 16 | Silk Street 17 | EC2Y 8DS 18 | 19 | 51.520099 20 | -0.093609 21 | 22 | 23 | http://www.last.fm/venue/8777860+Barbican+Centre 24 | http://www.barbican.org.uk 25 | 26 | http://userserve-ak.last.fm/serve/34/418510.jpg 27 | http://userserve-ak.last.fm/serve/64/418510.jpg 28 | http://userserve-ak.last.fm/serve/126/418510.jpg 29 | http://userserve-ak.last.fm/serve/252/418510.jpg 30 | http://userserve-ak.last.fm/serve/500/418510/Barbican+Centre.jpg 31 | 32 | Thu, 12 Jun 2008 19:30:00 33 | 34 | http://userserve-ak.last.fm/serve/34/39466081.png 35 | http://userserve-ak.last.fm/serve/64/39466081.png 36 | http://userserve-ak.last.fm/serve/126/39466081.png 37 | http://userserve-ak.last.fm/serve/252/39466081.png 38 | 48 39 | 0 40 | lastfm:event=328799 41 | http://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008 42 | 43 | 44 | 0 45 | 46 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/ListWithAttributes.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | CA92d4405c9237c4ea04b56cbda88e128c 6 | Fri, 13 Aug 2010 01:16:22 +0000 7 | Fri, 13 Aug 2010 01:16:22 +0000 8 | 9 | AC5ef877a5fe4238be081ea6f3c44186f3 10 | +15304551166 11 | +15105555555 12 | PNe2d8e63b37f46f2adb16f228afdb9058 13 | queued 14 | Thu, 12 Aug 2010 01:37:05 +0000 15 | Thu, 12 Aug 2010 01:37:40 +0000 16 | 17 | 18 | outbound-api 19 | 20 | 2010-04-01 21 | 22 | 23 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c 24 | 25 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Notifications 26 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Recordings 27 | 28 | 29 | 30 | CA12345 31 | Fri, 13 Aug 2010 01:16:22 +0000 32 | Fri, 13 Aug 2010 01:16:22 +0000 33 | 34 | AC5ef877a5fe4238be081ea6f3c44186f3 35 | +15304551166 36 | +15105555555 37 | PNe2d8e63b37f46f2adb16f228afdb9058 38 | queued 39 | Thu, 12 Aug 2010 01:37:05 +0000 40 | Thu, 12 Aug 2010 01:37:40 +0000 41 | 42 | 43 | outbound-api 44 | 45 | 2010-04-01 46 | 47 | 48 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c 49 | 50 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Notifications 51 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Recordings 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/NestedListSample.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | value1 5 | value2 6 | value3 7 | value4 8 | 9 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/boolean_from_number.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 1 4 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/boolean_from_string.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | true 4 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/datetimes.txt: -------------------------------------------------------------------------------- 1 | { 2 | "DateTime": "/Date(1309421746929+0000)/", 3 | "NullableDateTimeWithValue": "/Date(1309421746929+0000)/", 4 | "DateTimeOffset": "/Date(1309421746929+0000)/", 5 | "NullableDateTimeOffsetWithValue": "/Date(1309421746929+0000)/" 6 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/directlists.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | sv 5 | lusrvsql3 6 | Pomtest 7 | Pomtest 8 | 9 | 10 | 11 | 12 | 13 | sv 14 | lusrvsql3 15 | testdb 16 | Test 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/eventful.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 3 4 | 10 5 | 1 6 | 1 7 | 3 8 | 1 9 | 3 10 | 0.262 11 | 12 | 13 | http://eventful.com/venues/tivoli-/V0-001-002011236-6 14 | Tivoli 15 | Tivoli 16 | 17 | 18 |
291 Dandenong Rd
19 | Prahran 20 | Victoria 21 | VIC 22 | 3181 23 | Australia 24 | AU 25 | AUS 26 | 145.004726 27 | -37.859123 28 | EVDB Geocoder 29 | evdb 30 | 31 | 32 | 0 33 | 0 34 | 0 35 | 0 36 | 37 |
38 | 39 | http://eventful.com/brisbane/venues/tivoli-/V0-001-002169294-8 40 | Tivoli 41 | Tivoli 42 | <br> <br>(No phone for this venue yet.)<br> <br>(No website for this venue yet.)<br> <br> 43 | 44 |
Brisbane
45 | Brisbane 46 | Queensland 47 | QLD 48 | 49 | Australia 50 | AU 51 | AUS 52 | 153.017 53 | -27.5 54 | City Based GeoCodes 55 | evdb 56 | 57 | 58 | 1 59 | 0 60 | 0 61 | 1 62 | 63 |
64 | 65 | http://eventful.com/brisbane/venues/the-tivoli-/V0-001-000266914-3 66 | The Tivoli 67 | The Tivoli 68 | Built in 1917 and restored in Art Deco style, this elegant, fully licensed theatre has state-of-the-art technical features, top-of-the-range facilities, in-house catering by our 5 star chef and dedicated staff available to meet all your needs. 69 | Concert Hall 70 |
52 Costin Street Fortitude Valley
71 | Brisbane 72 | Queensland 73 | QLD 74 | 4006 75 | Australia 76 | AU 77 | AUS 78 | 153.031548 79 | -27.452335 80 | EVDB Geocoder 81 | evdb 82 | 83 | 84 | 28 85 | 0 86 | 7 87 | 1 88 | 89 | http://images.evdb.com/images/small/I0-001/001/414/278-2.jpeg 90 | 48 91 | 48 92 | 93 | 94 | http://images.evdb.com/images/thumb/I0-001/001/414/278-2.jpeg 95 | 48 96 | 48 97 | 98 | 99 | http://images.evdb.com/images/small/I0-001/001/414/278-2.jpeg 100 | 48 101 | 48 102 | 103 | 104 | http://images.evdb.com/images/medium/I0-001/001/414/278-2.jpeg 105 | 128 106 | 128 107 | 108 | 109 |
110 |
111 |
-------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/iso8601datetimes.txt: -------------------------------------------------------------------------------- 1 | { 2 | "DateTimeLocal": "2012-07-19T10:23:25", 3 | "DateTimeUtc": "2012-07-19T10:23:25.544Z", 4 | "DateTimeWithOffset": "2012-07-19T03:23:25.544-07:00", 5 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/jsonenums.txt: -------------------------------------------------------------------------------- 1 | { 2 | "upper": "FRIENDLY", 3 | "lower": "friendly", 4 | "camel_cased": "SoSo", 5 | "underscores": "So_So", 6 | "lower_underscores": "so_so", 7 | "dashes": "So-So", 8 | "lower_dashes": "so_so", 9 | "integer" : 1 10 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/jsonlists.txt: -------------------------------------------------------------------------------- 1 | { 2 | "names" : [ 3 | "John", 4 | "Bob", 5 | "Albert", 6 | "Jeff", 7 | "Charlie" 8 | ], 9 | "numbers" : [ 10 | 1, 11 | 2, 12 | 3, 13 | 5, 14 | 7, 15 | 11 16 | ] 17 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/person.json.txt: -------------------------------------------------------------------------------- 1 | { 2 | "StartDate": "/Date(1309421746929+0000)/" 3 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/sojson.txt: -------------------------------------------------------------------------------- 1 | { 2 | "User":{ 3 | "Id":1786, 4 | "Reputation":18332, 5 | "CreationDate":1219071163, 6 | "DisplayName":"John Sheehan", 7 | "EmailHash":"lkdsafadfjsadfkjlsdjflkjdsf", 8 | "Age":"28", 9 | "LastAccessDate":1269715453, 10 | "WebsiteUrl":"http://john-sheehan.com/blog", 11 | "Location":"Minnesota", 12 | "AboutMe":"

Follow me on Twitter

\r\n\r\n

Read my blog

\r\n\r\n

Visit managedassembly.com - A community for .NET developers.

\r\n\r\n

I am the founder of RIM Systems, maker of SnapLeague, a web-based league management system for recreational athletics.

", 13 | "Views":1639, 14 | "UpVotes":1665, 15 | "DownVotes":427 16 | } 17 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/timespans.txt: -------------------------------------------------------------------------------- 1 | { 2 | "Tick": "00:00:00.0468006", 3 | "Millisecond": "00:00:00.1250000", 4 | "Second": "00:00:08.0000000", 5 | "Minute": "00:55:02.0000000", 6 | "Hour": "21:30:07.0000000", 7 | "NullableWithoutValue": null, 8 | "NullableWithValue": "21:30:07.0000000", 9 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/underscore_prefix.txt: -------------------------------------------------------------------------------- 1 | { 2 | "User":{ 3 | "_id":1786, 4 | "_displayName":"John Sheehan", 5 | "Reputation":18332, 6 | "CreationDate":1219071163, 7 | "_displayName":"John Sheehan", 8 | "EmailHash":"lkdsafadfjsadfkjlsdjflkjdsf", 9 | "Age":"28", 10 | "LastAccessDate":1269715453, 11 | "WebsiteUrl":"http://john-sheehan.com/blog", 12 | "Location":"Minnesota", 13 | "AboutMe":"

Follow me on Twitter

\r\n\r\n

Read my blog

\r\n\r\n

Visit managedassembly.com - A community for .NET developers.

\r\n\r\n

I am the founder of RIM Systems, maker of SnapLeague, a web-based league management system for recreational athletics.

", 14 | "Views":1639, 15 | "UpVotes":1665, 16 | "DownVotes":427 17 | } 18 | } -------------------------------------------------------------------------------- /RestSharp.Tests/SampleData/xmllists.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | John 5 | Bob 6 | Albert 7 | Jeff 8 | Charlie 9 | 10 | 11 | 1 12 | 2 13 | 3 14 | 5 15 | 7 16 | 11 17 | 18 | -------------------------------------------------------------------------------- /RestSharp.Tests/UrlBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Xunit; 6 | 7 | namespace RestSharp.Tests 8 | { 9 | /// 10 | /// Note: These tests do not handle QueryString building, which is handled in Http, not RestClient 11 | /// 12 | public class UrlBuilderTests 13 | { 14 | [Fact] 15 | public void GET_with_leading_slash() 16 | { 17 | var request = new RestRequest("/resource"); 18 | var client = new RestClient("http://example.com"); 19 | 20 | var expected = new Uri("http://example.com/resource"); 21 | var output = client.BuildUri(request); 22 | 23 | Assert.Equal(expected, output); 24 | } 25 | 26 | [Fact] 27 | public void POST_with_leading_slash() 28 | { 29 | var request = new RestRequest("/resource", Method.POST); 30 | var client = new RestClient("http://example.com"); 31 | 32 | var expected = new Uri("http://example.com/resource"); 33 | var output = client.BuildUri(request); 34 | 35 | Assert.Equal(expected, output); 36 | } 37 | 38 | [Fact] 39 | public void GET_with_leading_slash_and_baseurl_trailing_slash() 40 | { 41 | var request = new RestRequest("/resource"); 42 | request.AddParameter("foo", "bar"); 43 | var client = new RestClient("http://example.com/"); 44 | 45 | var expected = new Uri("http://example.com/resource?foo=bar"); 46 | var output = client.BuildUri(request); 47 | 48 | Assert.Equal(expected, output); 49 | } 50 | 51 | [Fact] 52 | public void POST_with_leading_slash_and_baseurl_trailing_slash() 53 | { 54 | var request = new RestRequest("/resource", Method.POST); 55 | var client = new RestClient("http://example.com/"); 56 | 57 | var expected = new Uri("http://example.com/resource"); 58 | var output = client.BuildUri(request); 59 | 60 | Assert.Equal(expected, output); 61 | } 62 | 63 | [Fact] 64 | public void GET_with_resource_containing_slashes() 65 | { 66 | var request = new RestRequest("resource/foo"); 67 | var client = new RestClient("http://example.com"); 68 | 69 | var expected = new Uri("http://example.com/resource/foo"); 70 | var output = client.BuildUri(request); 71 | 72 | Assert.Equal(expected, output); 73 | } 74 | 75 | [Fact] 76 | public void POST_with_resource_containing_slashes() 77 | { 78 | var request = new RestRequest("resource/foo", Method.POST); 79 | var client = new RestClient("http://example.com"); 80 | 81 | var expected = new Uri("http://example.com/resource/foo"); 82 | var output = client.BuildUri(request); 83 | 84 | Assert.Equal(expected, output); 85 | } 86 | 87 | [Fact] 88 | public void GET_with_resource_containing_tokens() 89 | { 90 | var request = new RestRequest("resource/{foo}"); 91 | request.AddUrlSegment("foo", "bar"); 92 | var client = new RestClient("http://example.com"); 93 | 94 | var expected = new Uri("http://example.com/resource/bar"); 95 | var output = client.BuildUri(request); 96 | 97 | Assert.Equal(expected, output); 98 | } 99 | 100 | [Fact] 101 | public void POST_with_resource_containing_tokens() 102 | { 103 | var request = new RestRequest("resource/{foo}", Method.POST); 104 | request.AddUrlSegment("foo", "bar"); 105 | var client = new RestClient("http://example.com"); 106 | 107 | var expected = new Uri("http://example.com/resource/bar"); 108 | var output = client.BuildUri(request); 109 | 110 | Assert.Equal(expected, output); 111 | } 112 | 113 | [Fact] 114 | public void GET_with_empty_request() 115 | { 116 | var request = new RestRequest(); 117 | var client = new RestClient("http://example.com/resource"); 118 | 119 | var expected = new Uri("http://example.com/resource"); 120 | var output = client.BuildUri(request); 121 | 122 | Assert.Equal(expected, output); 123 | } 124 | 125 | [Fact] 126 | public void GET_with_empty_request_and_bare_hostname() 127 | { 128 | var request = new RestRequest(); 129 | var client = new RestClient("http://example.com"); 130 | 131 | var expected = new Uri("http://example.com/"); 132 | var output = client.BuildUri(request); 133 | 134 | Assert.Equal(expected, output); 135 | } 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /RestSharp.Tests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /RestSharp.WindowsPhone.Mango/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.WindowsPhone")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("edd38716-2ef8-46c4-8730-c4ed8bc12eed")] -------------------------------------------------------------------------------- /RestSharp.WindowsPhone.Mango/RestSharp.WindowsPhone.Mango.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual Studio 2010 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.WindowsPhone.Mango", "RestSharp.WindowsPhone.Mango.csproj", "{71647E33-714F-4975-8368-71B075045272}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Any CPU = Debug|Any CPU 9 | Release|Any CPU = Release|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {71647E33-714F-4975-8368-71B075045272}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {71647E33-714F-4975-8368-71B075045272}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {71647E33-714F-4975-8368-71B075045272}.Release|Any CPU.ActiveCfg = Release|Any CPU 15 | {71647E33-714F-4975-8368-71B075045272}.Release|Any CPU.Build.0 = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /RestSharp.WindowsPhone.Mango/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /RestSharp.WindowsPhone/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp.WindowsPhone")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("d6e5e03c-bbac-4d6a-8170-051b8225147c")] -------------------------------------------------------------------------------- /RestSharp.WindowsPhone/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /RestSharp/Authenticators/HttpBasicAuthenticator.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Linq; 19 | using System.Text; 20 | 21 | namespace RestSharp 22 | { 23 | public class HttpBasicAuthenticator : IAuthenticator 24 | { 25 | private readonly string _username; 26 | private readonly string _password; 27 | 28 | public HttpBasicAuthenticator(string username, string password) { 29 | _password = password; 30 | _username = username; 31 | } 32 | 33 | public void Authenticate(IRestClient client, IRestRequest request) { 34 | // NetworkCredentials always makes two trips, even if with PreAuthenticate, 35 | // it is also unsafe for many partial trust scenarios 36 | // request.Credentials = Credentials; 37 | // thanks TweetSharp! 38 | 39 | // request.Credentials = new NetworkCredential(_username, _password); 40 | 41 | // only add the Authorization parameter if it hasn't been added by a previous Execute 42 | if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) 43 | { 44 | var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _username, _password))); 45 | var authHeader = string.Format("Basic {0}", token); 46 | request.AddParameter("Authorization", authHeader, ParameterType.HttpHeader); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /RestSharp/Authenticators/IAuthenticator.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp 18 | { 19 | public interface IAuthenticator 20 | { 21 | void Authenticate(IRestClient client, IRestRequest request); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /RestSharp/Authenticators/NtlmAuthenticator.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Net; 19 | 20 | #if FRAMEWORK 21 | 22 | namespace RestSharp 23 | { 24 | /// 25 | /// Tries to Authenticate with the credentials of the currently logged in user, or impersonate a user 26 | /// 27 | public class NtlmAuthenticator : IAuthenticator 28 | { 29 | private readonly ICredentials credentials; 30 | 31 | /// 32 | /// Authenticate with the credentials of the currently logged in user 33 | /// 34 | public NtlmAuthenticator() 35 | : this(CredentialCache.DefaultCredentials) 36 | { 37 | } 38 | 39 | /// 40 | /// Authenticate by impersonation 41 | /// 42 | /// 43 | /// 44 | public NtlmAuthenticator(string username, string password) : this(new NetworkCredential(username, password)) 45 | { 46 | } 47 | 48 | /// 49 | /// Authenticate by impersonation, using an existing ICredentials instance 50 | /// 51 | /// 52 | public NtlmAuthenticator(ICredentials credentials) 53 | { 54 | if (credentials == null) throw new ArgumentNullException("credentials"); 55 | this.credentials = credentials; 56 | } 57 | 58 | public void Authenticate(IRestClient client, IRestRequest request) 59 | { 60 | request.Credentials = credentials; 61 | } 62 | } 63 | } 64 | 65 | #endif -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Text; 5 | 6 | namespace RestSharp.Authenticators.OAuth.Extensions 7 | { 8 | internal static class CollectionExtensions 9 | { 10 | public static IEnumerable AsEnumerable(this T item) 11 | { 12 | return new[] {item}; 13 | } 14 | 15 | public static IEnumerable And(this T item, T other) 16 | { 17 | return new[] {item, other}; 18 | } 19 | 20 | public static IEnumerable And(this IEnumerable items, T item) 21 | { 22 | foreach (var i in items) 23 | { 24 | yield return i; 25 | } 26 | 27 | yield return item; 28 | } 29 | 30 | public static K TryWithKey(this IDictionary dictionary, T key) 31 | { 32 | return dictionary.ContainsKey(key) ? dictionary[key] : default(K); 33 | } 34 | 35 | public static IEnumerable ToEnumerable(this object[] items) where T : class 36 | { 37 | foreach (var item in items) 38 | { 39 | var record = item as T; 40 | yield return record; 41 | } 42 | } 43 | 44 | public static void ForEach(this IEnumerable items, Action action) 45 | { 46 | foreach (var item in items) 47 | { 48 | action(item); 49 | } 50 | } 51 | 52 | #if !WINDOWS_PHONE && !SILVERLIGHT 53 | 54 | public static void AddRange(this IDictionary collection, NameValueCollection range) 55 | { 56 | foreach (var key in range.AllKeys) 57 | { 58 | collection.Add(key, range[key]); 59 | } 60 | } 61 | 62 | public static string ToQueryString(this NameValueCollection collection) 63 | { 64 | var sb = new StringBuilder(); 65 | if (collection.Count > 0) 66 | { 67 | sb.Append("?"); 68 | } 69 | 70 | var count = 0; 71 | foreach (var key in collection.AllKeys) 72 | { 73 | sb.AppendFormat("{0}={1}", key, collection[key].UrlEncode()); 74 | count++; 75 | 76 | if (count >= collection.Count) 77 | { 78 | continue; 79 | } 80 | sb.Append("&"); 81 | } 82 | return sb.ToString(); 83 | } 84 | 85 | #endif 86 | 87 | public static string Concatenate(this WebParameterCollection collection, string separator, string spacer) 88 | { 89 | var sb = new StringBuilder(); 90 | 91 | var total = collection.Count; 92 | var count = 0; 93 | 94 | foreach (var item in collection) 95 | { 96 | sb.Append(item.Name); 97 | sb.Append(separator); 98 | sb.Append(item.Value); 99 | 100 | count++; 101 | if (count < total) 102 | { 103 | sb.Append(spacer); 104 | } 105 | } 106 | 107 | return sb.ToString(); 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | 5 | namespace RestSharp.Authenticators.OAuth.Extensions 6 | { 7 | internal static class OAuthExtensions 8 | { 9 | public static string ToRequestValue(this OAuthSignatureMethod signatureMethod) 10 | { 11 | var value = signatureMethod.ToString().ToUpper(); 12 | var shaIndex = value.IndexOf("SHA1"); 13 | return shaIndex > -1 ? value.Insert(shaIndex, "-") : value; 14 | } 15 | 16 | public static OAuthSignatureMethod FromRequestValue(this string signatureMethod) 17 | { 18 | switch (signatureMethod) 19 | { 20 | case "HMAC-SHA1": 21 | return OAuthSignatureMethod.HmacSha1; 22 | case "RSA-SHA1": 23 | return OAuthSignatureMethod.RsaSha1; 24 | default: 25 | return OAuthSignatureMethod.PlainText; 26 | } 27 | } 28 | 29 | public static string HashWith(this string input, HashAlgorithm algorithm) 30 | { 31 | var data = Encoding.UTF8.GetBytes(input); 32 | var hash = algorithm.ComputeHash(data); 33 | return Convert.ToBase64String(hash); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Text.RegularExpressions; 7 | 8 | namespace RestSharp.Authenticators.OAuth.Extensions 9 | { 10 | internal static class StringExtensions 11 | { 12 | public static bool IsNullOrBlank(this string value) 13 | { 14 | return String.IsNullOrEmpty(value) || 15 | (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); 16 | } 17 | 18 | public static bool EqualsIgnoreCase(this string left, string right) 19 | { 20 | return String.Compare(left, right, StringComparison.OrdinalIgnoreCase) == 0; 21 | } 22 | 23 | public static bool EqualsAny(this string input, params string[] args) 24 | { 25 | return args.Aggregate(false, (current, arg) => current | input.Equals(arg)); 26 | } 27 | 28 | public static string FormatWith(this string format, params object[] args) 29 | { 30 | return String.Format(format, args); 31 | } 32 | 33 | public static string FormatWithInvariantCulture(this string format, params object[] args) 34 | { 35 | return String.Format(CultureInfo.InvariantCulture, format, args); 36 | } 37 | 38 | public static string Then(this string input, string value) 39 | { 40 | return String.Concat(input, value); 41 | } 42 | 43 | public static string UrlEncode(this string value) 44 | { 45 | // [DC] This is more correct than HttpUtility; it escapes spaces as %20, not + 46 | return Uri.EscapeDataString(value); 47 | } 48 | 49 | public static string UrlDecode(this string value) 50 | { 51 | return Uri.UnescapeDataString(value); 52 | } 53 | 54 | public static Uri AsUri(this string value) 55 | { 56 | return new Uri(value); 57 | } 58 | 59 | public static string ToBase64String(this byte[] input) 60 | { 61 | return Convert.ToBase64String(input); 62 | } 63 | 64 | public static byte[] GetBytes(this string input) 65 | { 66 | return Encoding.UTF8.GetBytes(input); 67 | } 68 | 69 | public static string PercentEncode(this string s) 70 | { 71 | var bytes = s.GetBytes(); 72 | var sb = new StringBuilder(); 73 | foreach (var b in bytes) 74 | { 75 | // [DC]: Support proper encoding of special characters (\n\r\t\b) 76 | if ((b > 7 && b < 11) || b == 13) 77 | { 78 | sb.Append(string.Format("%0{0:X}", b)); 79 | } 80 | else 81 | { 82 | sb.Append(string.Format("%{0:X}", b)); 83 | } 84 | } 85 | return sb.ToString(); 86 | } 87 | 88 | public static IDictionary ParseQueryString(this string query) 89 | { 90 | // [DC]: This method does not URL decode, and cannot handle decoded input 91 | if (query.StartsWith("?")) query = query.Substring(1); 92 | 93 | if (query.Equals(string.Empty)) 94 | { 95 | return new Dictionary(); 96 | } 97 | 98 | var parts = query.Split(new[] {'&'}); 99 | 100 | return parts.Select( 101 | part => part.Split(new[] {'='})).ToDictionary( 102 | pair => pair[0], pair => pair[1] 103 | ); 104 | } 105 | 106 | private const RegexOptions Options = 107 | #if !WINDOWS_PHONE && !SILVERLIGHT 108 | RegexOptions.Compiled | RegexOptions.IgnoreCase; 109 | #else 110 | RegexOptions.IgnoreCase; 111 | #endif 112 | } 113 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth.Extensions 4 | { 5 | internal static class TimeExtensions 6 | { 7 | public static DateTime FromNow(this TimeSpan value) 8 | { 9 | return new DateTime((DateTime.Now + value).Ticks); 10 | } 11 | 12 | public static DateTime FromUnixTime(this long seconds) 13 | { 14 | var time = new DateTime(1970, 1, 1); 15 | time = time.AddSeconds(seconds); 16 | 17 | return time.ToLocalTime(); 18 | } 19 | 20 | public static long ToUnixTime(this DateTime dateTime) 21 | { 22 | var timeSpan = (dateTime - new DateTime(1970, 1, 1)); 23 | var timestamp = (long) timeSpan.TotalSeconds; 24 | 25 | return timestamp; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/HttpPostParameter.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | internal class HttpPostParameter : WebParameter 6 | { 7 | public HttpPostParameter(string name, string value) : base(name, value) 8 | { 9 | } 10 | 11 | public virtual HttpPostParameterType Type { get; private set; } 12 | public virtual string FileName { get; private set; } 13 | public virtual string FilePath { get; private set; } 14 | public virtual Stream FileStream { get; set; } 15 | public virtual string ContentType { get; private set; } 16 | 17 | public static HttpPostParameter CreateFile(string name, string fileName, string filePath, string contentType) 18 | { 19 | var parameter = new HttpPostParameter(name, string.Empty) 20 | { 21 | Type = HttpPostParameterType.File, 22 | FileName = fileName, 23 | FilePath = filePath, 24 | ContentType = contentType, 25 | }; 26 | return parameter; 27 | } 28 | 29 | public static HttpPostParameter CreateFile(string name, string fileName, Stream fileStream, string contentType) 30 | { 31 | var parameter = new HttpPostParameter(name, string.Empty) 32 | { 33 | Type = HttpPostParameterType.File, 34 | FileName = fileName, 35 | FileStream = fileStream, 36 | ContentType = contentType, 37 | }; 38 | 39 | return parameter; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/HttpPostParameterType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | internal enum HttpPostParameterType 9 | { 10 | Field, 11 | File 12 | } 13 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/OAuthParameterHandling.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | public enum OAuthParameterHandling 9 | { 10 | HttpAuthorizationHeader, 11 | UrlOrPostParameters 12 | } 13 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/OAuthSignatureMethod.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | public enum OAuthSignatureMethod 9 | { 10 | HmacSha1, 11 | PlainText, 12 | RsaSha1 13 | } 14 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/OAuthSignatureTreatment.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | public enum OAuthSignatureTreatment 9 | { 10 | Escaped, 11 | Unescaped 12 | } 13 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/OAuthType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | public enum OAuthType 9 | { 10 | RequestToken, 11 | AccessToken, 12 | ProtectedResource, 13 | ClientAuthentication 14 | } 15 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp.Authenticators.OAuth 4 | { 5 | #if !SILVERLIGHT && !WINDOWS_PHONE 6 | [Serializable] 7 | #endif 8 | public class OAuthWebQueryInfo 9 | { 10 | public virtual string ConsumerKey { get; set; } 11 | public virtual string Token { get; set; } 12 | public virtual string Nonce { get; set; } 13 | public virtual string Timestamp { get; set; } 14 | public virtual string SignatureMethod { get; set; } 15 | public virtual string Signature { get; set; } 16 | public virtual string Version { get; set; } 17 | public virtual string Callback { get; set; } 18 | public virtual string Verifier { get; set; } 19 | public virtual string ClientMode { get; set; } 20 | public virtual string ClientUsername { get; set; } 21 | public virtual string ClientPassword { get; set; } 22 | public virtual string UserAgent { get; set; } 23 | public virtual string WebMethod { get; set; } 24 | public virtual OAuthParameterHandling ParameterHandling { get; set; } 25 | public virtual OAuthSignatureTreatment SignatureTreatment { get; set; } 26 | internal virtual string ConsumerSecret { get; set; } 27 | internal virtual string TokenSecret { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/WebPair.cs: -------------------------------------------------------------------------------- 1 | namespace RestSharp.Authenticators.OAuth 2 | { 3 | internal class WebPair 4 | { 5 | public WebPair(string name, string value) 6 | { 7 | Name = name; 8 | Value = value; 9 | } 10 | 11 | public string Value { get; set; } 12 | public string Name { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/WebPairCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | using System.Linq; 6 | 7 | namespace RestSharp.Authenticators.OAuth 8 | { 9 | internal class WebPairCollection : IList 10 | { 11 | private IList _parameters; 12 | 13 | public virtual WebPair this[string name] 14 | { 15 | get { return this.SingleOrDefault(p => p.Name.Equals(name)); } 16 | } 17 | 18 | public virtual IEnumerable Names 19 | { 20 | get { return _parameters.Select(p => p.Name); } 21 | } 22 | 23 | public virtual IEnumerable Values 24 | { 25 | get { return _parameters.Select(p => p.Value); } 26 | } 27 | 28 | public WebPairCollection(IEnumerable parameters) 29 | { 30 | _parameters = new List(parameters); 31 | } 32 | 33 | #if !WINDOWS_PHONE && !SILVERLIGHT 34 | public WebPairCollection(NameValueCollection collection) : this() 35 | { 36 | AddCollection(collection); 37 | } 38 | 39 | public virtual void AddRange(NameValueCollection collection) 40 | { 41 | AddCollection(collection); 42 | } 43 | 44 | private void AddCollection(NameValueCollection collection) 45 | { 46 | var parameters = collection.AllKeys.Select(key => new WebPair(key, collection[key])); 47 | foreach (var parameter in parameters) 48 | { 49 | _parameters.Add(parameter); 50 | } 51 | } 52 | #endif 53 | 54 | public WebPairCollection(IDictionary collection) : this() 55 | { 56 | AddCollection(collection); 57 | } 58 | 59 | public void AddCollection(IDictionary collection) 60 | { 61 | foreach (var key in collection.Keys) 62 | { 63 | var parameter = new WebPair(key, collection[key]); 64 | _parameters.Add(parameter); 65 | } 66 | } 67 | 68 | public WebPairCollection() 69 | { 70 | _parameters = new List(0); 71 | } 72 | 73 | public WebPairCollection(int capacity) 74 | { 75 | _parameters = new List(capacity); 76 | } 77 | 78 | private void AddCollection(IEnumerable collection) 79 | { 80 | foreach (var parameter in collection) 81 | { 82 | var pair = new WebPair(parameter.Name, parameter.Value); 83 | _parameters.Add(pair); 84 | } 85 | } 86 | 87 | public virtual void AddRange(WebPairCollection collection) 88 | { 89 | AddCollection(collection); 90 | } 91 | 92 | public virtual void AddRange(IEnumerable collection) 93 | { 94 | AddCollection(collection); 95 | } 96 | 97 | public virtual void Sort(Comparison comparison) 98 | { 99 | var sorted = new List(_parameters); 100 | sorted.Sort(comparison); 101 | _parameters = sorted; 102 | } 103 | 104 | public virtual bool RemoveAll(IEnumerable parameters) 105 | { 106 | var success = true; 107 | var array = parameters.ToArray(); 108 | for (var p = 0; p < array.Length; p++) 109 | { 110 | var parameter = array[p]; 111 | success &= _parameters.Remove(parameter); 112 | } 113 | return success && array.Length > 0; 114 | } 115 | 116 | public virtual void Add(string name, string value) 117 | { 118 | var pair = new WebPair(name, value); 119 | _parameters.Add(pair); 120 | } 121 | 122 | #region IList Members 123 | 124 | public virtual IEnumerator GetEnumerator() 125 | { 126 | return _parameters.GetEnumerator(); 127 | } 128 | 129 | IEnumerator IEnumerable.GetEnumerator() 130 | { 131 | return GetEnumerator(); 132 | } 133 | 134 | public virtual void Add(WebPair parameter) 135 | { 136 | _parameters.Add(parameter); 137 | } 138 | 139 | public virtual void Clear() 140 | { 141 | _parameters.Clear(); 142 | } 143 | 144 | public virtual bool Contains(WebPair parameter) 145 | { 146 | return _parameters.Contains(parameter); 147 | } 148 | 149 | public virtual void CopyTo(WebPair[] parameters, int arrayIndex) 150 | { 151 | _parameters.CopyTo(parameters, arrayIndex); 152 | } 153 | 154 | public virtual bool Remove(WebPair parameter) 155 | { 156 | return _parameters.Remove(parameter); 157 | } 158 | 159 | public virtual int Count 160 | { 161 | get { return _parameters.Count; } 162 | } 163 | 164 | public virtual bool IsReadOnly 165 | { 166 | get { return _parameters.IsReadOnly; } 167 | } 168 | 169 | public virtual int IndexOf(WebPair parameter) 170 | { 171 | return _parameters.IndexOf(parameter); 172 | } 173 | 174 | public virtual void Insert(int index, WebPair parameter) 175 | { 176 | _parameters.Insert(index, parameter); 177 | } 178 | 179 | public virtual void RemoveAt(int index) 180 | { 181 | _parameters.RemoveAt(index); 182 | } 183 | 184 | public virtual WebPair this[int index] 185 | { 186 | get { return _parameters[index]; } 187 | set { _parameters[index] = value; } 188 | } 189 | 190 | #endregion 191 | } 192 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/WebParameter.cs: -------------------------------------------------------------------------------- 1 | #if !Smartphone 2 | using System; 3 | using System.Diagnostics; 4 | 5 | #endif 6 | 7 | namespace RestSharp.Authenticators.OAuth 8 | { 9 | #if !Smartphone 10 | [DebuggerDisplay("{Name}:{Value}")] 11 | #endif 12 | #if !SILVERLIGHT && !WINDOWS_PHONE 13 | [Serializable] 14 | #endif 15 | internal class WebParameter : WebPair 16 | { 17 | public WebParameter(string name, string value) : base(name, value) 18 | { 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth/WebParameterCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Specialized; 3 | 4 | namespace RestSharp.Authenticators.OAuth 5 | { 6 | internal class WebParameterCollection : WebPairCollection 7 | { 8 | public WebParameterCollection(IEnumerable parameters) 9 | : base(parameters) 10 | { 11 | } 12 | 13 | #if !WINDOWS_PHONE && !SILVERLIGHT 14 | public WebParameterCollection(NameValueCollection collection) : base(collection) 15 | { 16 | } 17 | #endif 18 | 19 | public WebParameterCollection() 20 | { 21 | } 22 | 23 | public WebParameterCollection(int capacity) : base(capacity) 24 | { 25 | } 26 | 27 | public WebParameterCollection(IDictionary collection) : base(collection) 28 | { 29 | } 30 | 31 | public override void Add(string name, string value) 32 | { 33 | var parameter = new WebParameter(name, value); 34 | base.Add(parameter); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/OAuth2Authenticator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace RestSharp 5 | { 6 | /// 7 | /// Base class for OAuth 2 Authenticators. 8 | /// 9 | /// 10 | /// Since there are many ways to authenticate in OAuth2, 11 | /// this is used as a base class to differentiate between 12 | /// other authenticators. 13 | /// 14 | /// Any other OAuth2 authenticators must derive from this 15 | /// abstract class. 16 | /// 17 | public abstract class OAuth2Authenticator : IAuthenticator 18 | { 19 | /// 20 | /// Access token to be used when authenticating. 21 | /// 22 | private readonly string _accessToken; 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// 28 | /// The access token. 29 | /// 30 | public OAuth2Authenticator(string accessToken) 31 | { 32 | _accessToken = accessToken; 33 | } 34 | 35 | /// 36 | /// Gets the access token. 37 | /// 38 | public string AccessToken 39 | { 40 | get { return _accessToken; } 41 | } 42 | 43 | public abstract void Authenticate(IRestClient client, IRestRequest request); 44 | } 45 | 46 | /// 47 | /// The OAuth 2 authenticator using URI query parameter. 48 | /// 49 | /// 50 | /// Based on http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5.1.2 51 | /// 52 | public class OAuth2UriQueryParameterAuthenticator : OAuth2Authenticator 53 | { 54 | /// 55 | /// Initializes a new instance of the class. 56 | /// 57 | /// 58 | /// The access token. 59 | /// 60 | public OAuth2UriQueryParameterAuthenticator(string accessToken) 61 | : base(accessToken) 62 | { 63 | } 64 | 65 | public override void Authenticate(IRestClient client, IRestRequest request) 66 | { 67 | request.AddParameter("oauth_token", AccessToken, ParameterType.GetOrPost); 68 | } 69 | } 70 | 71 | /// 72 | /// The OAuth 2 authenticator using the authorization request header field. 73 | /// 74 | /// 75 | /// Based on http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-5.1.1 76 | /// 77 | public class OAuth2AuthorizationRequestHeaderAuthenticator : OAuth2Authenticator 78 | { 79 | /// 80 | /// Stores the Authorization header value as "[tokenType] accessToken". used for performance. 81 | /// 82 | private readonly string _authorizationValue; 83 | 84 | /// 85 | /// Initializes a new instance of the class. 86 | /// 87 | /// 88 | /// The access token. 89 | /// 90 | public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken) 91 | : this(accessToken, "OAuth") 92 | { 93 | } 94 | 95 | /// 96 | /// Initializes a new instance of the class. 97 | /// 98 | /// 99 | /// The access token. 100 | /// 101 | /// 102 | /// The token type. 103 | /// 104 | public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken, string tokenType) 105 | : base(accessToken) 106 | { 107 | // Conatenate during constructor so that it is only done once. can improve performance. 108 | _authorizationValue = tokenType + " " + accessToken; 109 | } 110 | 111 | public override void Authenticate(IRestClient client, IRestRequest request) 112 | { 113 | // only add the Authorization parameter if it hasn't been added. 114 | if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) 115 | { 116 | request.AddParameter("Authorization", _authorizationValue, ParameterType.HttpHeader); 117 | } 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /RestSharp/Authenticators/SimpleAuthenticator.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp 18 | { 19 | public class SimpleAuthenticator : IAuthenticator 20 | { 21 | private readonly string _usernameKey; 22 | private readonly string _username; 23 | private readonly string _passwordKey; 24 | private readonly string _password; 25 | 26 | public SimpleAuthenticator(string usernameKey, string username, string passwordKey, string password) { 27 | _usernameKey = usernameKey; 28 | _username = username; 29 | _passwordKey = passwordKey; 30 | _password = password; 31 | } 32 | 33 | public void Authenticate(IRestClient client, IRestRequest request) 34 | { 35 | request.AddParameter(_usernameKey, _username); 36 | request.AddParameter(_passwordKey, _password); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /RestSharp/Compression/ZLib/FlushType.cs: -------------------------------------------------------------------------------- 1 | #if WINDOWS_PHONE 2 | 3 | using System; 4 | using System.Net; 5 | 6 | namespace RestSharp.Compression.ZLib 7 | { 8 | 9 | /// 10 | /// Describes how to flush the current deflate operation. 11 | /// 12 | /// 13 | /// The different FlushType values are useful when using a Deflate in a streaming application. 14 | /// 15 | internal enum FlushType 16 | { 17 | /// No flush at all. 18 | None = 0, 19 | 20 | /// Closes the current block, but doesn't flush it to 21 | /// the output. Used internally only in hypothetical 22 | /// scenarios. This was supposed to be removed by Zlib, but it is 23 | /// still in use in some edge cases. 24 | /// 25 | Partial, 26 | 27 | /// 28 | /// Use this during compression to specify that all pending output should be 29 | /// flushed to the output buffer and the output should be aligned on a byte 30 | /// boundary. You might use this in a streaming communication scenario, so that 31 | /// the decompressor can get all input data available so far. When using this 32 | /// with a ZlibCodec, AvailableBytesIn will be zero after the call if 33 | /// enough output space has been provided before the call. Flushing will 34 | /// degrade compression and so it should be used only when necessary. 35 | /// 36 | Sync, 37 | 38 | /// 39 | /// Use this during compression to specify that all output should be flushed, as 40 | /// with FlushType.Sync, but also, the compression state should be reset 41 | /// so that decompression can restart from this point if previous compressed 42 | /// data has been damaged or if random access is desired. Using 43 | /// FlushType.Full too often can significantly degrade the compression. 44 | /// 45 | Full, 46 | 47 | /// Signals the end of the compression/decompression stream. 48 | Finish, 49 | } 50 | } 51 | 52 | #endif -------------------------------------------------------------------------------- /RestSharp/Compression/ZLib/ZLibConstants.cs: -------------------------------------------------------------------------------- 1 | // ZlibConstants.cs 2 | // ------------------------------------------------------------------ 3 | // 4 | // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. 5 | // All rights reserved. 6 | // 7 | // This code module is part of DotNetZip, a zipfile class library. 8 | // 9 | // ------------------------------------------------------------------ 10 | // 11 | // This code is licensed under the Microsoft Public License. 12 | // See the file License.txt for the license details. 13 | // More info on: http://dotnetzip.codeplex.com 14 | // 15 | // ------------------------------------------------------------------ 16 | // 17 | // last saved (in emacs): 18 | // Time-stamp: <2009-May-31 09:35:39> 19 | // 20 | // ------------------------------------------------------------------ 21 | // 22 | // This module defines constants used by the zlib class library. This 23 | // code is derived from the jzlib implementation of zlib, but 24 | // significantly modified. In keeping with the license for jzlib, the 25 | // copyright to that code is included here. 26 | // 27 | // ------------------------------------------------------------------ 28 | // 29 | // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. 30 | // 31 | // Redistribution and use in source and binary forms, with or without 32 | // modification, are permitted provided that the following conditions are met: 33 | // 34 | // 1. Redistributions of source code must retain the above copyright notice, 35 | // this list of conditions and the following disclaimer. 36 | // 37 | // 2. Redistributions in binary form must reproduce the above copyright 38 | // notice, this list of conditions and the following disclaimer in 39 | // the documentation and/or other materials provided with the distribution. 40 | // 41 | // 3. The names of the authors may not be used to endorse or promote products 42 | // derived from this software without specific prior written permission. 43 | // 44 | // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, 45 | // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 46 | // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, 47 | // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, 48 | // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 49 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 50 | // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 51 | // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 52 | // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 53 | // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 54 | // 55 | // ----------------------------------------------------------------------- 56 | // 57 | // This program is based on zlib-1.1.3; credit to authors 58 | // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) 59 | // and contributors of zlib. 60 | // 61 | // ----------------------------------------------------------------------- 62 | 63 | #if WINDOWS_PHONE 64 | 65 | using System; 66 | 67 | namespace RestSharp.Compression.ZLib 68 | { 69 | /// 70 | /// A bunch of constants used in the Zlib interface. 71 | /// 72 | internal static class ZlibConstants 73 | { 74 | /// 75 | /// The maximum number of window bits for the Deflate algorithm. 76 | /// 77 | public const int WindowBitsMax = 15; // 32K LZ77 window 78 | 79 | /// 80 | /// The default number of window bits for the Deflate algorithm. 81 | /// 82 | public const int WindowBitsDefault = WindowBitsMax; 83 | 84 | /// 85 | /// indicates everything is A-OK 86 | /// 87 | public const int Z_OK = 0; 88 | 89 | /// 90 | /// Indicates that the last operation reached the end of the stream. 91 | /// 92 | public const int Z_STREAM_END = 1; 93 | 94 | /// 95 | /// The operation ended in need of a dictionary. 96 | /// 97 | public const int Z_NEED_DICT = 2; 98 | 99 | /// 100 | /// There was an error with the stream - not enough data, not open and readable, etc. 101 | /// 102 | public const int Z_STREAM_ERROR = -2; 103 | 104 | /// 105 | /// There was an error with the data - not enough data, bad data, etc. 106 | /// 107 | public const int Z_DATA_ERROR = -3; 108 | 109 | /// 110 | /// There was an error with the working buffer. 111 | /// 112 | public const int Z_BUF_ERROR = -5; 113 | 114 | /// 115 | /// The size of the working buffer used in the ZlibCodec class. Defaults to 8192 bytes. 116 | /// 117 | public const int WorkingBufferSizeDefault = 8192; // 8192; // 0x8000; // 16384; // 1024; 118 | 119 | /// 120 | /// The minimum size of the working buffer used in the ZlibCodec class. Currently it is 128 bytes. 121 | /// 122 | public const int WorkingBufferSizeMin = 128; 123 | } 124 | 125 | } 126 | 127 | #endif -------------------------------------------------------------------------------- /RestSharp/Deserializers/DeserializeAsAttribute.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | 19 | namespace RestSharp.Deserializers 20 | { 21 | /// 22 | /// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer 23 | /// 24 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] 25 | public sealed class DeserializeAsAttribute : Attribute 26 | { 27 | /// 28 | /// The name to use for the serialized element 29 | /// 30 | public string Name { get; set; } 31 | 32 | /// 33 | /// Sets if the property to Deserialize is an Attribute or Element (Default: false) 34 | /// 35 | public bool Attribute { get; set; } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /RestSharp/Deserializers/DotNetXmlDeserializer.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System.IO; 18 | using System.Text; 19 | 20 | namespace RestSharp.Deserializers 21 | { 22 | /// 23 | /// Wrapper for System.Xml.Serialization.XmlSerializer. 24 | /// 25 | public class DotNetXmlDeserializer : IDeserializer 26 | { 27 | public string DateFormat { get; set; } 28 | 29 | public string Namespace { get; set; } 30 | 31 | public string RootElement { get; set; } 32 | 33 | public T Deserialize(IRestResponse response) 34 | { 35 | if (string.IsNullOrEmpty(response.Content)) 36 | { 37 | return default(T); 38 | } 39 | 40 | using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content))) 41 | { 42 | var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); 43 | return (T)serializer.Deserialize(stream); 44 | } 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /RestSharp/Deserializers/IDeserializer.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp.Deserializers 18 | { 19 | public interface IDeserializer 20 | { 21 | T Deserialize(IRestResponse response); 22 | string RootElement { get; set; } 23 | string Namespace { get; set; } 24 | string DateFormat { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /RestSharp/Enum.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp 18 | { 19 | /// 20 | /// Types of parameters that can be added to requests 21 | /// 22 | public enum ParameterType 23 | { 24 | Cookie, 25 | GetOrPost, 26 | UrlSegment, 27 | HttpHeader, 28 | RequestBody 29 | } 30 | 31 | /// 32 | /// Data formats 33 | /// 34 | public enum DataFormat 35 | { 36 | Json, 37 | Xml 38 | } 39 | 40 | /// 41 | /// HTTP method to use when making requests 42 | /// 43 | public enum Method 44 | { 45 | GET, 46 | POST, 47 | PUT, 48 | DELETE, 49 | HEAD, 50 | OPTIONS, 51 | PATCH 52 | } 53 | 54 | /// 55 | /// Format strings for commonly-used date formats 56 | /// 57 | public struct DateFormat 58 | { 59 | /// 60 | /// .NET format string for ISO 8601 date format 61 | /// 62 | public const string Iso8601 = "s"; 63 | /// 64 | /// .NET format string for roundtrip date format 65 | /// 66 | public const string RoundTrip = "u"; 67 | } 68 | 69 | /// 70 | /// Status for responses (surprised?) 71 | /// 72 | public enum ResponseStatus 73 | { 74 | None, 75 | Completed, 76 | Error, 77 | TimedOut, 78 | Aborted 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /RestSharp/Extensions/MiscExtensions.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System.Globalization; 18 | using System.IO; 19 | using System.Text; 20 | 21 | namespace RestSharp.Extensions 22 | { 23 | /// 24 | /// Extension method overload! 25 | /// 26 | public static class MiscExtensions 27 | { 28 | #if !WINDOWS_PHONE 29 | /// 30 | /// Save a byte array to a file 31 | /// 32 | /// Bytes to save 33 | /// Full path to save file to 34 | public static void SaveAs(this byte[] input, string path) 35 | { 36 | File.WriteAllBytes(path, input); 37 | } 38 | #endif 39 | 40 | /// 41 | /// Read a stream into a byte array 42 | /// 43 | /// Stream to read 44 | /// byte[] 45 | public static byte[] ReadAsBytes(this Stream input) 46 | { 47 | byte[] buffer = new byte[16 * 1024]; 48 | using (MemoryStream ms = new MemoryStream()) 49 | { 50 | int read; 51 | while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 52 | { 53 | ms.Write(buffer, 0, read); 54 | } 55 | return ms.ToArray(); 56 | } 57 | } 58 | 59 | /// 60 | /// Copies bytes from one stream to another 61 | /// 62 | /// The input stream. 63 | /// The output stream. 64 | public static void CopyTo(this Stream input, Stream output) 65 | { 66 | var buffer = new byte[32768]; 67 | while(true) 68 | { 69 | var read = input.Read(buffer, 0, buffer.Length); 70 | if(read <= 0) 71 | return; 72 | output.Write(buffer, 0, read); 73 | } 74 | } 75 | 76 | /// 77 | /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding. 78 | /// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx 79 | /// 80 | /// An array of bytes to convert 81 | /// The byte as a string. 82 | public static string AsString(this byte[] buffer) 83 | { 84 | if (buffer == null) return ""; 85 | 86 | // Ansi as default 87 | Encoding encoding = Encoding.UTF8; 88 | 89 | #if FRAMEWORK 90 | return encoding.GetString(buffer); 91 | #else 92 | if (buffer == null || buffer.Length == 0) 93 | return ""; 94 | 95 | /* 96 | EF BB BF UTF-8 97 | FF FE UTF-16 little endian 98 | FE FF UTF-16 big endian 99 | FF FE 00 00 UTF-32, little endian 100 | 00 00 FE FF UTF-32, big-endian 101 | */ 102 | 103 | if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf) 104 | { 105 | encoding = Encoding.UTF8; 106 | } 107 | else if (buffer[0] == 0xfe && buffer[1] == 0xff) 108 | { 109 | encoding = Encoding.Unicode; 110 | } 111 | else if (buffer[0] == 0xfe && buffer[1] == 0xff) 112 | { 113 | encoding = Encoding.BigEndianUnicode; // utf-16be 114 | } 115 | 116 | using (MemoryStream stream = new MemoryStream()) 117 | { 118 | stream.Write(buffer, 0, buffer.Length); 119 | stream.Seek(0, SeekOrigin.Begin); 120 | using (StreamReader reader = new StreamReader(stream, encoding)) 121 | { 122 | return reader.ReadToEnd(); 123 | } 124 | } 125 | #endif 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /RestSharp/Extensions/MonoHttp/Helpers.cs: -------------------------------------------------------------------------------- 1 | // 2 | // System.Web.Util.Helpers 3 | // 4 | // Authors: 5 | // Marek Habersack (mhabersack@novell.com) 6 | // 7 | // (C) 2009 Novell, Inc (http://novell.com) 8 | 9 | // 10 | // Permission is hereby granted, free of charge, to any person obtaining 11 | // a copy of this software and associated documentation files (the 12 | // "Software"), to deal in the Software without restriction, including 13 | // without limitation the rights to use, copy, modify, merge, publish, 14 | // distribute, sublicense, and/or sell copies of the Software, and to 15 | // permit persons to whom the Software is furnished to do so, subject to 16 | // the following conditions: 17 | // 18 | // The above copyright notice and this permission notice shall be 19 | // included in all copies or substantial portions of the Software. 20 | // 21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | using System; 30 | using System.Globalization; 31 | 32 | namespace RestSharp.Contrib 33 | { 34 | class Helpers 35 | { 36 | public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; 37 | } 38 | } -------------------------------------------------------------------------------- /RestSharp/Extensions/ReflectionExtensions.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Globalization; 19 | using System.Linq; 20 | using System.Reflection; 21 | 22 | namespace RestSharp.Extensions 23 | { 24 | /// 25 | /// Reflection extensions 26 | /// 27 | public static class ReflectionExtensions 28 | { 29 | /// 30 | /// Retrieve an attribute from a member (property) 31 | /// 32 | /// Type of attribute to retrieve 33 | /// Member to retrieve attribute from 34 | /// 35 | public static T GetAttribute(this MemberInfo prop) where T : Attribute { 36 | return Attribute.GetCustomAttribute(prop, typeof(T)) as T; 37 | } 38 | 39 | /// 40 | /// Retrieve an attribute from a type 41 | /// 42 | /// Type of attribute to retrieve 43 | /// Type to retrieve attribute from 44 | /// 45 | public static T GetAttribute(this Type type) where T : Attribute { 46 | return Attribute.GetCustomAttribute(type, typeof(T)) as T; 47 | } 48 | 49 | /// 50 | /// Checks a type to see if it derives from a raw generic (e.g. List[[]]) 51 | /// 52 | /// 53 | /// 54 | /// 55 | public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) { 56 | while (toCheck != typeof(object)) { 57 | var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; 58 | if (generic == cur) { 59 | return true; 60 | } 61 | toCheck = toCheck.BaseType; 62 | } 63 | return false; 64 | } 65 | 66 | public static object ChangeType(this object source, Type newType) 67 | { 68 | #if FRAMEWORK 69 | return Convert.ChangeType(source, newType); 70 | #else 71 | return Convert.ChangeType(source, newType, null); 72 | #endif 73 | } 74 | 75 | public static object ChangeType(this object source, Type newType, CultureInfo culture) 76 | { 77 | #if FRAMEWORK || SILVERLIGHT || WINDOWS_PHONE 78 | return Convert.ChangeType(source, newType, culture); 79 | #else 80 | return Convert.ChangeType(source, newType, null); 81 | #endif 82 | } 83 | 84 | /// 85 | /// Find a value from a System.Enum by trying several possible variants 86 | /// of the string value of the enum. 87 | /// 88 | /// Type of enum 89 | /// Value for which to search 90 | /// The culture used to calculate the name variants 91 | /// 92 | public static object FindEnumValue(this Type type, string value, CultureInfo culture) 93 | { 94 | #if FRAMEWORK 95 | var ret = Enum.GetValues( type ) 96 | .Cast() 97 | .FirstOrDefault(v => v.ToString().GetNameVariants(culture).Contains(value, StringComparer.Create(culture, true))); 98 | 99 | if (ret == null) 100 | { 101 | int enumValueAsInt; 102 | if (Int32.TryParse(value, out enumValueAsInt) && Enum.IsDefined(type, enumValueAsInt)) 103 | { 104 | ret = (Enum) Enum.ToObject(type, enumValueAsInt); 105 | } 106 | } 107 | 108 | return ret; 109 | #else 110 | return Enum.Parse(type, value, true); 111 | #endif 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /RestSharp/Extensions/ResponseExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp.Extensions 7 | { 8 | public static class ResponseExtensions 9 | { 10 | public static IRestResponse toAsyncResponse(this IRestResponse response) 11 | { 12 | return new RestResponse 13 | { 14 | ContentEncoding = response.ContentEncoding, 15 | ContentLength = response.ContentLength, 16 | ContentType = response.ContentType, 17 | Cookies = response.Cookies, 18 | ErrorMessage = response.ErrorMessage, 19 | Headers = response.Headers, 20 | RawBytes = response.RawBytes, 21 | ResponseStatus = response.ResponseStatus, 22 | ResponseUri = response.ResponseUri, 23 | Server = response.Server, 24 | StatusCode = response.StatusCode, 25 | StatusDescription = response.StatusDescription 26 | }; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /RestSharp/Extensions/XmlExtensions.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System.Xml.Linq; 18 | 19 | namespace RestSharp.Extensions 20 | { 21 | /// 22 | /// XML Extension Methods 23 | /// 24 | public static class XmlExtensions 25 | { 26 | /// 27 | /// Returns the name of an element with the namespace if specified 28 | /// 29 | /// Element name 30 | /// XML Namespace 31 | /// 32 | public static XName AsNamespaced(this string name, string @namespace) { 33 | XName xName = name; 34 | 35 | if (@namespace.HasValue()) 36 | xName = XName.Get(name, @namespace); 37 | 38 | return xName; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /RestSharp/FileParameter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace RestSharp 5 | { 6 | /// 7 | /// Container for files to be uploaded with requests 8 | /// 9 | public class FileParameter 10 | { 11 | /// 12 | /// Creates a file parameter from an array of bytes. 13 | /// 14 | ///The parameter name to use in the request. 15 | ///The data to use as the file's contents. 16 | ///The filename to use in the request. 17 | ///The content type to use in the request. 18 | ///The 19 | public static FileParameter Create(string name, byte[] data, string filename, string contentType) 20 | { 21 | #if FRAMEWORK 22 | var length = data.LongLength; 23 | #else 24 | var length = (long)data.Length; 25 | #endif 26 | return new FileParameter 27 | { 28 | Writer = s => s.Write(data, 0, data.Length), 29 | FileName = filename, 30 | ContentType = contentType, 31 | ContentLength = length, 32 | Name = name 33 | }; 34 | } 35 | 36 | /// 37 | /// Creates a file parameter from an array of bytes. 38 | /// 39 | ///The parameter name to use in the request. 40 | ///The data to use as the file's contents. 41 | ///The filename to use in the request. 42 | ///The using the default content type. 43 | public static FileParameter Create(string name, byte[] data, string filename) 44 | { 45 | return Create(name, data, filename, null); 46 | } 47 | 48 | /// 49 | /// The length of data to be sent 50 | /// 51 | public long ContentLength { get; set; } 52 | /// 53 | /// Provides raw data for file 54 | /// 55 | public Action Writer { get; set; } 56 | /// 57 | /// Name of the file to use when uploading 58 | /// 59 | public string FileName { get; set; } 60 | /// 61 | /// MIME content type of file 62 | /// 63 | public string ContentType { get; set; } 64 | /// 65 | /// Name of the parameter 66 | /// 67 | public string Name { get; set; } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /RestSharp/HttpCookie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace RestSharp 4 | { 5 | /// 6 | /// Representation of an HTTP cookie 7 | /// 8 | public class HttpCookie 9 | { 10 | /// 11 | /// Comment of the cookie 12 | /// 13 | public string Comment { get; set; } 14 | /// 15 | /// Comment of the cookie 16 | /// 17 | public Uri CommentUri { get; set; } 18 | /// 19 | /// Indicates whether the cookie should be discarded at the end of the session 20 | /// 21 | public bool Discard { get; set; } 22 | /// 23 | /// Domain of the cookie 24 | /// 25 | public string Domain { get; set; } 26 | /// 27 | /// Indicates whether the cookie is expired 28 | /// 29 | public bool Expired { get; set; } 30 | /// 31 | /// Date and time that the cookie expires 32 | /// 33 | public DateTime Expires { get; set; } 34 | /// 35 | /// Indicates that this cookie should only be accessed by the server 36 | /// 37 | public bool HttpOnly { get; set; } 38 | /// 39 | /// Name of the cookie 40 | /// 41 | public string Name { get; set; } 42 | /// 43 | /// Path of the cookie 44 | /// 45 | public string Path { get; set; } 46 | /// 47 | /// Port of the cookie 48 | /// 49 | public string Port { get; set; } 50 | /// 51 | /// Indicates that the cookie should only be sent over secure channels 52 | /// 53 | public bool Secure { get; set; } 54 | /// 55 | /// Date and time the cookie was created 56 | /// 57 | public DateTime TimeStamp { get; set; } 58 | /// 59 | /// Value of the cookie 60 | /// 61 | public string Value { get; set; } 62 | /// 63 | /// Version of the cookie 64 | /// 65 | public int Version { get; set; } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /RestSharp/HttpFile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace RestSharp 5 | { 6 | /// 7 | /// Container for HTTP file 8 | /// 9 | public class HttpFile 10 | { 11 | 12 | /// 13 | /// The length of data to be sent 14 | /// 15 | public long ContentLength { get; set; } 16 | /// 17 | /// Provides raw data for file 18 | /// 19 | public Action Writer { get; set; } 20 | /// 21 | /// Name of the file to use when uploading 22 | /// 23 | public string FileName { get; set; } 24 | /// 25 | /// MIME content type of file 26 | /// 27 | public string ContentType { get; set; } 28 | /// 29 | /// Name of the parameter 30 | /// 31 | public string Name { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /RestSharp/HttpHeader.cs: -------------------------------------------------------------------------------- 1 | namespace RestSharp 2 | { 3 | /// 4 | /// Representation of an HTTP header 5 | /// 6 | public class HttpHeader 7 | { 8 | /// 9 | /// Name of the header 10 | /// 11 | public string Name { get; set; } 12 | /// 13 | /// Value of the header 14 | /// 15 | public string Value { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /RestSharp/HttpParameter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace RestSharp 7 | { 8 | /// 9 | /// Representation of an HTTP parameter (QueryString or Form value) 10 | /// 11 | public class HttpParameter 12 | { 13 | /// 14 | /// Name of the parameter 15 | /// 16 | public string Name { get; set; } 17 | /// 18 | /// Value of the parameter 19 | /// 20 | public string Value { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /RestSharp/HttpResponse.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using System.Net; 20 | using RestSharp.Extensions; 21 | 22 | namespace RestSharp 23 | { 24 | /// 25 | /// HTTP response data 26 | /// 27 | public class HttpResponse : IHttpResponse 28 | { 29 | private string _content; 30 | 31 | /// 32 | /// Default constructor 33 | /// 34 | public HttpResponse() 35 | { 36 | Headers = new List(); 37 | Cookies = new List(); 38 | } 39 | 40 | /// 41 | /// MIME content type of response 42 | /// 43 | public string ContentType { get; set; } 44 | /// 45 | /// Length in bytes of the response content 46 | /// 47 | public long ContentLength { get; set; } 48 | /// 49 | /// Encoding of the response content 50 | /// 51 | public string ContentEncoding { get; set; } 52 | /// 53 | /// Lazy-loaded string representation of response content 54 | /// 55 | public string Content 56 | { 57 | get 58 | { 59 | if (_content == null) 60 | { 61 | _content = RawBytes.AsString(); 62 | } 63 | return _content; 64 | } 65 | } 66 | /// 67 | /// HTTP response status code 68 | /// 69 | public HttpStatusCode StatusCode { get; set; } 70 | /// 71 | /// Description of HTTP status returned 72 | /// 73 | public string StatusDescription { get; set; } 74 | /// 75 | /// Response content 76 | /// 77 | public byte[] RawBytes { get; set; } 78 | /// 79 | /// The URL that actually responded to the content (different from request if redirected) 80 | /// 81 | public Uri ResponseUri { get; set; } 82 | /// 83 | /// HttpWebResponse.Server 84 | /// 85 | public string Server { get; set; } 86 | /// 87 | /// Headers returned by server with the response 88 | /// 89 | public IList Headers { get; private set; } 90 | /// 91 | /// Cookies returned by server with the response 92 | /// 93 | public IList Cookies { get; private set; } 94 | 95 | private ResponseStatus _responseStatus = ResponseStatus.None; 96 | /// 97 | /// Status of the request. Will return Error for transport errors. 98 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead 99 | /// 100 | public ResponseStatus ResponseStatus 101 | { 102 | get 103 | { 104 | return _responseStatus; 105 | } 106 | set 107 | { 108 | _responseStatus = value; 109 | } 110 | } 111 | 112 | /// 113 | /// Transport or other non-HTTP error generated while attempting request 114 | /// 115 | public string ErrorMessage { get; set; } 116 | 117 | /// 118 | /// Exception thrown when error is encountered. 119 | /// 120 | public Exception ErrorException { get; set; } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /RestSharp/IHttp.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using System.IO; 20 | using System.Net; 21 | using System.Security.Cryptography.X509Certificates; 22 | 23 | namespace RestSharp 24 | { 25 | public interface IHttp 26 | { 27 | Action ResponseWriter { get; set; } 28 | CookieContainer CookieContainer { get; set; } 29 | ICredentials Credentials { get; set; } 30 | string UserAgent { get; set; } 31 | int Timeout { get; set; } 32 | #if !SILVERLIGHT 33 | bool FollowRedirects { get; set; } 34 | #endif 35 | #if FRAMEWORK 36 | X509CertificateCollection ClientCertificates { get; set; } 37 | int? MaxRedirects { get; set; } 38 | #endif 39 | 40 | IList Headers { get; } 41 | IList Parameters { get; } 42 | IList Files { get; } 43 | IList Cookies { get; } 44 | string RequestBody { get; set; } 45 | string RequestContentType { get; set; } 46 | 47 | /// 48 | /// An alternative to RequestBody, for when the caller already has the byte array. 49 | /// 50 | byte[] RequestBodyBytes { get; set; } 51 | 52 | Uri Url { get; set; } 53 | 54 | HttpWebRequest DeleteAsync(Action action); 55 | HttpWebRequest GetAsync(Action action); 56 | HttpWebRequest HeadAsync(Action action); 57 | HttpWebRequest OptionsAsync(Action action); 58 | HttpWebRequest PostAsync(Action action); 59 | HttpWebRequest PutAsync(Action action); 60 | HttpWebRequest PatchAsync(Action action); 61 | HttpWebRequest AsPostAsync(Action action, string httpMethod); 62 | HttpWebRequest AsGetAsync(Action action, string httpMethod); 63 | 64 | #if FRAMEWORK 65 | HttpResponse Delete(); 66 | HttpResponse Get(); 67 | HttpResponse Head(); 68 | HttpResponse Options(); 69 | HttpResponse Post(); 70 | HttpResponse Put(); 71 | HttpResponse Patch(); 72 | HttpResponse AsPost(string httpMethod); 73 | HttpResponse AsGet(string httpMethod); 74 | 75 | IWebProxy Proxy { get; set; } 76 | #endif 77 | } 78 | } -------------------------------------------------------------------------------- /RestSharp/IHttpFactory.cs: -------------------------------------------------------------------------------- 1 | namespace RestSharp 2 | { 3 | public interface IHttpFactory 4 | { 5 | IHttp Create(); 6 | } 7 | 8 | public class SimpleFactory : IHttpFactory where T : IHttp, new() 9 | { 10 | public IHttp Create() 11 | { 12 | return new T(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /RestSharp/IHttpResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | 5 | namespace RestSharp 6 | { 7 | /// 8 | /// HTTP response data 9 | /// 10 | public interface IHttpResponse 11 | { 12 | /// 13 | /// MIME content type of response 14 | /// 15 | string ContentType { get; set; } 16 | 17 | /// 18 | /// Length in bytes of the response content 19 | /// 20 | long ContentLength { get; set; } 21 | 22 | /// 23 | /// Encoding of the response content 24 | /// 25 | string ContentEncoding { get; set; } 26 | 27 | /// 28 | /// String representation of response content 29 | /// 30 | string Content { get; } 31 | 32 | /// 33 | /// HTTP response status code 34 | /// 35 | HttpStatusCode StatusCode { get; set; } 36 | 37 | /// 38 | /// Description of HTTP status returned 39 | /// 40 | string StatusDescription { get; set; } 41 | 42 | /// 43 | /// Response content 44 | /// 45 | byte[] RawBytes { get; set; } 46 | 47 | /// 48 | /// The URL that actually responded to the content (different from request if redirected) 49 | /// 50 | Uri ResponseUri { get; set; } 51 | 52 | /// 53 | /// HttpWebResponse.Server 54 | /// 55 | string Server { get; set; } 56 | 57 | /// 58 | /// Headers returned by server with the response 59 | /// 60 | IList Headers { get; } 61 | 62 | /// 63 | /// Cookies returned by server with the response 64 | /// 65 | IList Cookies { get; } 66 | 67 | /// 68 | /// Status of the request. Will return Error for transport errors. 69 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead 70 | /// 71 | ResponseStatus ResponseStatus { get; set; } 72 | 73 | /// 74 | /// Transport or other non-HTTP error generated while attempting request 75 | /// 76 | string ErrorMessage { get; set; } 77 | 78 | /// 79 | /// Exception thrown when error is encountered. 80 | /// 81 | Exception ErrorException { get; set; } 82 | } 83 | } -------------------------------------------------------------------------------- /RestSharp/IRestClient.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Net; 19 | using System.Collections.Generic; 20 | using System.Security.Cryptography.X509Certificates; 21 | 22 | namespace RestSharp 23 | { 24 | /// 25 | /// 26 | /// 27 | public interface IRestClient 28 | { 29 | /// 30 | /// 31 | /// 32 | CookieContainer CookieContainer { get; set; } 33 | /// 34 | /// 35 | /// 36 | string UserAgent { get; set; } 37 | /// 38 | /// 39 | /// 40 | int Timeout { get; set; } 41 | /// 42 | /// 43 | /// 44 | bool UseSynchronizationContext { get; set; } 45 | /// 46 | /// 47 | /// 48 | IAuthenticator Authenticator { get; set; } 49 | /// 50 | /// 51 | /// 52 | string BaseUrl { get; set; } 53 | /// 54 | /// 55 | /// 56 | IList DefaultParameters { get; } 57 | /// 58 | /// 59 | /// 60 | /// 61 | RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action callback); 62 | /// 63 | /// 64 | /// 65 | /// 66 | RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action, RestRequestAsyncHandle> callback); 67 | 68 | #if FRAMEWORK 69 | /// 70 | /// X509CertificateCollection to be sent with request 71 | /// 72 | X509CertificateCollection ClientCertificates { get; set; } 73 | IRestResponse Execute(IRestRequest request); 74 | IRestResponse Execute(IRestRequest request) where T : new(); 75 | 76 | IWebProxy Proxy { get; set; } 77 | #endif 78 | 79 | Uri BuildUri(IRestRequest request); 80 | 81 | /// 82 | /// Executes a GET-style request and callback asynchronously, authenticating if needed 83 | /// 84 | /// Request to be executed 85 | /// Callback function to be executed upon completion providing access to the async handle. 86 | /// The HTTP method to execute 87 | RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action callback, string httpMethod); 88 | 89 | /// 90 | /// Executes a POST-style request and callback asynchronously, authenticating if needed 91 | /// 92 | /// Request to be executed 93 | /// Callback function to be executed upon completion providing access to the async handle. 94 | /// The HTTP method to execute 95 | RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action callback, string httpMethod); 96 | 97 | /// 98 | /// Executes a GET-style request and callback asynchronously, authenticating if needed 99 | /// 100 | /// Target deserialization type 101 | /// Request to be executed 102 | /// Callback function to be executed upon completion 103 | /// The HTTP method to execute 104 | RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action, RestRequestAsyncHandle> callback, string httpMethod); 105 | 106 | /// 107 | /// Executes a GET-style request and callback asynchronously, authenticating if needed 108 | /// 109 | /// Target deserialization type 110 | /// Request to be executed 111 | /// Callback function to be executed upon completion 112 | /// The HTTP method to execute 113 | RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action, RestRequestAsyncHandle> callback, string httpMethod); 114 | 115 | #if FRAMEWORK 116 | IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod); 117 | IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod); 118 | IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) where T : new(); 119 | IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) where T : new(); 120 | #endif 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /RestSharp/IRestResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | 5 | namespace RestSharp 6 | { 7 | /// 8 | /// Container for data sent back from API 9 | /// 10 | public interface IRestResponse 11 | { 12 | /// 13 | /// The RestRequest that was made to get this RestResponse 14 | /// 15 | /// 16 | /// Mainly for debugging if ResponseStatus is not OK 17 | /// 18 | IRestRequest Request { get; set; } 19 | 20 | /// 21 | /// MIME content type of response 22 | /// 23 | string ContentType { get; set; } 24 | 25 | /// 26 | /// Length in bytes of the response content 27 | /// 28 | long ContentLength { get; set; } 29 | 30 | /// 31 | /// Encoding of the response content 32 | /// 33 | string ContentEncoding { get; set; } 34 | 35 | /// 36 | /// String representation of response content 37 | /// 38 | string Content { get; set; } 39 | 40 | /// 41 | /// HTTP response status code 42 | /// 43 | HttpStatusCode StatusCode { get; set; } 44 | 45 | /// 46 | /// Description of HTTP status returned 47 | /// 48 | string StatusDescription { get; set; } 49 | 50 | /// 51 | /// Response content 52 | /// 53 | byte[] RawBytes { get; set; } 54 | 55 | /// 56 | /// The URL that actually responded to the content (different from request if redirected) 57 | /// 58 | Uri ResponseUri { get; set; } 59 | 60 | /// 61 | /// HttpWebResponse.Server 62 | /// 63 | string Server { get; set; } 64 | 65 | /// 66 | /// Cookies returned by server with the response 67 | /// 68 | IList Cookies { get; } 69 | 70 | /// 71 | /// Headers returned by server with the response 72 | /// 73 | IList Headers { get; } 74 | 75 | /// 76 | /// Status of the request. Will return Error for transport errors. 77 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead 78 | /// 79 | ResponseStatus ResponseStatus { get; set; } 80 | 81 | /// 82 | /// Transport or other non-HTTP error generated while attempting request 83 | /// 84 | string ErrorMessage { get; set; } 85 | 86 | /// 87 | /// The exception thrown during the request, if any 88 | /// 89 | Exception ErrorException { get; set; } 90 | } 91 | 92 | /// 93 | /// Container for data sent back from API including deserialized data 94 | /// 95 | /// Type of data to deserialize to 96 | public interface IRestResponse : IRestResponse 97 | { 98 | /// 99 | /// Deserialized entity data 100 | /// 101 | T Data { get; set; } 102 | } 103 | } -------------------------------------------------------------------------------- /RestSharp/Parameter.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp 18 | { 19 | /// 20 | /// Parameter container for REST requests 21 | /// 22 | public class Parameter 23 | { 24 | /// 25 | /// Name of the parameter 26 | /// 27 | public string Name { get; set; } 28 | /// 29 | /// Value of the parameter 30 | /// 31 | public object Value { get; set; } 32 | /// 33 | /// Type of the parameter 34 | /// 35 | public ParameterType Type { get; set; } 36 | 37 | /// 38 | /// Return a human-readable representation of this parameter 39 | /// 40 | /// String 41 | public override string ToString() { 42 | return string.Format("{0}={1}", Name, Value); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /RestSharp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("RestSharp")] 9 | 10 | // Setting ComVisible to false makes the types in this assembly not visible 11 | // to COM components. If you need to access a type in this assembly from 12 | // COM, set the ComVisible attribute to true on that type. 13 | [assembly: ComVisible(false)] 14 | 15 | // The following GUID is for the ID of the typelib if this project is exposed to COM 16 | [assembly: Guid("d2b12a34-b748-47f9-8ad6-f84da992c64b")] 17 | 18 | [assembly: InternalsVisibleTo("RestSharp.IntegrationTests")] -------------------------------------------------------------------------------- /RestSharp/RestClient.Sync.cs: -------------------------------------------------------------------------------- 1 | #if FRAMEWORK 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Text; 7 | using RestSharp.Deserializers; 8 | 9 | namespace RestSharp 10 | { 11 | public partial class RestClient 12 | { 13 | 14 | 15 | /// 16 | /// Executes the specified request and downloads the response data 17 | /// 18 | /// Request to execute 19 | /// Response data 20 | public byte[] DownloadData(IRestRequest request) 21 | { 22 | var response = Execute(request); 23 | return response.RawBytes; 24 | } 25 | 26 | /// 27 | /// Executes the request and returns a response, authenticating if needed 28 | /// 29 | /// Request to be executed 30 | /// RestResponse 31 | public virtual IRestResponse Execute(IRestRequest request) 32 | { 33 | var method = Enum.GetName(typeof(Method), request.Method); 34 | switch (request.Method) 35 | { 36 | case Method.POST: 37 | case Method.PUT: 38 | case Method.PATCH: 39 | return Execute(request, method, DoExecuteAsPost); 40 | default: 41 | return Execute(request, method, DoExecuteAsGet); 42 | } 43 | } 44 | 45 | public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) 46 | { 47 | return Execute(request, httpMethod, DoExecuteAsGet); 48 | } 49 | 50 | public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) 51 | { 52 | request.Method = Method.POST; // Required by RestClient.BuildUri... 53 | return Execute(request, httpMethod, DoExecuteAsPost); 54 | } 55 | 56 | private IRestResponse Execute(IRestRequest request, string httpMethod, Func getResponse) 57 | { 58 | AuthenticateIfNeeded(this, request); 59 | 60 | IRestResponse response = new RestResponse(); 61 | try 62 | { 63 | var http = HttpFactory.Create(); 64 | 65 | ConfigureHttp(request, http); 66 | 67 | response = ConvertToRestResponse(request, getResponse(http, httpMethod)); 68 | response.Request = request; 69 | response.Request.IncreaseNumAttempts(); 70 | 71 | } 72 | catch (Exception ex) 73 | { 74 | response.ResponseStatus = ResponseStatus.Error; 75 | response.ErrorMessage = ex.Message; 76 | response.ErrorException = ex; 77 | } 78 | 79 | return response; 80 | } 81 | 82 | private static HttpResponse DoExecuteAsGet(IHttp http, string method) 83 | { 84 | return http.AsGet(method); 85 | } 86 | 87 | private static HttpResponse DoExecuteAsPost(IHttp http, string method) 88 | { 89 | return http.AsPost(method); 90 | } 91 | 92 | /// 93 | /// Executes the specified request and deserializes the response content using the appropriate content handler 94 | /// 95 | /// Target deserialization type 96 | /// Request to execute 97 | /// RestResponse[[T]] with deserialized data in Data property 98 | public virtual IRestResponse Execute(IRestRequest request) where T : new() 99 | { 100 | return Deserialize(request, Execute(request)); 101 | } 102 | 103 | public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) where T : new() 104 | { 105 | return Deserialize(request, ExecuteAsGet(request, httpMethod)); 106 | } 107 | 108 | public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) where T : new() 109 | { 110 | return Deserialize(request, ExecuteAsPost(request, httpMethod)); 111 | } 112 | } 113 | } 114 | #endif -------------------------------------------------------------------------------- /RestSharp/RestRequestAsyncHandle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | namespace RestSharp 4 | { 5 | public class RestRequestAsyncHandle 6 | { 7 | public HttpWebRequest WebRequest; 8 | 9 | public RestRequestAsyncHandle() 10 | { 11 | } 12 | 13 | public RestRequestAsyncHandle(HttpWebRequest webRequest) 14 | { 15 | WebRequest = webRequest; 16 | } 17 | 18 | public void Abort() 19 | { 20 | if (WebRequest != null) 21 | WebRequest.Abort(); 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /RestSharp/RestResponse.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Collections.Generic; 19 | using System.Net; 20 | using RestSharp.Extensions; 21 | 22 | namespace RestSharp 23 | { 24 | /// 25 | /// Base class for common properties shared by RestResponse and RestResponse[[T]] 26 | /// 27 | public abstract class RestResponseBase 28 | { 29 | private string _content; 30 | 31 | /// 32 | /// Default constructor 33 | /// 34 | public RestResponseBase() 35 | { 36 | Headers = new List(); 37 | Cookies = new List(); 38 | } 39 | /// 40 | /// The RestRequest that was made to get this RestResponse 41 | /// 42 | /// 43 | /// Mainly for debugging if ResponseStatus is not OK 44 | /// 45 | public IRestRequest Request { get; set; } 46 | /// 47 | /// MIME content type of response 48 | /// 49 | public string ContentType { get; set; } 50 | /// 51 | /// Length in bytes of the response content 52 | /// 53 | public long ContentLength { get; set; } 54 | /// 55 | /// Encoding of the response content 56 | /// 57 | public string ContentEncoding { get; set; } 58 | /// 59 | /// String representation of response content 60 | /// 61 | public string Content 62 | { 63 | get 64 | { 65 | if (_content == null) 66 | { 67 | _content = RawBytes.AsString(); 68 | } 69 | return _content; 70 | } 71 | set 72 | { 73 | _content = value; 74 | } 75 | } 76 | /// 77 | /// HTTP response status code 78 | /// 79 | public HttpStatusCode StatusCode { get; set; } 80 | /// 81 | /// Description of HTTP status returned 82 | /// 83 | public string StatusDescription { get; set; } 84 | /// 85 | /// Response content 86 | /// 87 | public byte[] RawBytes { get; set; } 88 | /// 89 | /// The URL that actually responded to the content (different from request if redirected) 90 | /// 91 | public Uri ResponseUri { get; set; } 92 | /// 93 | /// HttpWebResponse.Server 94 | /// 95 | public string Server { get; set; } 96 | /// 97 | /// Cookies returned by server with the response 98 | /// 99 | public IList Cookies { get; protected internal set; } 100 | /// 101 | /// Headers returned by server with the response 102 | /// 103 | public IList Headers { get; protected internal set; } 104 | 105 | private ResponseStatus _responseStatus = ResponseStatus.None; 106 | /// 107 | /// Status of the request. Will return Error for transport errors. 108 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead 109 | /// 110 | public ResponseStatus ResponseStatus 111 | { 112 | get 113 | { 114 | return _responseStatus; 115 | } 116 | set 117 | { 118 | _responseStatus = value; 119 | } 120 | } 121 | 122 | /// 123 | /// Transport or other non-HTTP error generated while attempting request 124 | /// 125 | public string ErrorMessage { get; set; } 126 | 127 | /// 128 | /// The exception thrown during the request, if any 129 | /// 130 | public Exception ErrorException { get; set; } 131 | } 132 | 133 | /// 134 | /// Container for data sent back from API including deserialized data 135 | /// 136 | /// Type of data to deserialize to 137 | public class RestResponse : RestResponseBase, IRestResponse 138 | { 139 | /// 140 | /// Deserialized entity data 141 | /// 142 | public T Data { get; set; } 143 | 144 | public static explicit operator RestResponse(RestResponse response) 145 | { 146 | return new RestResponse 147 | { 148 | ContentEncoding = response.ContentEncoding, 149 | ContentLength = response.ContentLength, 150 | ContentType = response.ContentType, 151 | Cookies = response.Cookies, 152 | ErrorMessage = response.ErrorMessage, 153 | Headers = response.Headers, 154 | RawBytes = response.RawBytes, 155 | ResponseStatus = response.ResponseStatus, 156 | ResponseUri = response.ResponseUri, 157 | Server = response.Server, 158 | StatusCode = response.StatusCode, 159 | StatusDescription = response.StatusDescription, 160 | Request = response.Request 161 | }; 162 | } 163 | 164 | } 165 | 166 | /// 167 | /// Container for data sent back from API 168 | /// 169 | public class RestResponse : RestResponseBase, IRestResponse 170 | { 171 | 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /RestSharp/RestResponseCookie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace RestSharp 3 | { 4 | public class RestResponseCookie 5 | { 6 | /// 7 | /// Comment of the cookie 8 | /// 9 | public string Comment { get; set; } 10 | /// 11 | /// Comment of the cookie 12 | /// 13 | public Uri CommentUri { get; set; } 14 | /// 15 | /// Indicates whether the cookie should be discarded at the end of the session 16 | /// 17 | public bool Discard { get; set; } 18 | /// 19 | /// Domain of the cookie 20 | /// 21 | public string Domain { get; set; } 22 | /// 23 | /// Indicates whether the cookie is expired 24 | /// 25 | public bool Expired { get; set; } 26 | /// 27 | /// Date and time that the cookie expires 28 | /// 29 | public DateTime Expires { get; set; } 30 | /// 31 | /// Indicates that this cookie should only be accessed by the server 32 | /// 33 | public bool HttpOnly { get; set; } 34 | /// 35 | /// Name of the cookie 36 | /// 37 | public string Name { get; set; } 38 | /// 39 | /// Path of the cookie 40 | /// 41 | public string Path { get; set; } 42 | /// 43 | /// Port of the cookie 44 | /// 45 | public string Port { get; set; } 46 | /// 47 | /// Indicates that the cookie should only be sent over secure channels 48 | /// 49 | public bool Secure { get; set; } 50 | /// 51 | /// Date and time the cookie was created 52 | /// 53 | public DateTime TimeStamp { get; set; } 54 | /// 55 | /// Value of the cookie 56 | /// 57 | public string Value { get; set; } 58 | /// 59 | /// Version of the cookie 60 | /// 61 | public int Version { get; set; } 62 | } 63 | } 64 | 65 | -------------------------------------------------------------------------------- /RestSharp/Serializers/DotNetXmlSerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | using System.Xml.Serialization; 4 | 5 | namespace RestSharp.Serializers 6 | { 7 | /// 8 | /// Wrapper for System.Xml.Serialization.XmlSerializer. 9 | /// 10 | public class DotNetXmlSerializer : ISerializer 11 | { 12 | /// 13 | /// Default constructor, does not specify namespace 14 | /// 15 | public DotNetXmlSerializer() 16 | { 17 | ContentType = "application/xml"; 18 | Encoding = Encoding.UTF8; 19 | } 20 | 21 | /// 22 | /// Specify the namespaced to be used when serializing 23 | /// 24 | /// XML namespace 25 | public DotNetXmlSerializer(string @namespace) : this() 26 | { 27 | Namespace = @namespace; 28 | } 29 | 30 | /// 31 | /// Serialize the object as XML 32 | /// 33 | /// Object to serialize 34 | /// XML as string 35 | public string Serialize(object obj) 36 | { 37 | var ns = new XmlSerializerNamespaces(); 38 | ns.Add(string.Empty, Namespace); 39 | var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); 40 | var writer = new EncodingStringWriter(Encoding); 41 | serializer.Serialize(writer, obj, ns); 42 | 43 | return writer.ToString(); 44 | } 45 | 46 | /// 47 | /// Name of the root element to use when serializing 48 | /// 49 | public string RootElement { get; set; } 50 | 51 | /// 52 | /// XML namespace to use when serializing 53 | /// 54 | public string Namespace { get; set; } 55 | 56 | /// 57 | /// Format string to use when serializing dates 58 | /// 59 | public string DateFormat { get; set; } 60 | 61 | /// 62 | /// Content type for serialized content 63 | /// 64 | public string ContentType { get; set; } 65 | 66 | /// 67 | /// Encoding for serialized content 68 | /// 69 | public Encoding Encoding { get; set; } 70 | 71 | /// 72 | /// Need to subclass StringWriter in order to override Encoding 73 | /// 74 | private class EncodingStringWriter : StringWriter 75 | { 76 | private readonly Encoding encoding; 77 | 78 | public EncodingStringWriter(Encoding encoding) 79 | { 80 | this.encoding = encoding; 81 | } 82 | 83 | public override Encoding Encoding 84 | { 85 | get { return encoding; } 86 | } 87 | } 88 | } 89 | } -------------------------------------------------------------------------------- /RestSharp/Serializers/ISerializer.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | namespace RestSharp.Serializers 18 | { 19 | public interface ISerializer 20 | { 21 | string Serialize(object obj); 22 | string RootElement { get; set; } 23 | string Namespace { get; set; } 24 | string DateFormat { get; set; } 25 | string ContentType { get; set; } 26 | } 27 | } -------------------------------------------------------------------------------- /RestSharp/Serializers/JsonSerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace RestSharp.Serializers 4 | { 5 | /// 6 | /// Default JSON serializer for request bodies 7 | /// Doesn't currently use the SerializeAs attribute, defers to Newtonsoft's attributes 8 | /// 9 | public class JsonSerializer : ISerializer 10 | { 11 | /// 12 | /// Default serializer 13 | /// 14 | public JsonSerializer() 15 | { 16 | ContentType = "application/json"; 17 | } 18 | 19 | /// 20 | /// Serialize the object as JSON 21 | /// 22 | /// Object to serialize 23 | /// JSON as String 24 | public string Serialize(object obj) 25 | { 26 | return SimpleJson.SerializeObject(obj); 27 | } 28 | 29 | /// 30 | /// Unused for JSON Serialization 31 | /// 32 | public string DateFormat { get; set; } 33 | /// 34 | /// Unused for JSON Serialization 35 | /// 36 | public string RootElement { get; set; } 37 | /// 38 | /// Unused for JSON Serialization 39 | /// 40 | public string Namespace { get; set; } 41 | /// 42 | /// Content type for serialized content 43 | /// 44 | public string ContentType { get; set; } 45 | } 46 | } -------------------------------------------------------------------------------- /RestSharp/Serializers/SerializeAsAttribute.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using RestSharp.Extensions; 19 | using System.Globalization; 20 | 21 | namespace RestSharp.Serializers 22 | { 23 | /// 24 | /// Allows control how class and property names and values are serialized by XmlSerializer 25 | /// Currently not supported with the JsonSerializer 26 | /// When specified at the property level the class-level specification is overridden 27 | /// 28 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] 29 | public sealed class SerializeAsAttribute : Attribute 30 | { 31 | public SerializeAsAttribute() { 32 | NameStyle = NameStyle.AsIs; 33 | Index = int.MaxValue; 34 | Culture = CultureInfo.InvariantCulture; 35 | } 36 | 37 | /// 38 | /// The name to use for the serialized element 39 | /// 40 | public string Name { get; set; } 41 | 42 | /// 43 | /// Sets the value to be serialized as an Attribute instead of an Element 44 | /// 45 | public bool Attribute { get; set; } 46 | 47 | /// 48 | /// The culture to use when serializing 49 | /// 50 | public CultureInfo Culture { get; set; } 51 | 52 | /// 53 | /// Transforms the casing of the name based on the selected value. 54 | /// 55 | public NameStyle NameStyle { get; set; } 56 | 57 | /// 58 | /// The order to serialize the element. Default is int.MaxValue. 59 | /// 60 | public int Index { get; set; } 61 | 62 | /// 63 | /// Called by the attribute when NameStyle is speficied 64 | /// 65 | /// The string to transform 66 | /// String 67 | public string TransformName(string input) { 68 | var name = Name ?? input; 69 | switch (NameStyle) { 70 | case NameStyle.CamelCase: 71 | return name.ToCamelCase(Culture); 72 | case NameStyle.PascalCase: 73 | return name.ToPascalCase(Culture); 74 | case NameStyle.LowerCase: 75 | return name.ToLower(); 76 | } 77 | 78 | return input; 79 | } 80 | } 81 | 82 | /// 83 | /// Options for transforming casing of element names 84 | /// 85 | public enum NameStyle 86 | { 87 | AsIs, 88 | CamelCase, 89 | LowerCase, 90 | PascalCase 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /RestSharp/Serializers/XmlSerializer.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | using System.Collections; 19 | using System.Linq; 20 | using System.Xml.Linq; 21 | using RestSharp.Extensions; 22 | 23 | namespace RestSharp.Serializers 24 | { 25 | /// 26 | /// Default XML Serializer 27 | /// 28 | public class XmlSerializer : ISerializer 29 | { 30 | /// 31 | /// Default constructor, does not specify namespace 32 | /// 33 | public XmlSerializer() { 34 | ContentType = "text/xml"; 35 | } 36 | 37 | /// 38 | /// Specify the namespaced to be used when serializing 39 | /// 40 | /// XML namespace 41 | public XmlSerializer(string @namespace) { 42 | Namespace = @namespace; 43 | ContentType = "text/xml"; 44 | } 45 | 46 | /// 47 | /// Serialize the object as XML 48 | /// 49 | /// Object to serialize 50 | /// XML as string 51 | public string Serialize(object obj) { 52 | var doc = new XDocument(); 53 | 54 | var t = obj.GetType(); 55 | var name = t.Name; 56 | 57 | var options = t.GetAttribute(); 58 | if (options != null) { 59 | name = options.TransformName(options.Name ?? name); 60 | } 61 | 62 | var root = new XElement(name.AsNamespaced(Namespace)); 63 | 64 | if (obj is IList) 65 | { 66 | var itemTypeName = ""; 67 | foreach (var item in (IList)obj) 68 | { 69 | var type = item.GetType(); 70 | var opts = type.GetAttribute(); 71 | if (opts != null) 72 | { 73 | itemTypeName = opts.TransformName(opts.Name ?? name); 74 | } 75 | if (itemTypeName == "") 76 | { 77 | itemTypeName = type.Name; 78 | } 79 | var instance = new XElement(itemTypeName); 80 | Map(instance, item); 81 | root.Add(instance); 82 | } 83 | } 84 | else 85 | Map(root, obj); 86 | 87 | if (RootElement.HasValue()) { 88 | var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root); 89 | doc.Add(wrapper); 90 | } 91 | else { 92 | doc.Add(root); 93 | } 94 | 95 | return doc.ToString(); 96 | } 97 | 98 | private void Map(XElement root, object obj) { 99 | var objType = obj.GetType(); 100 | 101 | var props = from p in objType.GetProperties() 102 | let indexAttribute = p.GetAttribute() 103 | where p.CanRead && p.CanWrite 104 | orderby indexAttribute == null ? int.MaxValue : indexAttribute.Index 105 | select p; 106 | 107 | var globalOptions = objType.GetAttribute(); 108 | 109 | foreach (var prop in props) { 110 | var name = prop.Name; 111 | var rawValue = prop.GetValue(obj, null); 112 | 113 | if (rawValue == null) { 114 | continue; 115 | } 116 | 117 | var value = GetSerializedValue(rawValue); 118 | var propType = prop.PropertyType; 119 | 120 | var useAttribute = false; 121 | var settings = prop.GetAttribute(); 122 | if (settings != null) { 123 | name = settings.Name.HasValue() ? settings.Name : name; 124 | useAttribute = settings.Attribute; 125 | } 126 | 127 | var options = prop.GetAttribute(); 128 | if (options != null) { 129 | name = options.TransformName(name); 130 | } 131 | else if (globalOptions != null) { 132 | name = globalOptions.TransformName(name); 133 | } 134 | 135 | var nsName = name.AsNamespaced(Namespace); 136 | var element = new XElement(nsName); 137 | 138 | if (propType.IsPrimitive || propType.IsValueType || propType == typeof(string)) { 139 | if (useAttribute) { 140 | root.Add(new XAttribute(name, value)); 141 | continue; 142 | } 143 | 144 | element.Value = value; 145 | } 146 | else if (rawValue is IList) { 147 | var itemTypeName = ""; 148 | foreach (var item in (IList)rawValue) { 149 | if (itemTypeName == "") { 150 | itemTypeName = item.GetType().Name; 151 | } 152 | var instance = new XElement(itemTypeName); 153 | Map(instance, item); 154 | element.Add(instance); 155 | } 156 | } 157 | else { 158 | Map(element, rawValue); 159 | } 160 | 161 | root.Add(element); 162 | } 163 | } 164 | 165 | private string GetSerializedValue(object obj) { 166 | var output = obj; 167 | 168 | if (obj is DateTime && DateFormat.HasValue()) 169 | { 170 | output = ((DateTime) obj).ToString(DateFormat); 171 | } 172 | if (obj is bool) 173 | { 174 | output = obj.ToString().ToLower(); 175 | } 176 | 177 | return output.ToString(); 178 | } 179 | 180 | /// 181 | /// Name of the root element to use when serializing 182 | /// 183 | public string RootElement { get; set; } 184 | /// 185 | /// XML namespace to use when serializing 186 | /// 187 | public string Namespace { get; set; } 188 | /// 189 | /// Format string to use when serializing dates 190 | /// 191 | public string DateFormat { get; set; } 192 | /// 193 | /// Content type for serialized content 194 | /// 195 | public string ContentType { get; set; } 196 | } 197 | } -------------------------------------------------------------------------------- /RestSharp/SharedAssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | using System; 5 | 6 | // General Information about an assembly is controlled through the following 7 | // set of attributes. Change these attribute values to modify the information 8 | // associated with an assembly. 9 | [assembly: AssemblyDescription("Simple REST and HTTP API Client")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("restsharp.org")] 12 | [assembly: AssemblyProduct("RestSharp")] 13 | [assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2012")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | [assembly: CLSCompliant(true)] 17 | // Version information for an assembly consists of the following four values: 18 | // 19 | // Major Version 20 | // Minor Version 21 | // Build Number 22 | // Revision 23 | // 24 | // You can specify all the values or you can default the Build and Revision Numbers 25 | // by using the '*' as shown below: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("104.2.0.0")] 28 | [assembly: AssemblyFileVersion("104.2.0.0")] 29 | -------------------------------------------------------------------------------- /RestSharp/T4Helper/T4Toolbox.tt: -------------------------------------------------------------------------------- 1 | <#@ dte processor="T4Toolbox.DteProcessor" #> 2 | <#@ TransformationContext processor="T4Toolbox.TransformationContextProcessor" #> 3 | <#@ assembly name="System.Xml" #> 4 | <#@ assembly name="EnvDTE" #> 5 | <#@ assembly name="Microsoft.VisualStudio.Ole.Interop" #> 6 | <#@ assembly name="Microsoft.VisualStudio.Shell" #> 7 | <#@ assembly name="Microsoft.VisualStudio.Shell.Interop" #> 8 | <#@ assembly name="VSLangProj" #> 9 | <#@ import namespace="T4Toolbox" #> -------------------------------------------------------------------------------- /RestSharp/Validation/Require.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | 19 | namespace RestSharp.Validation 20 | { 21 | /// 22 | /// Helper methods for validating required values 23 | /// 24 | public class Require 25 | { 26 | /// 27 | /// Require a parameter to not be null 28 | /// 29 | /// Name of the parameter 30 | /// Value of the parameter 31 | public static void Argument(string argumentName, object argumentValue) { 32 | if (argumentValue == null) { 33 | throw new ArgumentException("Argument cannot be null.", argumentName); 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /RestSharp/Validation/Validate.cs: -------------------------------------------------------------------------------- 1 | #region License 2 | // Copyright 2010 John Sheehan 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | #endregion 16 | 17 | using System; 18 | 19 | namespace RestSharp.Validation 20 | { 21 | /// 22 | /// Helper methods for validating values 23 | /// 24 | public class Validate 25 | { 26 | /// 27 | /// Validate an integer value is between the specified values (exclusive of min/max) 28 | /// 29 | /// Value to validate 30 | /// Exclusive minimum value 31 | /// Exclusive maximum value 32 | public static void IsBetween(int value, int min, int max) { 33 | if (value < min || value > max) { 34 | throw new ArgumentException(string.Format("Value ({0}) is not between {1} and {2}.", value, min, max)); 35 | } 36 | } 37 | 38 | /// 39 | /// Validate a string length 40 | /// 41 | /// String to be validated 42 | /// Maximum length of the string 43 | public static void IsValidLength(string value, int maxSize) { 44 | if (value == null) 45 | return; 46 | 47 | if (value.Length > maxSize) { 48 | throw new ArgumentException(string.Format("String is longer than max allowed size ({0}).", maxSize)); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /RestSharp/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /Tools/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cratesmith/RestSharp-for-unity3d/86c9403eccafe4acb3ad0121baea3f1836e1d057/Tools/NuGet.exe -------------------------------------------------------------------------------- /package.cmd: -------------------------------------------------------------------------------- 1 | %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe RestSharp.sln /t:Clean,Rebuild /p:Configuration=Release /fileLogger 2 | 3 | if not exist Download\Net4 mkdir Download\Net4\ 4 | if not exist Download\Silverlight mkdir Download\Silverlight\ 5 | if not exist Download\WindowsPhone mkdir Download\WindowsPhone\ 6 | if not exist Download\package\lib\net35 mkdir Download\package\lib\net35\ 7 | if not exist Download\package\lib\net35-client mkdir Download\package\lib\net35-client\ 8 | if not exist Download\package\lib\net4 mkdir Download\package\lib\net4\ 9 | if not exist Download\package\lib\net4-client mkdir Download\package\lib\net4-client\ 10 | if not exist Download\package\lib\sl4-wp71 mkdir Download\package\lib\sl4-wp71\ 11 | if not exist Download\package\lib\sl4 mkdir Download\package\lib\sl4\ 12 | 13 | copy RestSharp\bin\Release\RestSharp.dll Download\ 14 | copy RestSharp\bin\Release\RestSharp.xml Download\ 15 | 16 | copy RestSharp.Net4\bin\Release\RestSharp.dll Download\Net4\ 17 | copy RestSharp.Net4\bin\Release\RestSharp.xml Download\Net4\ 18 | 19 | copy RestSharp.Silverlight\bin\Release\RestSharp.Silverlight.dll Download\Silverlight\ 20 | copy RestSharp.Silverlight\bin\Release\RestSharp.Silverlight.xml Download\Silverlight\ 21 | 22 | copy RestSharp.WindowsPhone\bin\Release\RestSharp.WindowsPhone.dll Download\WindowsPhone\ 23 | copy RestSharp.WindowsPhone\bin\Release\RestSharp.WindowsPhone.xml Download\WindowsPhone\ 24 | 25 | copy LICENSE.txt Download\ 26 | copy readme.txt Download\ 27 | copy readme.txt Download\package\ 28 | 29 | copy RestSharp\bin\Release\RestSharp.dll Download\Package\lib\net35\ 30 | copy RestSharp\bin\Release\RestSharp.dll Download\Package\lib\net35-client\ 31 | 32 | copy RestSharp.Net4\bin\Release\RestSharp.dll Download\Package\lib\net4\ 33 | copy RestSharp.Net4\bin\Release\RestSharp.dll Download\Package\lib\net4-client\ 34 | 35 | copy RestSharp.Silverlight\bin\Release\RestSharp.Silverlight.dll Download\Package\lib\sl4\ 36 | copy RestSharp.WindowsPhone\bin\Release\RestSharp.WindowsPhone.dll Download\Package\lib\sl4-wp71\ 37 | 38 | copy RestSharp\bin\Release\RestSharp.xml Download\Package\lib\net35\ 39 | copy RestSharp\bin\Release\RestSharp.xml Download\Package\lib\net35-client\ 40 | 41 | copy RestSharp.Net4\bin\Release\RestSharp.xml Download\Package\lib\net4\ 42 | copy RestSharp.Net4\bin\Release\RestSharp.xml Download\Package\lib\net4-client\ 43 | 44 | copy RestSharp.Silverlight\bin\Release\RestSharp.Silverlight.xml Download\Package\lib\sl4\ 45 | copy RestSharp.WindowsPhone\bin\Release\RestSharp.WindowsPhone.xml Download\Package\lib\sl4-wp71\ 46 | 47 | tools\nuget.exe update -self 48 | tools\nuget.exe pack restsharp.nuspec -BasePath Download\Package -Output Download -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | *** IMPORTANT CHANGE IN RESTSHARP VERSION 103 *** 2 | 3 | In 103.0, JSON.NET was removed as a dependency. 4 | 5 | If this is still installed in your project and no other libraries depend on 6 | it you may remove it from your installed packages. 7 | 8 | There is one breaking change: the default Json*Serializer* is no longer 9 | compatible with Json.NET. To use Json.NET for serialization, copy the code 10 | from https://github.com/restsharp/RestSharp/blob/86b31f9adf049d7fb821de8279154f41a17b36f7/RestSharp/Serializers/JsonSerializer.cs 11 | and register it with your client: 12 | 13 | var client = new RestClient(); 14 | client.JsonSerializer = new YourCustomSerializer(); 15 | 16 | The default Json*Deserializer* should be 100% compatible. 17 | 18 | If you run into any compatibility issues with deserialization, 19 | please report it to http://groups.google.com/group/restsharp -------------------------------------------------------------------------------- /releasenotes.markdown: -------------------------------------------------------------------------------- 1 | # RestSharp Release Notes 2 | 3 | ## 104.1 4 | 5 | * Fixed bug where ExecuteAsync sometimes doesn't send data 6 | 7 | ## 104.0 8 | 9 | * Fixed Windows Phone and Silverlight to use culture when calling Convert.ChangeType() (thanks trydis) 10 | * Added support for non-standard HTTP methods (thanks jhoerr) 11 | New API methods include: 12 | * `IRestClient.ExecuteAsyncGet()` 13 | * `IRestClient.ExecuteAsyncPost()` 14 | * `IRestClient.ExecuteAsyncGet()` 15 | * `IRestClient.ExecuteAsyncPost()` 16 | 17 | See [groups discussion](https://groups.google.com/forum/?fromgroups=#!topic/restsharp/FCLGE5By7AU) for more info 18 | 19 | * Resolved an xAuth support issue in the OAuth1Authenticator (thanks artema) 20 | * Change AddDefaultParameter methods to be extension methods (thanks haacked) 21 | Added `RestClientExtensions.AddDefaultParameter()` with 4 overloads. See pull request [#311](https://github.com/restsharp/RestSharp/pull/311) for more info 22 | 23 | * Adding support for deserializing enums from integer representations (thanks dontjee) 24 | 25 | ## 103.4 26 | 27 | * Version bump to fix assembly versioning 28 | 29 | ## 103.3 30 | 31 | * Added in the check for it being generic before calling GetGenericType Definition() (thanks nicwise) 32 | * Add support for deserializing properties with an underscore prefix (thanks psampaio) 33 | * BaseUrl is now virtual (thanks Haacked) 34 | * Fixed List json deserialization, when T was a something like DateTime, Timespan, Guid, etc. (thanks PedroLamas) 35 | * Improve support for parsing iso8601 dates (thanks friism) 36 | 37 | ## 103.2 38 | 39 | ### New Features 40 | 41 | * Allow deserializing a single item into a List field, for JSON that only uses a list when there's more than one item for a given field (thanks petejohanson) 42 | * Extended NtlmAuthenticator so that it can also impersonate a user (thanks kleinron) 43 | * Added support for mapping JSON objects to Dictionary (thanks petejohanson) 44 | * Added ability to set Host and Date when built for .NET 4.0 (thanks lukebakken) 45 | * Allow deserializing lists with null in them. Should resolve pull request (thanks petejohanson) 46 | * Add support for deserializing JSON to subclasses of List (thanks abaybuzskiy) 47 | 48 | ### Bugs fixed 49 | * Fixed invalid OAuth1 signature for GET request (thanks trilobyte) 50 | * Added some missing OAuth files to the .NET4 and Silverlight projects (thanks PedroLamas) 51 | * Removed unused NewtonsoftJsonMonoTouch.dll and Newtonsoft.Json.MonoDroid.dll binaries (thanks attilah) 52 | * Fixed various issues with MonoTouch/Droid ports (thanks attilah) 53 | * Add ability to set Host and Date when built for .NET 4.0 (thanks lukebakken) 54 | * Fixed XmlDeserializer issue not handling lowercase + dash root elements in some cases 55 | * Fixed an issue where RestResponse.Request was not populated (thanks mattleibow) 56 | * Don't crash on captive networks that intercept SSL (thanks aroben) 57 | 58 | ## 103.1 59 | 60 | * #267 Added CLS Compliance 61 | * #263 Fixed InvalidCastException 62 | * #218 Handles connection failures better 63 | * #231 OAuth now complies with rfc3986 url hex encoding 64 | 65 | ## 103.0 - Remove dependency on Json.NET 66 | 67 | * Remove WP7.0 support (7.1 Mango remains). 68 | 69 | ## 102.7 70 | 71 | * Updating Json.NET to 4.0.8, misc fixes 72 | 73 | ## 102.6 74 | 75 | * Updating Json.NET reference to 4.0.5 -------------------------------------------------------------------------------- /restsharp.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RestSharp 5 | 104.1 6 | John Sheehan, RestSharp Community 7 | John Sheehan 8 | Simple REST and HTTP API Client 9 | en-US 10 | http://restsharp.org 11 | https://github.com/restsharp/RestSharp/blob/master/LICENSE.txt 12 | http://dl.dropbox.com/u/1827/restsharp100.png 13 | REST HTTP API JSON XML 14 | 15 | 18 | 19 | 20 | --------------------------------------------------------------------------------