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":"\r\n\r\n\r\n\r\nVisit managedassembly.com - A community for .NET developers.
\r\n\r\nI 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":"\r\n\r\n\r\n\r\nVisit managedassembly.com - A community for .NET developers.
\r\n\r\nI 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 |
--------------------------------------------------------------------------------