diff --git a/.nuget/RestSharp.Build.dll b/.nuget/RestSharp.Build.dll index 7aa20747b..0b948cdbc 100644 Binary files a/.nuget/RestSharp.Build.dll and b/.nuget/RestSharp.Build.dll differ diff --git a/.nuget/Signed/RestSharp.Build.dll b/.nuget/Signed/RestSharp.Build.dll index 71d45f912..1179208a5 100644 Binary files a/.nuget/Signed/RestSharp.Build.dll and b/.nuget/Signed/RestSharp.Build.dll differ diff --git a/RestSharp.2015.sln b/RestSharp.2015.sln new file mode 100644 index 000000000..a36ec2ce6 --- /dev/null +++ b/RestSharp.2015.sln @@ -0,0 +1,277 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{E709A928-A45C-4622-A35C-CCD8EE44CA80}" + ProjectSection(SolutionItems) = preProject + package.cmd = package.cmd + packageAll.cmd = packageAll.cmd + packageSigned.cmd = packageSigned.cmd + readme.txt = readme.txt + restsharp.nuspec = restsharp.nuspec + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1B3F12F6-D32B-48C4-98D7-AB448EB78811}" + ProjectSection(SolutionItems) = preProject + .nuget\NuGet.exe = .nuget\NuGet.exe + .nuget\NuGet.targets = .nuget\NuGet.targets + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Meta", "Meta", "{C5B02FAA-6A0A-4BF9-BBD4-82FD2DCBF669}" + ProjectSection(SolutionItems) = preProject + CONTRIBUTING.markdown = CONTRIBUTING.markdown + README.markdown = README.markdown + readme.txt = readme.txt + releasenotes.markdown = releasenotes.markdown + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp", "RestSharp\RestSharp.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests", "RestSharp.Tests\RestSharp.Tests.csproj", "{1464E4AC-18BB-4F23-8A0B-68196F9E1871}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.IntegrationTests", "RestSharp.IntegrationTests\RestSharp.IntegrationTests.csproj", "{47D3EBB9-0300-4AF8-BAC5-740D51454A63}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Silverlight", "RestSharp.Silverlight\RestSharp.Silverlight.csproj", "{11F84600-0978-48B9-A28F-63B3781E54B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.WindowsPhone", "RestSharp.WindowsPhone\RestSharp.WindowsPhone.csproj", "{F4D48DF6-316E-4963-B5C1-59CA39B431B7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net4", "RestSharp.Net4\RestSharp.Net4.csproj", "{5FF943A5-260F-4042-B4CE-C4977BAD4EBB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Build", "RestSharp.Build\RestSharp.Build.csproj", "{CCC30138-3D68-44D8-AF1A-D22F769EE8DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net45", "RestSharp.Net45\RestSharp.Net45.csproj", "{D5D62FE9-1679-4697-BDC6-9574D907A717}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net451", "RestSharp.Net451\RestSharp.Net451.csproj", "{53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net452", "RestSharp.Net452\RestSharp.Net452.csproj", "{353349A9-4E6C-4706-A1C4-8363EAE0DBF3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net46", "RestSharp.Net46\RestSharp.Net46.csproj", "{47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x86 = Debug|x86 + DebugAppveyor|Any CPU = DebugAppveyor|Any CPU + DebugAppveyor|ARM = DebugAppveyor|ARM + DebugAppveyor|Mixed Platforms = DebugAppveyor|Mixed Platforms + DebugAppveyor|x86 = DebugAppveyor|x86 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM + Release|Mixed Platforms = Release|Mixed Platforms + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|ARM.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|ARM.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|x86.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.Build.0 = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|ARM.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|x86.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|ARM.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|x86.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Mixed Platforms.ActiveCfg = DebugAppveyor|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Mixed Platforms.Build.0 = DebugAppveyor|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Any CPU.Build.0 = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|ARM.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|x86.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|ARM.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|x86.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Any CPU.Build.0 = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|ARM.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|x86.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|ARM.ActiveCfg = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|ARM.Build.0 = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|x86.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|ARM.ActiveCfg = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|ARM.Build.0 = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Any CPU.Build.0 = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|ARM.ActiveCfg = Release|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|ARM.Build.0 = Release|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|x86.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|ARM.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|x86.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Any CPU.Build.0 = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|ARM.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|x86.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|ARM.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|x86.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|ARM.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|x86.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|ARM.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|x86.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Any CPU.Build.0 = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|ARM.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|x86.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|ARM.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|x86.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Any CPU.Build.0 = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|ARM.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|x86.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|ARM.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|x86.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Any CPU.Build.0 = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|ARM.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|x86.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|ARM.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|ARM.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|x86.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|x86.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|ARM.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|x86.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Any CPU.Build.0 = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|ARM.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|ARM.Build.0 = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|x86.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/RestSharp.All.sln b/RestSharp.All.sln new file mode 100644 index 000000000..4b7d83b8f --- /dev/null +++ b/RestSharp.All.sln @@ -0,0 +1,451 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.40629.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{E709A928-A45C-4622-A35C-CCD8EE44CA80}" + ProjectSection(SolutionItems) = preProject + package.cmd = package.cmd + packageAll.cmd = packageAll.cmd + packageSigned.cmd = packageSigned.cmd + readme.txt = readme.txt + restsharp.nuspec = restsharp.nuspec + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1B3F12F6-D32B-48C4-98D7-AB448EB78811}" + ProjectSection(SolutionItems) = preProject + .nuget\NuGet.exe = .nuget\NuGet.exe + .nuget\NuGet.targets = .nuget\NuGet.targets + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Meta", "Meta", "{C5B02FAA-6A0A-4BF9-BBD4-82FD2DCBF669}" + ProjectSection(SolutionItems) = preProject + CONTRIBUTING.markdown = CONTRIBUTING.markdown + README.markdown = README.markdown + readme.txt = readme.txt + releasenotes.markdown = releasenotes.markdown + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net35", "RestSharp\RestSharp.Net35.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests", "RestSharp.Tests\RestSharp.Tests.csproj", "{1464E4AC-18BB-4F23-8A0B-68196F9E1871}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.IntegrationTests", "RestSharp.IntegrationTests\RestSharp.IntegrationTests.csproj", "{47D3EBB9-0300-4AF8-BAC5-740D51454A63}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Silverlight", "RestSharp.Silverlight\RestSharp.Silverlight.csproj", "{11F84600-0978-48B9-A28F-63B3781E54B3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.WindowsPhone", "RestSharp.WindowsPhone\RestSharp.WindowsPhone.csproj", "{F4D48DF6-316E-4963-B5C1-59CA39B431B7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net4", "RestSharp.Net4\RestSharp.Net4.csproj", "{5FF943A5-260F-4042-B4CE-C4977BAD4EBB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Build", "RestSharp.Build\RestSharp.Build.csproj", "{CCC30138-3D68-44D8-AF1A-D22F769EE8DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net45", "RestSharp.Net45\RestSharp.Net45.csproj", "{D5D62FE9-1679-4697-BDC6-9574D907A717}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net451", "RestSharp.Net451\RestSharp.Net451.csproj", "{53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net452", "RestSharp.Net452\RestSharp.Net452.csproj", "{353349A9-4E6C-4706-A1C4-8363EAE0DBF3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net46", "RestSharp.Net46\RestSharp.Net46.csproj", "{47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net35.Signed", "RestSharp\RestSharp.Net35.Signed.csproj", "{3190E0DC-674C-4C41-A7A3-BD2F406963B0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Build.Signed", "RestSharp.Build\RestSharp.Build.Signed.csproj", "{60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.IntegrationTests.Signed", "RestSharp.IntegrationTests\RestSharp.IntegrationTests.Signed.csproj", "{3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net4.Signed", "RestSharp.Net4\RestSharp.Net4.Signed.csproj", "{ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net45.Signed", "RestSharp.Net45\RestSharp.Net45.Signed.csproj", "{EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net46.Signed", "RestSharp.Net46\RestSharp.Net46.Signed.csproj", "{BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net451.Signed", "RestSharp.Net451\RestSharp.Net451.Signed.csproj", "{142BC56F-48B2-4BAE-A33D-583D0B77232C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net452.Signed", "RestSharp.Net452\RestSharp.Net452.Signed.csproj", "{F4C74773-8D8E-4A7D-977B-DE985B4D49D9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests.Signed", "RestSharp.Tests\RestSharp.Tests.Signed.csproj", "{25D4AAB0-B538-4F13-AB0E-96247307858B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x86 = Debug|x86 + DebugAppveyor|Any CPU = DebugAppveyor|Any CPU + DebugAppveyor|ARM = DebugAppveyor|ARM + DebugAppveyor|Mixed Platforms = DebugAppveyor|Mixed Platforms + DebugAppveyor|x86 = DebugAppveyor|x86 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM + Release|Mixed Platforms = Release|Mixed Platforms + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|ARM.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|ARM.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|x86.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Any CPU.Build.0 = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|ARM.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Release|x86.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|ARM.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Debug|x86.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Mixed Platforms.ActiveCfg = DebugAppveyor|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|Mixed Platforms.Build.0 = DebugAppveyor|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Any CPU.Build.0 = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|ARM.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {47D3EBB9-0300-4AF8-BAC5-740D51454A63}.Release|x86.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|ARM.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Debug|x86.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Any CPU.Build.0 = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|ARM.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {11F84600-0978-48B9-A28F-63B3781E54B3}.Release|x86.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|ARM.ActiveCfg = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|ARM.Build.0 = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Debug|x86.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|ARM.ActiveCfg = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|ARM.Build.0 = Debug|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Any CPU.Build.0 = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|ARM.ActiveCfg = Release|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|ARM.Build.0 = Release|ARM + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {F4D48DF6-316E-4963-B5C1-59CA39B431B7}.Release|x86.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|ARM.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Debug|x86.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Any CPU.Build.0 = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|ARM.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {5FF943A5-260F-4042-B4CE-C4977BAD4EBB}.Release|x86.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|ARM.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Debug|x86.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|ARM.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}.Release|x86.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|ARM.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Debug|x86.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Any CPU.Build.0 = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|ARM.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {D5D62FE9-1679-4697-BDC6-9574D907A717}.Release|x86.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|ARM.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Debug|x86.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Any CPU.Build.0 = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|ARM.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {53F45A1D-088B-4A2C-A8E2-5901F0DB5EA8}.Release|x86.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|ARM.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Debug|x86.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Any CPU.Build.0 = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|ARM.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|x86.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|ARM.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Debug|x86.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Any CPU.Build.0 = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|ARM.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2}.Release|x86.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|ARM.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|x86.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Any CPU.Build.0 = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|ARM.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|x86.ActiveCfg = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|Any CPU.Build.0 = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|ARM.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Debug|x86.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|Any CPU.ActiveCfg = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|Any CPU.Build.0 = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|ARM.ActiveCfg = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}.Release|x86.ActiveCfg = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|ARM.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Debug|x86.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|Any CPU.Build.0 = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|ARM.ActiveCfg = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6}.Release|x86.ActiveCfg = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|ARM.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Debug|x86.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|Any CPU.Build.0 = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|ARM.ActiveCfg = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92}.Release|x86.ActiveCfg = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|ARM.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Debug|x86.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|Any CPU.Build.0 = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|ARM.ActiveCfg = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {EC77CB3A-A55C-4A00-8471-C9AADAE2EED4}.Release|x86.ActiveCfg = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|ARM.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Debug|x86.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Any CPU.Build.0 = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|ARM.ActiveCfg = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|x86.ActiveCfg = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|ARM.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Debug|x86.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|Any CPU.Build.0 = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|ARM.ActiveCfg = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {142BC56F-48B2-4BAE-A33D-583D0B77232C}.Release|x86.ActiveCfg = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|ARM.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|Any CPU.Build.0 = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|ARM.ActiveCfg = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9}.Release|x86.ActiveCfg = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|ARM.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Debug|x86.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|Any CPU.Build.0 = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|ARM.ActiveCfg = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {25D4AAB0-B538-4F13-AB0E-96247307858B}.Release|x86.ActiveCfg = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/RestSharp.Build/NuSpecUpdateTask.cs b/RestSharp.Build/NuSpecUpdateTask.cs index 49fe0e0aa..97fe917a6 100644 --- a/RestSharp.Build/NuSpecUpdateTask.cs +++ b/RestSharp.Build/NuSpecUpdateTask.cs @@ -9,7 +9,7 @@ namespace RestSharp.Build { public class NuSpecUpdateTask : Task { - private Assembly _assembly; + private Assembly assembly; public string Id { get; private set; } @@ -27,7 +27,7 @@ public NuSpecUpdateTask() : this(null) { } public NuSpecUpdateTask(Assembly assembly) { - this._assembly = assembly; + this.assembly = assembly; } public override bool Execute() @@ -36,18 +36,18 @@ public override bool Execute() return false; var path = Path.GetFullPath(this.SourceAssemblyFile); - this._assembly = this._assembly ?? Assembly.LoadFile(path); + this.assembly = this.assembly ?? Assembly.LoadFile(path); - var name = this._assembly.GetName(); + var name = this.assembly.GetName(); #if SIGNED this.Id = name.Name + "Signed"; #else this.Id = name.Name; #endif - this.Authors = this.GetAuthors(this._assembly); - this.Description = this.GetDescription(this._assembly); - this.Version = this.GetVersion(this._assembly); + this.Authors = GetAuthors(this.assembly); + this.Description = GetDescription(this.assembly); + this.Version = GetVersion(this.assembly); this.GenerateComputedSpecFile(); @@ -59,16 +59,16 @@ private void GenerateComputedSpecFile() var doc = XDocument.Load(this.SpecFile); var metaNode = doc.Descendants("metadata").First(); - this.ReplaceToken(metaNode, "id", this.Id); - this.ReplaceToken(metaNode, "authors", this.Authors); - this.ReplaceToken(metaNode, "owners", this.Authors); - this.ReplaceToken(metaNode, "description", this.Description); - this.ReplaceToken(metaNode, "version", this.Version); + ReplaceToken(metaNode, "id", this.Id); + ReplaceToken(metaNode, "authors", this.Authors); + ReplaceToken(metaNode, "owners", this.Authors); + ReplaceToken(metaNode, "description", this.Description); + ReplaceToken(metaNode, "version", this.Version); doc.Save(this.SpecFile.Replace(".nuspec", "-computed.nuspec")); } - private void ReplaceToken(XElement metaNode, XName name, string value) + private static void ReplaceToken(XContainer metaNode, XName name, string value) { var node = metaNode.Element(name); var token = string.Format("${0}$", name.ToString().TrimEnd('s')); @@ -78,26 +78,26 @@ private void ReplaceToken(XElement metaNode, XName name, string value) token = "$author$"; } - if (node.Value.Equals(token, StringComparison.OrdinalIgnoreCase)) + if (node != null && node.Value.Equals(token, StringComparison.OrdinalIgnoreCase)) { node.SetValue(value); } } - private string GetDescription(Assembly asm) + private static string GetDescription(ICustomAttributeProvider asm) { - return this.GetAttribute(asm).Description; + return GetAttribute(asm).Description; } - private string GetAuthors(Assembly asm) + private static string GetAuthors(ICustomAttributeProvider asm) { - return this.GetAttribute(asm).Company; + return GetAttribute(asm).Company; } - private string GetVersion(Assembly asm) + private static string GetVersion(Assembly asm) { var version = asm.GetName().Version.ToString(); - var attr = this.GetAttribute(asm); + var attr = GetAttribute(asm); if (attr != null) { @@ -107,7 +107,7 @@ private string GetVersion(Assembly asm) return version; } - private TAttr GetAttribute(Assembly asm) where TAttr : Attribute + private static TAttr GetAttribute(ICustomAttributeProvider asm) where TAttr : Attribute { var attrs = asm.GetCustomAttributes(typeof(TAttr), false); diff --git a/RestSharp.Build/RestSharp.Build.Signed.csproj b/RestSharp.Build/RestSharp.Build.Signed.csproj index 007591010..04daffbb8 100644 --- a/RestSharp.Build/RestSharp.Build.Signed.csproj +++ b/RestSharp.Build/RestSharp.Build.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 8.0.30703 2.0 - {CCC30138-3D68-44D8-AF1A-D22F769EE8DC} + {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475} Library Properties RestSharp.Build diff --git a/RestSharp.Compact.sln b/RestSharp.Compact.sln deleted file mode 100644 index 39ae77eb7..000000000 --- a/RestSharp.Compact.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Compact", "RestSharp\RestSharp.Compact.csproj", "{A29E330B-F854-4287-BEB2-C4CBE9D9C637}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A29E330B-F854-4287-BEB2-C4CBE9D9C637}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A29E330B-F854-4287-BEB2-C4CBE9D9C637}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A29E330B-F854-4287-BEB2-C4CBE9D9C637}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A29E330B-F854-4287-BEB2-C4CBE9D9C637}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/RestSharp.IntegrationTests/App.config b/RestSharp.IntegrationTests/App.config index 544bbb783..a33cef108 100644 --- a/RestSharp.IntegrationTests/App.config +++ b/RestSharp.IntegrationTests/App.config @@ -4,19 +4,19 @@ - + - + - + - + - + - + \ No newline at end of file diff --git a/RestSharp.IntegrationTests/AsyncRequestBodyTests.cs b/RestSharp.IntegrationTests/AsyncRequestBodyTests.cs index eb2c564ed..da3364cff 100644 --- a/RestSharp.IntegrationTests/AsyncRequestBodyTests.cs +++ b/RestSharp.IntegrationTests/AsyncRequestBodyTests.cs @@ -18,15 +18,15 @@ public void Can_Not_Be_Added_To_GET_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -42,10 +42,9 @@ public void Can_Have_No_Body_Added_To_POST_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); - - var resetEvent = new ManualResetEvent(false); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -61,15 +60,15 @@ public void Can_Be_Added_To_POST_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -85,15 +84,15 @@ public void Can_Be_Added_To_PUT_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -109,15 +108,15 @@ public void Can_Be_Added_To_DELETE_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -133,15 +132,15 @@ public void Can_Not_Be_Added_To_HEAD_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -157,15 +156,15 @@ public void Can_Be_Added_To_OPTIONS_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -181,15 +180,15 @@ public void Can_Be_Added_To_PATCH_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); @@ -224,7 +223,7 @@ private class RequestBodyCapturer public static void Capture(HttpListenerContext context) { - var request = context.Request; + HttpListenerRequest request = context.Request; CapturedContentType = request.ContentType; CapturedHasEntityBody = request.HasEntityBody; @@ -233,7 +232,7 @@ public static void Capture(HttpListenerContext context) private static string StreamToString(Stream stream) { - var streamReader = new StreamReader(stream); + StreamReader streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); } } diff --git a/RestSharp.IntegrationTests/AsyncTests.cs b/RestSharp.IntegrationTests/AsyncTests.cs index 6fe49cd32..26b66208e 100644 --- a/RestSharp.IntegrationTests/AsyncTests.cs +++ b/RestSharp.IntegrationTests/AsyncTests.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Net; using System.Threading; +using System.Threading.Tasks; using NUnit.Framework; using RestSharp.IntegrationTests.Helpers; @@ -16,12 +17,12 @@ public void Can_Perform_GET_Async() Uri baseUrl = new Uri("http://localhost:8888/"); const string val = "Basic async test"; - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue(val))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); client.ExecuteAsync(request, (response, asyncHandle) => { @@ -40,12 +41,12 @@ public void Can_Perform_GET_Async_Without_Async_Handle() Uri baseUrl = new Uri("http://localhost:8888/"); const string val = "Basic async test"; - var resetEvent = new ManualResetEvent(false); + ManualResetEvent resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue(val))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); client.ExecuteAsync(request, response => { @@ -66,9 +67,9 @@ public void Can_Perform_GET_TaskAsync() using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); - var task = client.ExecuteTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); + Task task = client.ExecuteTaskAsync(request); task.Wait(); @@ -81,22 +82,22 @@ public void Can_Perform_GET_TaskAsync() public void Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler() { const string baseUrl = "http://localhost:8888/"; - const string ExceptionMessage = "Thrown from OnBeforeDeserialization"; + const string exceptionMessage = "Thrown from OnBeforeDeserialization"; using (SimpleServer.Create(baseUrl, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("success"); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("success"); - request.OnBeforeDeserialization += r => { throw new Exception(ExceptionMessage); }; + request.OnBeforeDeserialization += r => { throw new Exception(exceptionMessage); }; - var task = client.ExecuteTaskAsync(request); + Task> task = client.ExecuteTaskAsync(request); task.Wait(); - var response = task.Result; + IRestResponse response = task.Result; - Assert.AreEqual(ExceptionMessage, response.ErrorMessage); + Assert.AreEqual(exceptionMessage, response.ErrorMessage); Assert.AreEqual(ResponseStatus.Error, response.ResponseStatus); } } @@ -108,9 +109,9 @@ public void Can_Perform_ExecuteGetTaskAsync_With_Response_Type() using (SimpleServer.Create(baseUrl, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("success"); - var task = client.ExecuteTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("success"); + Task> task = client.ExecuteTaskAsync(request); task.Wait(); @@ -125,9 +126,9 @@ public void Can_Perform_GetTaskAsync_With_Response_Type() using (SimpleServer.Create(baseUrl, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("success"); - var task = client.GetTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("success"); + Task task = client.GetTaskAsync(request); task.Wait(); @@ -143,10 +144,10 @@ public void Can_Cancel_GET_TaskAsync() using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) { - var client = new RestClient(baseUrl); - var request = new RestRequest("timeout"); - var cancellationTokenSource = new CancellationTokenSource(); - var task = client.ExecuteTaskAsync(request, cancellationTokenSource.Token); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("timeout"); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + Task task = client.ExecuteTaskAsync(request, cancellationTokenSource.Token); cancellationTokenSource.Cancel(); @@ -162,10 +163,10 @@ public void Can_Cancel_GET_TaskAsync_With_Response_Type() using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) { - var client = new RestClient(baseUrl); - var request = new RestRequest("timeout"); - var cancellationTokenSource = new CancellationTokenSource(); - var task = client.ExecuteTaskAsync(request, cancellationTokenSource.Token); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("timeout"); + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + Task> task = client.ExecuteTaskAsync(request, cancellationTokenSource.Token); cancellationTokenSource.Cancel(); @@ -180,9 +181,9 @@ public void Handles_GET_Request_Errors_TaskAsync() using (SimpleServer.Create(baseUrl, UrlToStatusCodeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404"); - var task = client.ExecuteTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404"); + Task task = client.ExecuteTaskAsync(request); task.Wait(); @@ -197,9 +198,9 @@ public void Handles_GET_Request_Errors_TaskAsync_With_Response_Type() using (SimpleServer.Create(baseUrl, UrlToStatusCodeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404"); - var task = client.ExecuteTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404"); + Task> task = client.ExecuteTaskAsync(request); task.Wait(); @@ -214,17 +215,17 @@ public void Can_Timeout_GET_TaskAsync() using (SimpleServer.Create(baseUrl, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("timeout", Method.GET).AddBody("Body_Content"); + RestClient client = new RestClient(baseUrl); + IRestRequest request = new RestRequest("timeout", Method.GET).AddBody("Body_Content"); - //Half the value of ResponseHandler.Timeout + // Half the value of ResponseHandler.Timeout request.Timeout = 500; - var task = client.ExecuteTaskAsync(request); + Task task = client.ExecuteTaskAsync(request); task.Wait(); - var response = task.Result; + IRestResponse response = task.Result; Assert.AreEqual(ResponseStatus.TimedOut, response.ResponseStatus); } @@ -237,35 +238,35 @@ public void Can_Timeout_PUT_TaskAsync() using (SimpleServer.Create(baseUrl, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("timeout", Method.PUT).AddBody("Body_Content"); + RestClient client = new RestClient(baseUrl); + IRestRequest request = new RestRequest("timeout", Method.PUT).AddBody("Body_Content"); - //Half the value of ResponseHandler.Timeout + // Half the value of ResponseHandler.Timeout request.Timeout = 500; - var task = client.ExecuteTaskAsync(request); + Task task = client.ExecuteTaskAsync(request); task.Wait(); - var response = task.Result; + IRestResponse response = task.Result; Assert.AreEqual(ResponseStatus.TimedOut, response.ResponseStatus); } } - static void UrlToStatusCodeHandler(HttpListenerContext obj) + private static void UrlToStatusCodeHandler(HttpListenerContext obj) { obj.Response.StatusCode = int.Parse(obj.Request.Url.Segments.Last()); } public class ResponseHandler { - void error(HttpListenerContext context) + private void error(HttpListenerContext context) { context.Response.StatusCode = 400; context.Response.Headers.Add("Content-Type", "application/xml"); context.Response.OutputStream.WriteStringUtf8( -@" + @" Not found! @@ -273,10 +274,10 @@ void error(HttpListenerContext context) "); } - void success(HttpListenerContext context) + private void success(HttpListenerContext context) { context.Response.OutputStream.WriteStringUtf8( -@" + @" Works! @@ -284,7 +285,7 @@ void success(HttpListenerContext context) "); } - void timeout(HttpListenerContext context) + private void timeout(HttpListenerContext context) { Thread.Sleep(1000); } diff --git a/RestSharp.IntegrationTests/AuthenticationTests.cs b/RestSharp.IntegrationTests/AuthenticationTests.cs index a8d03614f..6bb7cd440 100644 --- a/RestSharp.IntegrationTests/AuthenticationTests.cs +++ b/RestSharp.IntegrationTests/AuthenticationTests.cs @@ -1,10 +1,11 @@ using System; +using System.Collections.Specialized; using System.Diagnostics; using System.Net; using System.Text; using NUnit.Framework; using RestSharp.Authenticators; -using RestSharp.Contrib; +using RestSharp.Extensions.MonoHttp; using RestSharp.IntegrationTests.Helpers; namespace RestSharp.IntegrationTests @@ -17,14 +18,14 @@ public void Can_Authenticate_With_Basic_Http_Auth() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, UsernamePasswordEchoHandler)) + using (SimpleServer.Create(baseUrl.AbsoluteUri, UsernamePasswordEchoHandler)) { - var client = new RestClient(baseUrl) - { - Authenticator = new HttpBasicAuthenticator("testuser", "testpassword") - }; - var request = new RestRequest("test"); - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl) + { + Authenticator = new HttpBasicAuthenticator("testuser", "testpassword") + }; + RestRequest request = new RestRequest("test"); + IRestResponse response = client.Execute(request); Assert.AreEqual("testuser|testpassword", response.Content); } @@ -32,8 +33,9 @@ public void Can_Authenticate_With_Basic_Http_Auth() private static void UsernamePasswordEchoHandler(HttpListenerContext context) { - var header = context.Request.Headers["Authorization"]; - var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':'); + string header = context.Request.Headers["Authorization"]; + string[] parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))) + .Split(':'); context.Response.OutputStream.WriteStringUtf8(string.Join("|", parts)); } @@ -41,27 +43,28 @@ private static void UsernamePasswordEchoHandler(HttpListenerContext context) //[Test] public void Can_Authenticate_With_OAuth() { - var baseUrl = new Uri("https://api.twitter.com"); - var client = new RestClient(baseUrl) - { - Authenticator = OAuth1Authenticator.ForRequestToken("CONSUMER_KEY", "CONSUMER_SECRET") - }; - var request = new RestRequest("oauth/request_token"); - var response = client.Execute(request); + Uri baseUrl = new Uri("https://api.twitter.com"); + RestClient client = new RestClient(baseUrl) + { + Authenticator = OAuth1Authenticator.ForRequestToken("CONSUMER_KEY", "CONSUMER_SECRET") + }; + RestRequest request = new RestRequest("oauth/request_token"); + IRestResponse response = client.Execute(request); Assert.NotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var qs = HttpUtility.ParseQueryString(response.Content); - var oauthToken = qs["oauth_token"]; - var oauthTokenSecret = qs["oauth_token_secret"]; + NameValueCollection qs = HttpUtility.ParseQueryString(response.Content); + string oauthToken = qs["oauth_token"]; + string oauthTokenSecret = qs["oauth_token_secret"]; Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); request = new RestRequest("oauth/authorize?oauth_token=" + oauthToken); - var url = client.BuildUri(request).ToString(); + string url = client.BuildUri(request) + .ToString(); Process.Start(url); diff --git a/RestSharp.IntegrationTests/CompressionTests.cs b/RestSharp.IntegrationTests/CompressionTests.cs index e719d594f..a1190e7ce 100644 --- a/RestSharp.IntegrationTests/CompressionTests.cs +++ b/RestSharp.IntegrationTests/CompressionTests.cs @@ -14,11 +14,11 @@ public void Can_Handle_Gzip_Compressed_Content() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, GzipEchoValue("This is some gzipped content"))) + using (SimpleServer.Create(baseUrl.AbsoluteUri, GzipEchoValue("This is some gzipped content"))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); + IRestResponse response = client.Execute(request); Assert.AreEqual("This is some gzipped content", response.Content); } @@ -29,11 +29,11 @@ public void Can_Handle_Deflate_Compressed_Content() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, DeflateEchoValue("This is some deflated content"))) + using (SimpleServer.Create(baseUrl.AbsoluteUri, DeflateEchoValue("This is some deflated content"))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); + IRestResponse response = client.Execute(request); Assert.AreEqual("This is some deflated content", response.Content); } @@ -44,40 +44,40 @@ public void Can_Handle_Uncompressed_Content() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue("This is some sample content"))) + using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue("This is some sample content"))) { - var client = new RestClient(baseUrl); - var request = new RestRequest(""); - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(""); + IRestResponse response = client.Execute(request); Assert.AreEqual("This is some sample content", response.Content); } } - static Action GzipEchoValue(string value) + private static Action GzipEchoValue(string value) { return context => - { - context.Response.Headers.Add("Content-encoding", "gzip"); + { + context.Response.Headers.Add("Content-encoding", "gzip"); - using (var gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true)) - { - gzip.WriteStringUtf8(value); - } - }; + using (GZipStream gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true)) + { + gzip.WriteStringUtf8(value); + } + }; } - static Action DeflateEchoValue(string value) + private static Action DeflateEchoValue(string value) { return context => - { - context.Response.Headers.Add("Content-encoding", "deflate"); + { + context.Response.Headers.Add("Content-encoding", "deflate"); - using (var gzip = new DeflateStream(context.Response.OutputStream, CompressionMode.Compress, true)) - { - gzip.WriteStringUtf8(value); - } - }; + using (DeflateStream gzip = new DeflateStream(context.Response.OutputStream, CompressionMode.Compress, true)) + { + gzip.WriteStringUtf8(value); + } + }; } } } diff --git a/RestSharp.IntegrationTests/FileTests.cs b/RestSharp.IntegrationTests/FileTests.cs index b82eb94cd..26eecd835 100644 --- a/RestSharp.IntegrationTests/FileTests.cs +++ b/RestSharp.IntegrationTests/FileTests.cs @@ -13,12 +13,12 @@ public void Handles_Binary_File_Download() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.FileHandler)) + using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.FileHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("Assets/Koala.jpg"); - var response = client.DownloadData(request); - var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("Assets/Koala.jpg"); + byte[] response = client.DownloadData(request); + byte[] expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); Assert.AreEqual(expected, response); } @@ -33,20 +33,20 @@ public void Writes_Response_To_Stream() { string tempFile = Path.GetTempFileName(); - using (var writer = File.OpenWrite(tempFile)) + using (FileStream writer = File.OpenWrite(tempFile)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("Assets/Koala.jpg") - { - ResponseWriter = (responseStream) => responseStream.CopyTo(writer) - }; - var response = client.DownloadData(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("Assets/Koala.jpg") + { + ResponseWriter = (responseStream) => responseStream.CopyTo(writer) + }; + byte[] response = client.DownloadData(request); Assert.Null(response); } - var fromTemp = File.ReadAllBytes(tempFile); - var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); + byte[] fromTemp = File.ReadAllBytes(tempFile); + byte[] expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); Assert.AreEqual(expected, fromTemp); } diff --git a/RestSharp.IntegrationTests/Helpers/Extensions.cs b/RestSharp.IntegrationTests/Helpers/Extensions.cs index 2d172fced..9cc908bce 100644 --- a/RestSharp.IntegrationTests/Helpers/Extensions.cs +++ b/RestSharp.IntegrationTests/Helpers/Extensions.cs @@ -7,7 +7,7 @@ public static class Extensions { public static void WriteStringUtf8(this Stream target, string value) { - var encoded = Encoding.UTF8.GetBytes(value); + byte[] encoded = Encoding.UTF8.GetBytes(value); target.Write(encoded, 0, encoded.Length); } diff --git a/RestSharp.IntegrationTests/Helpers/Handlers.cs b/RestSharp.IntegrationTests/Helpers/Handlers.cs index a47577421..8be936e63 100644 --- a/RestSharp.IntegrationTests/Helpers/Handlers.cs +++ b/RestSharp.IntegrationTests/Helpers/Handlers.cs @@ -30,10 +30,13 @@ public static Action EchoValue(string value) /// public static void FileHandler(HttpListenerContext context) { - var pathToFile = Path.Combine(context.Request.Url.Segments.Select(s => s.Replace("/", "")).ToArray()); + string pathToFile = Path.Combine(context.Request.Url.Segments.Select(s => s.Replace("/", "")) + .ToArray()); - using (var reader = new StreamReader(pathToFile)) + using (StreamReader reader = new StreamReader(pathToFile)) + { reader.BaseStream.CopyTo(context.Response.OutputStream); + } } /// @@ -57,20 +60,20 @@ public static void FileHandler(HttpListenerContext context) public static Action Generic() where T : new() { return ctx => - { - var methodName = ctx.Request.Url.Segments.Last(); - var method = typeof(T).GetMethod(methodName, - BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + { + string methodName = ctx.Request.Url.Segments.Last(); + MethodInfo method = typeof(T).GetMethod(methodName, + BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); - if (method.IsStatic) - { - method.Invoke(null, new object[] { ctx }); - } - else - { - method.Invoke(new T(), new object[] { ctx }); - } - }; + if (method.IsStatic) + { + method.Invoke(null, new object[] { ctx }); + } + else + { + method.Invoke(new T(), new object[] { ctx }); + } + }; } } -} \ No newline at end of file +} diff --git a/RestSharp.IntegrationTests/Helpers/SimpleServer.cs b/RestSharp.IntegrationTests/Helpers/SimpleServer.cs index e0a8067a1..eb7706746 100644 --- a/RestSharp.IntegrationTests/Helpers/SimpleServer.cs +++ b/RestSharp.IntegrationTests/Helpers/SimpleServer.cs @@ -8,7 +8,9 @@ public class SimpleServer : IDisposable { private readonly HttpListener listener; + private readonly Action handler; + private Thread thread; private SimpleServer(HttpListener listener, Action handler) @@ -20,8 +22,12 @@ private SimpleServer(HttpListener listener, Action handler) public static SimpleServer Create(string url, Action handler, AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous) { - var listener = new HttpListener { Prefixes = { url }, AuthenticationSchemes = authenticationSchemes }; - var server = new SimpleServer(listener, handler); + HttpListener listener = new HttpListener + { + Prefixes = { url }, + AuthenticationSchemes = authenticationSchemes + }; + SimpleServer server = new SimpleServer(listener, handler); server.Start(); @@ -39,7 +45,7 @@ public void Start() this.thread = new Thread(() => { - var context = this.listener.GetContext(); + HttpListenerContext context = this.listener.GetContext(); this.handler(context); diff --git a/RestSharp.IntegrationTests/Models/LinkedINMemberProfile.cs b/RestSharp.IntegrationTests/Models/LinkedINMemberProfile.cs index 7c31a7776..8f359656d 100644 --- a/RestSharp.IntegrationTests/Models/LinkedINMemberProfile.cs +++ b/RestSharp.IntegrationTests/Models/LinkedINMemberProfile.cs @@ -1,4 +1,5 @@ -namespace RestSharp.IntegrationTests.Models + +namespace RestSharp.IntegrationTests.Models { /// /// Model for used by the LinkedIN integration tests. diff --git a/RestSharp.IntegrationTests/MultipartFormDataTests.cs b/RestSharp.IntegrationTests/MultipartFormDataTests.cs index 08b393da9..e92586567 100644 --- a/RestSharp.IntegrationTests/MultipartFormDataTests.cs +++ b/RestSharp.IntegrationTests/MultipartFormDataTests.cs @@ -2,6 +2,7 @@ using System.IO; using System.Net; using System.Threading; +using System.Threading.Tasks; using NUnit.Framework; using RestSharp.IntegrationTests.Helpers; @@ -37,17 +38,29 @@ public void MultipartFormData_WithParameterAndFile_Async() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("/", Method.POST) { AlwaysMultipartFormData = true }; - string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "Assets\\TestFile.txt"); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("/", Method.POST) + { + AlwaysMultipartFormData = true + }; + DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()) + .Parent; + + if (directoryInfo != null) + { + string path = Path.Combine(directoryInfo.FullName, + "Assets\\TestFile.txt"); + + request.AddFile("fileName", path); + } - request.AddFile("fileName", path); request.AddParameter("controlName", "test", "application/json", ParameterType.RequestBody); - var task = client.ExecuteTaskAsync(request).ContinueWith(x => - { - Assert.AreEqual(this.expectedFileAndBodyRequestContent, x.Result.Content); - }); + Task task = client.ExecuteTaskAsync(request) + .ContinueWith(x => + { + Assert.AreEqual(this.expectedFileAndBodyRequestContent, x.Result.Content); + }); task.Wait(); } @@ -60,14 +73,24 @@ public void MultipartFormData_WithParameterAndFile() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("/", Method.POST) { AlwaysMultipartFormData = true }; - string path = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "Assets\\TestFile.txt"); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("/", Method.POST) + { + AlwaysMultipartFormData = true + }; + DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()) + .Parent; + + if (directoryInfo != null) + { + string path = Path.Combine(directoryInfo.FullName, "Assets\\TestFile.txt"); + + request.AddFile("fileName", path); + } - request.AddFile("fileName", path); request.AddParameter("controlName", "test", "application/json", ParameterType.RequestBody); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual(this.expectedFileAndBodyRequestContent, response.Content); } @@ -79,8 +102,11 @@ public void MultipartFormDataAsync() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("/", Method.POST) { AlwaysMultipartFormData = true }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("/", Method.POST) + { + AlwaysMultipartFormData = true + }; AddParameters(request); @@ -99,12 +125,15 @@ public void MultipartFormData() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("/", Method.POST) { AlwaysMultipartFormData = true }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("/", Method.POST) + { + AlwaysMultipartFormData = true + }; AddParameters(request); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual(this.expected, response.Content); } @@ -117,16 +146,16 @@ public void AlwaysMultipartFormData_WithParameter_Execute() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("?json_route=/posts") - { - AlwaysMultipartFormData = true, - Method = Method.POST, - }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("?json_route=/posts") + { + AlwaysMultipartFormData = true, + Method = Method.POST, + }; request.AddParameter("title", "test", ParameterType.RequestBody); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.Null(response.ErrorException); } @@ -139,16 +168,17 @@ public void AlwaysMultipartFormData_WithParameter_ExecuteTaskAsync() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("?json_route=/posts") - { - AlwaysMultipartFormData = true, - Method = Method.POST, - }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("?json_route=/posts") + { + AlwaysMultipartFormData = true, + Method = Method.POST, + }; request.AddParameter("title", "test", ParameterType.RequestBody); - var task = client.ExecuteTaskAsync(request).ContinueWith(x => { Assert.Null(x.Result.ErrorException); }); + Task task = client.ExecuteTaskAsync(request) + .ContinueWith(x => { Assert.Null(x.Result.ErrorException); }); task.Wait(); } @@ -161,18 +191,18 @@ public void AlwaysMultipartFormData_WithParameter_ExecuteAsync() using (SimpleServer.Create(baseUrl, EchoHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("?json_route=/posts") - { - AlwaysMultipartFormData = true, - Method = Method.POST, - }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("?json_route=/posts") + { + AlwaysMultipartFormData = true, + Method = Method.POST, + }; request.AddParameter("title", "test", ParameterType.RequestBody); IRestResponse syncResponse = null; - using (var eventWaitHandle = new AutoResetEvent(false)) + using (AutoResetEvent eventWaitHandle = new AutoResetEvent(false)) { client.ExecuteAsync(request, response => { @@ -191,7 +221,7 @@ private static void EchoHandler(HttpListenerContext obj) { obj.Response.StatusCode = 200; - var streamReader = new StreamReader(obj.Request.InputStream); + StreamReader streamReader = new StreamReader(obj.Request.InputStream); obj.Response.OutputStream.WriteStringUtf8(streamReader.ReadToEnd()); } @@ -202,4 +232,4 @@ private static void AddParameters(IRestRequest request) request.AddParameter("a name with spaces", "somedata"); } } -} \ No newline at end of file +} diff --git a/RestSharp.IntegrationTests/NonProtocolExceptionHandlingTests.cs b/RestSharp.IntegrationTests/NonProtocolExceptionHandlingTests.cs index f016f6d1f..81ba664a8 100644 --- a/RestSharp.IntegrationTests/NonProtocolExceptionHandlingTests.cs +++ b/RestSharp.IntegrationTests/NonProtocolExceptionHandlingTests.cs @@ -1,5 +1,6 @@ using System.Net; using System.Threading; +using System.Threading.Tasks; using NUnit.Framework; using RestSharp.IntegrationTests.Helpers; @@ -15,9 +16,9 @@ public class NonProtocolExceptionHandlingTests [Test] public void Handles_Non_Existent_Domain() { - var client = new RestClient("http://nonexistantdomainimguessing.org"); - var request = new RestRequest("foo"); - var response = client.Execute(request); + RestClient client = new RestClient("http://nonexistantdomainimguessing.org"); + RestRequest request = new RestRequest("foo"); + IRestResponse response = client.Execute(request); Assert.AreEqual(ResponseStatus.Error, response.ResponseStatus); } @@ -30,17 +31,17 @@ public class StupidClass [Test] public void Task_Handles_Non_Existent_Domain() { - var client = new RestClient("http://192.168.1.200:8001"); - var request = new RestRequest("/") - { - RequestFormat = DataFormat.Json, - Method = Method.GET - }; + RestClient client = new RestClient("http://192.168.1.200:8001"); + RestRequest request = new RestRequest("/") + { + RequestFormat = DataFormat.Json, + Method = Method.GET + }; + Task> task = client.ExecuteTaskAsync(request); - var task = client.ExecuteTaskAsync(request); task.Wait(); - var response = task.Result; + IRestResponse response = task.Result; Assert.IsInstanceOf(response.ErrorException); Assert.AreEqual("Unable to connect to the remote server", response.ErrorException.Message); @@ -59,9 +60,12 @@ public void Handles_Server_Timeout_Error() using (SimpleServer.Create(baseUrl, TimeoutHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404") { Timeout = 500 }; - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404") + { + Timeout = 500 + }; + IRestResponse response = client.Execute(request); Assert.NotNull(response.ErrorException); Assert.IsInstanceOf(response.ErrorException); @@ -73,12 +77,16 @@ public void Handles_Server_Timeout_Error() public void Handles_Server_Timeout_Error_Async() { const string baseUrl = "http://localhost:8888/"; - var resetEvent = new ManualResetEvent(false); + + ManualResetEvent resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl, TimeoutHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404") { Timeout = 500 }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404") + { + Timeout = 500 + }; IRestResponse response = null; client.ExecuteAsync(request, responseCb => @@ -104,9 +112,9 @@ public void Handles_Server_Timeout_Error_AsyncTask() using (SimpleServer.Create(baseUrl, TimeoutHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404") { Timeout = 500 }; - var task = client.ExecuteTaskAsync(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404") { Timeout = 500 }; + Task task = client.ExecuteTaskAsync(request); task.Wait(); @@ -133,9 +141,9 @@ public void Handles_Server_Timeout_Error_With_Deserializer() using (SimpleServer.Create(baseUrl, TimeoutHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404") { Timeout = 500 }; - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404") { Timeout = 500 }; + IRestResponse response = client.Execute(request); Assert.Null(response.Data); Assert.NotNull(response.ErrorException); diff --git a/RestSharp.IntegrationTests/Properties/AssemblyInfo.cs b/RestSharp.IntegrationTests/Properties/AssemblyInfo.cs index b76f755af..69811dfb7 100644 --- a/RestSharp.IntegrationTests/Properties/AssemblyInfo.cs +++ b/RestSharp.IntegrationTests/Properties/AssemblyInfo.cs @@ -4,6 +4,7 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("RestSharp.IntegrationTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -16,9 +17,11 @@ // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. + [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("d1867cb5-67ee-49c2-afd5-3c9f371b9b4c")] // Version information for an assembly consists of the following four values: @@ -31,5 +34,6 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] + [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/RestSharp.IntegrationTests/RequestBodyTests.cs b/RestSharp.IntegrationTests/RequestBodyTests.cs index 93b4af093..71f9317eb 100644 --- a/RestSharp.IntegrationTests/RequestBodyTests.cs +++ b/RestSharp.IntegrationTests/RequestBodyTests.cs @@ -14,10 +14,11 @@ public class RequestBodyTests public void Can_Not_Be_Added_To_GET_Request() { const Method httpMethod = Method.GET; + using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -37,8 +38,8 @@ public void Can_Have_No_Body_Added_To_POST_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); client.Execute(request); @@ -53,8 +54,8 @@ public void Can_Be_Added_To_POST_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -74,8 +75,8 @@ public void Can_Be_Added_To_PUT_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -95,8 +96,8 @@ public void Can_Be_Added_To_DELETE_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -116,8 +117,8 @@ public void Can_Not_Be_Added_To_HEAD_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -137,8 +138,8 @@ public void Can_Be_Added_To_OPTIONS_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -158,8 +159,8 @@ public void Can_Be_Added_To_PATCH_Request() using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; @@ -198,7 +199,7 @@ private class RequestBodyCapturer public static void Capture(HttpListenerContext context) { - var request = context.Request; + HttpListenerRequest request = context.Request; CapturedContentType = request.ContentType; CapturedHasEntityBody = request.HasEntityBody; @@ -207,7 +208,7 @@ public static void Capture(HttpListenerContext context) private static string StreamToString(Stream stream) { - var streamReader = new StreamReader(stream); + StreamReader streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); } } diff --git a/RestSharp.IntegrationTests/RequestHeadTests.cs b/RestSharp.IntegrationTests/RequestHeadTests.cs index 14081de70..037345664 100644 --- a/RestSharp.IntegrationTests/RequestHeadTests.cs +++ b/RestSharp.IntegrationTests/RequestHeadTests.cs @@ -21,16 +21,21 @@ public void SetupRequestHeadTests() public void Does_Not_Pass_Default_Credentials_When_Server_Does_Not_Negotiate() { const Method httpMethod = Method.GET; + using (SimpleServer.Create(BASE_URL, Handlers.Generic())) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) { UseDefaultCredentials = true }; + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) + { + UseDefaultCredentials = true + }; client.Execute(request); Assert.NotNull(RequestHeadCapturer.CapturedHeaders); - var keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast().ToArray(); + string[] keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast() + .ToArray(); Assert.False(keys.Contains("Authorization"), "Authorization header was present in HTTP request from client, even though server does not use the Negotiate scheme"); @@ -44,14 +49,18 @@ public void Passes_Default_Credentials_When_UseDefaultCredentials_Is_True() using (SimpleServer.Create(BASE_URL, Handlers.Generic(), AuthenticationSchemes.Negotiate)) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) { UseDefaultCredentials = true }; - var response = client.Execute(request); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) + { + UseDefaultCredentials = true + }; + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(RequestHeadCapturer.CapturedHeaders); - var keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast().ToArray(); + string[] keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast() + .ToArray(); Assert.True(keys.Contains("Authorization"), "Authorization header not present in HTTP request from client, even though UseDefaultCredentials = true"); @@ -65,15 +74,15 @@ public void Does_Not_Pass_Default_Credentials_When_UseDefaultCredentials_Is_Fals using (SimpleServer.Create(BASE_URL, Handlers.Generic(), AuthenticationSchemes.Negotiate)) { - var client = new RestClient(BASE_URL); - var request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) - { - // UseDefaultCredentials is currently false by default, - // but to make the test more robust in case that ever - // changes, it's better to explicitly set it here. - UseDefaultCredentials = false - }; - var response = client.Execute(request); + RestClient client = new RestClient(BASE_URL); + RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) + { + // UseDefaultCredentials is currently false by default, + // but to make the test more robust in case that ever + // changes, it's better to explicitly set it here. + UseDefaultCredentials = false + }; + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Null(RequestHeadCapturer.CapturedHeaders); @@ -93,7 +102,7 @@ public static void Initialize() public static void Capture(HttpListenerContext context) { - var request = context.Request; + HttpListenerRequest request = context.Request; CapturedHeaders = request.Headers; } diff --git a/RestSharp.IntegrationTests/RestSharp.IntegrationTests.Signed.csproj b/RestSharp.IntegrationTests/RestSharp.IntegrationTests.Signed.csproj index 21cb24ea3..7ebf2c9cc 100644 --- a/RestSharp.IntegrationTests/RestSharp.IntegrationTests.Signed.csproj +++ b/RestSharp.IntegrationTests/RestSharp.IntegrationTests.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 9.0.30729 2.0 - {47D3EBB9-0300-4AF8-BAC5-740D51454A63} + {3AC3B97E-D5AF-4462-BF5D-0EC28F4619C6} Library Properties RestSharp.IntegrationTests @@ -74,7 +74,7 @@ - + @@ -98,7 +98,7 @@ - {5ff943a5-260f-4042-b4ce-c4977bad4ebb} + {ed71eee1-29e5-437a-a4c7-06da0ec1aa92} RestSharp.Net4.Signed diff --git a/RestSharp.IntegrationTests/StatusCodeTests.cs b/RestSharp.IntegrationTests/StatusCodeTests.cs index 05f121a2b..f191994eb 100644 --- a/RestSharp.IntegrationTests/StatusCodeTests.cs +++ b/RestSharp.IntegrationTests/StatusCodeTests.cs @@ -14,11 +14,11 @@ public void Handles_GET_Request_404_Error() { Uri baseUrl = new Uri("http://localhost:8080/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, UrlToStatusCodeHandler)) + using (SimpleServer.Create(baseUrl.AbsoluteUri, UrlToStatusCodeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404"); - var response = client.Execute(request); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404"); + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } @@ -31,12 +31,12 @@ public void Handles_GET_Request_404_Error_With_Body() using (SimpleServer.Create(baseUrl.AbsoluteUri, UrlToStatusCodeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest("404"); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("404"); request.AddBody("This is the body"); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } @@ -52,10 +52,13 @@ public void Handles_Different_Root_Element_On_Http_Error() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic())) + using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("error") { RootElement = "Success" }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("error") + { + RootElement = "Success" + }; request.OnBeforeDeserialization = resp => { @@ -65,7 +68,7 @@ public void Handles_Different_Root_Element_On_Http_Error() } }; - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); Assert.AreEqual("Not found!", response.Data.Message); @@ -77,10 +80,13 @@ public void Handles_Default_Root_Element_On_No_Error() { Uri baseUrl = new Uri("http://localhost:8888/"); - using(SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic())) + using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic())) { - var client = new RestClient(baseUrl); - var request = new RestRequest("success") { RootElement = "Success" }; + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest("success") + { + RootElement = "Success" + }; request.OnBeforeDeserialization = resp => { @@ -90,7 +96,7 @@ public void Handles_Default_Root_Element_On_No_Error() } }; - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("Works!", response.Data.Message); @@ -100,12 +106,12 @@ public void Handles_Default_Root_Element_On_No_Error() public class ResponseHandler { - void error(HttpListenerContext context) + private void error(HttpListenerContext context) { context.Response.StatusCode = 400; context.Response.Headers.Add("Content-Type", "application/xml"); context.Response.OutputStream.WriteStringUtf8( -@" + @" Not found! @@ -113,12 +119,12 @@ void error(HttpListenerContext context) "); } - void errorwithbody(HttpListenerContext context) + private void errorwithbody(HttpListenerContext context) { context.Response.StatusCode = 400; context.Response.Headers.Add("Content-Type", "application/xml"); context.Response.OutputStream.WriteStringUtf8( -@" + @" Not found! @@ -126,10 +132,10 @@ void errorwithbody(HttpListenerContext context) "); } - void success(HttpListenerContext context) + private void success(HttpListenerContext context) { context.Response.OutputStream.WriteStringUtf8( -@" + @" Works! diff --git a/RestSharp.IntegrationTests/StructuredSyntaxSuffixTests.cs b/RestSharp.IntegrationTests/StructuredSyntaxSuffixTests.cs index 5eac5678a..612bd943c 100644 --- a/RestSharp.IntegrationTests/StructuredSyntaxSuffixTests.cs +++ b/RestSharp.IntegrationTests/StructuredSyntaxSuffixTests.cs @@ -17,6 +17,7 @@ private class Person } private const string XML_CONTENT = "Bob50"; + private const string JSON_CONTENT = @"{ ""name"":""Bob"", ""age"":50 }"; private static void QueryStringBasedContentAndContentTypeHandler(HttpListenerContext obj) @@ -33,13 +34,13 @@ public void By_default_content_types_with_JSON_structured_syntax_suffix_should_d using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest(); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(); request.AddParameter("ct", "application/vnd.somebody.something+json"); request.AddParameter("c", JSON_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); @@ -53,13 +54,13 @@ public void By_default_content_types_with_XML_structured_syntax_suffix_should_de using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest(); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(); request.AddParameter("ct", "application/vnd.somebody.something+xml"); request.AddParameter("c", XML_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); @@ -73,17 +74,17 @@ public void Content_type_that_matches_the_structured_syntax_suffix_format_but_wa using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); + RestClient client = new RestClient(baseUrl); // In spite of the content type (+xml), treat this specific content type as JSON client.AddHandler("application/vnd.somebody.something+xml", new JsonDeserializer()); - var request = new RestRequest(); + RestRequest request = new RestRequest(); request.AddParameter("ct", "application/vnd.somebody.something+xml"); request.AddParameter("c", JSON_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); @@ -97,17 +98,17 @@ public void Should_allow_wildcard_content_types_to_be_defined() using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); + RestClient client = new RestClient(baseUrl); // In spite of the content type, handle ALL structured syntax suffixes of "+xml" as JSON client.AddHandler("*+xml", new JsonDeserializer()); - var request = new RestRequest(); + RestRequest request = new RestRequest(); request.AddParameter("ct", "application/vnd.somebody.something+xml"); request.AddParameter("c", JSON_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); @@ -121,13 +122,13 @@ public void By_default_application_json_content_type_should_deserialize_as_JSON( using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest(); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(); request.AddParameter("ct", "application/json"); request.AddParameter("c", JSON_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); @@ -141,13 +142,13 @@ public void By_default_text_xml_content_type_should_deserialize_as_XML() using (SimpleServer.Create(baseUrl.AbsoluteUri, QueryStringBasedContentAndContentTypeHandler)) { - var client = new RestClient(baseUrl); - var request = new RestRequest(); + RestClient client = new RestClient(baseUrl); + RestRequest request = new RestRequest(); request.AddParameter("ct", "text/xml"); request.AddParameter("c", XML_CONTENT); - var response = client.Execute(request); + IRestResponse response = client.Execute(request); Assert.AreEqual("Bob", response.Data.Name); Assert.AreEqual(50, response.Data.Age); diff --git a/RestSharp.IntegrationTests/oAuth1Tests.cs b/RestSharp.IntegrationTests/oAuth1Tests.cs index 9938a893b..48c12c1c3 100644 --- a/RestSharp.IntegrationTests/oAuth1Tests.cs +++ b/RestSharp.IntegrationTests/oAuth1Tests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; @@ -8,7 +9,7 @@ using NUnit.Framework; using RestSharp.Authenticators; using RestSharp.Authenticators.OAuth; -using RestSharp.Contrib; +using RestSharp.Extensions.MonoHttp; using RestSharp.IntegrationTests.Models; namespace RestSharp.IntegrationTests @@ -23,20 +24,20 @@ public void Can_Authenticate_With_OAuth() const string consumerKey = ""; const string consumerSecret = ""; - var baseUrl = new Uri("https://api.twitter.com"); - var client = new RestClient(baseUrl) - { - Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) - }; - var request = new RestRequest("oauth/request_token", Method.POST); - var response = client.Execute(request); + Uri baseUrl = new Uri("https://api.twitter.com"); + RestClient client = new RestClient(baseUrl) + { + Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) + }; + RestRequest request = new RestRequest("oauth/request_token", Method.POST); + IRestResponse response = client.Execute(request); Assert.NotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var qs = HttpUtility.ParseQueryString(response.Content); - var oauthToken = qs["oauth_token"]; - var oauthTokenSecret = qs["oauth_token_secret"]; + NameValueCollection qs = HttpUtility.ParseQueryString(response.Content); + string oauthToken = qs["oauth_token"]; + string oauthTokenSecret = qs["oauth_token_secret"]; Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); @@ -44,7 +45,8 @@ public void Can_Authenticate_With_OAuth() request = new RestRequest("oauth/authorize"); request.AddParameter("oauth_token", oauthToken); - var url = client.BuildUri(request).ToString(); + string url = client.BuildUri(request) + .ToString(); Process.Start(url); @@ -105,24 +107,28 @@ public void Can_Authenticate_Twitter() Assert.True(File.Exists(@"..\..\config.json")); - var config = SimpleJson.DeserializeObject(File.ReadAllText(@"..\..\config.json")) as JsonObject; - var client = new RestClient("https://api.twitter.com/1.1") - { - Authenticator = OAuth1Authenticator.ForProtectedResource( - (string) config["ConsumerKey"], - (string) config["ConsumerSecret"], - (string) config["AccessToken"], - (string) config["AccessSecret"]) - }; + JsonObject config = SimpleJson.DeserializeObject(File.ReadAllText(@"..\..\config.json")) as JsonObject; - var request = new RestRequest("account/verify_credentials.json"); + if (config != null) + { + RestClient client = new RestClient("https://api.twitter.com/1.1") + { + Authenticator = OAuth1Authenticator.ForProtectedResource( + (string) config["ConsumerKey"], + (string) config["ConsumerSecret"], + (string) config["AccessToken"], + (string) config["AccessSecret"]) + }; - request.AddParameter("include_entities", "true", ParameterType.QueryString); + RestRequest request = new RestRequest("account/verify_credentials.json"); - var response = client.Execute(request); + request.AddParameter("include_entities", "true", ParameterType.QueryString); - Assert.NotNull(response); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + IRestResponse response = client.Execute(request); + + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + } } #region Netflix test classes @@ -154,35 +160,36 @@ public void Can_Authenticate_Netflix_With_OAuth() const string consumerKey = ""; const string consumerSecret = ""; - var baseUrl = new Uri("http://api.netflix.com"); - var client = new RestClient(baseUrl) - { - Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) - }; - var request = new RestRequest("oauth/request_token"); - var response = client.Execute(request); + Uri baseUrl = new Uri("http://api.netflix.com"); + RestClient client = new RestClient(baseUrl) + { + Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) + }; + RestRequest request = new RestRequest("oauth/request_token"); + IRestResponse response = client.Execute(request); Assert.NotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - var qs = HttpUtility.ParseQueryString(response.Content); - var oauthToken = qs["oauth_token"]; - var oauthTokenSecret = qs["oauth_token_secret"]; - var applicationName = qs["application_name"]; + NameValueCollection qs = HttpUtility.ParseQueryString(response.Content); + string oauthToken = qs["oauth_token"]; + string oauthTokenSecret = qs["oauth_token_secret"]; + string applicationName = qs["application_name"]; Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); Assert.NotNull(applicationName); - var baseSslUrl = new Uri("https://api-user.netflix.com"); - var sslClient = new RestClient(baseSslUrl); + Uri baseSslUrl = new Uri("https://api-user.netflix.com"); + RestClient sslClient = new RestClient(baseSslUrl); request = new RestRequest("oauth/login"); request.AddParameter("oauth_token", oauthToken); request.AddParameter("oauth_consumer_key", consumerKey); request.AddParameter("application_name", applicationName); - var url = sslClient.BuildUri(request).ToString(); + string url = sslClient.BuildUri(request) + .ToString(); Process.Start(url); @@ -198,7 +205,7 @@ public void Can_Authenticate_Netflix_With_OAuth() oauthToken = qs["oauth_token"]; oauthTokenSecret = qs["oauth_token_secret"]; - var userId = qs["user_id"]; + string userId = qs["user_id"]; Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); @@ -210,7 +217,7 @@ public void Can_Authenticate_Netflix_With_OAuth() request.AddUrlSegment("user_id", userId); request.AddParameter("max_results", "2"); - var queueResponse = client.Execute(request); + IRestResponse queueResponse = client.Execute(request); Assert.NotNull(queueResponse); Assert.AreEqual(HttpStatusCode.OK, queueResponse.StatusCode); @@ -221,8 +228,12 @@ public void Can_Authenticate_Netflix_With_OAuth() [Test] public void Properly_Encodes_Parameter_Names() { - var postData = new WebParameterCollection { { "name[first]", "Chuck" }, { "name[last]", "Testa" } }; - var sortedParams = OAuthTools.SortParametersExcludingSignature(postData); + WebParameterCollection postData = new WebParameterCollection + { + {"name[first]", "Chuck"}, + {"name[last]", "Testa"} + }; + WebParameterCollection sortedParams = OAuthTools.SortParametersExcludingSignature(postData); Assert.AreEqual("name%5Bfirst%5D", sortedParams[0].Name); } @@ -231,12 +242,15 @@ public void Properly_Encodes_Parameter_Names() public void Use_RFC_3986_Encoding_For_Auth_Signature_Base() { // reserved characters for 2396 and 3986 - var reserved2396Characters = new[] { ";", "/", "?", ":", "@", "&", "=", "+", "$", "," }; // http://www.ietf.org/rfc/rfc2396.txt - var additionalReserved3986Characters = new[] { "!", "*", "'", "(", ")" }; // http://www.ietf.org/rfc/rfc3986.txt - var reservedCharacterString = string.Join(string.Empty, reserved2396Characters.Union(additionalReserved3986Characters)); + // http://www.ietf.org/rfc/rfc2396.txt + string[] reserved2396Characters = { ";", "/", "?", ":", "@", "&", "=", "+", "$", "," }; + // http://www.ietf.org/rfc/rfc3986.txt + string[] additionalReserved3986Characters = { "!", "*", "'", "(", ")" }; + string reservedCharacterString = string.Join(string.Empty, + reserved2396Characters.Union(additionalReserved3986Characters)); // act - var escapedString = OAuthTools.UrlEncodeRelaxed(reservedCharacterString); + string escapedString = OAuthTools.UrlEncodeRelaxed(reservedCharacterString); // assert Assert.AreEqual("%3B%2F%3F%3A%40%26%3D%2B%24%2C%21%2A%27%28%29", escapedString); @@ -250,20 +264,21 @@ public void Can_Authenticate_LinkedIN_With_OAuth() const string consumerSecret = "TODO_CONSUMER_SECRET_HERE"; // request token - var client = new RestClient - { - BaseUrl = new Uri("https://api.linkedin.com/uas/oauth"), - Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret, "http://localhost") - }; - var requestTokenRequest = new RestRequest("requestToken"); - var requestTokenResponse = client.Execute(requestTokenRequest); + RestClient client = new RestClient + { + BaseUrl = new Uri("https://api.linkedin.com/uas/oauth"), + Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret, + "http://localhost") + }; + RestRequest requestTokenRequest = new RestRequest("requestToken"); + IRestResponse requestTokenResponse = client.Execute(requestTokenRequest); Assert.NotNull(requestTokenResponse); Assert.AreEqual(HttpStatusCode.OK, requestTokenResponse.StatusCode); - var requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content); - var requestToken = requestTokenResponseParameters["oauth_token"]; - var requestSecret = requestTokenResponseParameters["oauth_token_secret"]; + NameValueCollection requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content); + string requestToken = requestTokenResponseParameters["oauth_token"]; + string requestSecret = requestTokenResponseParameters["oauth_token_secret"]; Assert.NotNull(requestToken); Assert.NotNull(requestSecret); @@ -271,7 +286,7 @@ public void Can_Authenticate_LinkedIN_With_OAuth() // redirect user requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken); - var redirectUri = client.BuildUri(requestTokenRequest); + Uri redirectUri = client.BuildUri(requestTokenRequest); Process.Start(redirectUri.ToString()); @@ -286,21 +301,21 @@ public void Can_Authenticate_LinkedIN_With_OAuth() Debugger.Break(); // get the access token - var requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(requestUrl).Query); - var requestVerifier = requestTokenQueryParameters["oauth_verifier"]; + NameValueCollection requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(requestUrl).Query); + string requestVerifier = requestTokenQueryParameters["oauth_verifier"]; client.Authenticator = OAuth1Authenticator.ForAccessToken( consumerKey, consumerSecret, requestToken, requestSecret, requestVerifier); - var requestAccessTokenRequest = new RestRequest("accessToken"); - var requestActionTokenResponse = client.Execute(requestAccessTokenRequest); + RestRequest requestAccessTokenRequest = new RestRequest("accessToken"); + IRestResponse requestActionTokenResponse = client.Execute(requestAccessTokenRequest); Assert.NotNull(requestActionTokenResponse); Assert.AreEqual(HttpStatusCode.OK, requestActionTokenResponse.StatusCode); - var requestActionTokenResponseParameters = HttpUtility.ParseQueryString(requestActionTokenResponse.Content); - var accessToken = requestActionTokenResponseParameters["oauth_token"]; - var accessSecret = requestActionTokenResponseParameters["oauth_token_secret"]; + NameValueCollection requestActionTokenResponseParameters = HttpUtility.ParseQueryString(requestActionTokenResponse.Content); + string accessToken = requestActionTokenResponseParameters["oauth_token"]; + string accessSecret = requestActionTokenResponseParameters["oauth_token_secret"]; Assert.NotNull(accessToken); Assert.NotNull(accessSecret); @@ -316,16 +331,16 @@ public void Can_Retrieve_Member_Profile_Field_Field_Selector_From_LinkedIN() const string accessSecret = "TODO_ACCES_SECRET_HERE"; // arrange - var client = new RestClient - { - BaseUrl = new Uri("http://api.linkedin.com/v1"), - Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, - accessToken, accessSecret) - }; - var request = new RestRequest("people/~:(id,first-name,last-name)"); + RestClient client = new RestClient + { + BaseUrl = new Uri("http://api.linkedin.com/v1"), + Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, + consumerSecret, accessToken, accessSecret) + }; + RestRequest request = new RestRequest("people/~:(id,first-name,last-name)"); // act - var response = client.Execute(request); + IRestResponse response = client.Execute(request); // assert Assert.NotNull(response); @@ -344,12 +359,12 @@ public void Can_Query_Vimeo() const string consumerSecret = "TODO_CONSUMER_SECRET_HERE"; // arrange - var client = new RestClient - { - BaseUrl = new Uri("http://vimeo.com/api/rest/v2"), - Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) - }; - var request = new RestRequest(); + RestClient client = new RestClient + { + BaseUrl = new Uri("http://vimeo.com/api/rest/v2"), + Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) + }; + RestRequest request = new RestRequest(); request.AddParameter("format", "json"); request.AddParameter("method", "vimeo.videos.search"); @@ -357,7 +372,7 @@ public void Can_Query_Vimeo() request.AddParameter("full_response", 1); // act - var response = client.Execute(request); + IRestResponse response = client.Execute(request); // assert Assert.NotNull(response); diff --git a/RestSharp.IntegrationTests/packages.config b/RestSharp.IntegrationTests/packages.config index 512ce05d0..babd286d5 100644 --- a/RestSharp.IntegrationTests/packages.config +++ b/RestSharp.IntegrationTests/packages.config @@ -1,4 +1,5 @@  + - + \ No newline at end of file diff --git a/RestSharp.Net4/Extensions/RestClientExtensions.cs b/RestSharp.Net4/Extensions/RestClientExtensions.cs deleted file mode 100644 index 553c6ce78..000000000 --- a/RestSharp.Net4/Extensions/RestClientExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ - -namespace RestSharp.Extensions -{ - public static partial class RestClientExtensions - { - public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) - { - var response = client.Execute(request); - var generic = (RestResponse)response; - dynamic content = SimpleJson.DeserializeObject(response.Content); - - generic.Data = content; - - return generic; - } - } -} diff --git a/RestSharp.Net4/RestSharp.Net4.Signed.csproj b/RestSharp.Net4/RestSharp.Net4.Signed.csproj index 9ef2cdb48..648c4a4e5 100644 --- a/RestSharp.Net4/RestSharp.Net4.Signed.csproj +++ b/RestSharp.Net4/RestSharp.Net4.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 8.0.30703 2.0 - {5FF943A5-260F-4042-B4CE-C4977BAD4EBB} + {ED71EEE1-29E5-437A-A4C7-06DA0EC1AA92} Library Properties RestSharp @@ -277,7 +277,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net4/RestSharp.Net4.csproj b/RestSharp.Net4/RestSharp.Net4.csproj index beb393491..80a5dc7a5 100644 --- a/RestSharp.Net4/RestSharp.Net4.csproj +++ b/RestSharp.Net4/RestSharp.Net4.csproj @@ -266,7 +266,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net45/Extensions/RestClientExtensions.cs b/RestSharp.Net45/Extensions/RestClientExtensions.cs deleted file mode 100644 index 553c6ce78..000000000 --- a/RestSharp.Net45/Extensions/RestClientExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ - -namespace RestSharp.Extensions -{ - public static partial class RestClientExtensions - { - public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) - { - var response = client.Execute(request); - var generic = (RestResponse)response; - dynamic content = SimpleJson.DeserializeObject(response.Content); - - generic.Data = content; - - return generic; - } - } -} diff --git a/RestSharp.Net45/RestSharp.Net45.Signed.csproj b/RestSharp.Net45/RestSharp.Net45.Signed.csproj index 31da08e0c..9540e17b3 100644 --- a/RestSharp.Net45/RestSharp.Net45.Signed.csproj +++ b/RestSharp.Net45/RestSharp.Net45.Signed.csproj @@ -280,7 +280,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net45/RestSharp.Net45.csproj b/RestSharp.Net45/RestSharp.Net45.csproj index 98424a96a..9315d548a 100644 --- a/RestSharp.Net45/RestSharp.Net45.csproj +++ b/RestSharp.Net45/RestSharp.Net45.csproj @@ -269,7 +269,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net451/Extensions/RestClientExtensions.cs b/RestSharp.Net451/Extensions/RestClientExtensions.cs deleted file mode 100644 index 553c6ce78..000000000 --- a/RestSharp.Net451/Extensions/RestClientExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ - -namespace RestSharp.Extensions -{ - public static partial class RestClientExtensions - { - public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) - { - var response = client.Execute(request); - var generic = (RestResponse)response; - dynamic content = SimpleJson.DeserializeObject(response.Content); - - generic.Data = content; - - return generic; - } - } -} diff --git a/RestSharp.Net451/RestSharp.Net451.Signed.csproj b/RestSharp.Net451/RestSharp.Net451.Signed.csproj index 01b04593e..8674f164d 100644 --- a/RestSharp.Net451/RestSharp.Net451.Signed.csproj +++ b/RestSharp.Net451/RestSharp.Net451.Signed.csproj @@ -280,7 +280,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net451/RestSharp.Net451.csproj b/RestSharp.Net451/RestSharp.Net451.csproj index 43dc07f28..3a6b282b2 100644 --- a/RestSharp.Net451/RestSharp.Net451.csproj +++ b/RestSharp.Net451/RestSharp.Net451.csproj @@ -269,7 +269,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net452/Extensions/RestClientExtensions.cs b/RestSharp.Net452/Extensions/RestClientExtensions.cs deleted file mode 100644 index 553c6ce78..000000000 --- a/RestSharp.Net452/Extensions/RestClientExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ - -namespace RestSharp.Extensions -{ - public static partial class RestClientExtensions - { - public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) - { - var response = client.Execute(request); - var generic = (RestResponse)response; - dynamic content = SimpleJson.DeserializeObject(response.Content); - - generic.Data = content; - - return generic; - } - } -} diff --git a/RestSharp.Net452/RestSharp.Net452.Signed.csproj b/RestSharp.Net452/RestSharp.Net452.Signed.csproj index fe6e497cf..d0574d9d7 100644 --- a/RestSharp.Net452/RestSharp.Net452.Signed.csproj +++ b/RestSharp.Net452/RestSharp.Net452.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 8.0.30703 2.0 - {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110} + {F4C74773-8D8E-4A7D-977B-DE985B4D49D9} Library Properties RestSharp @@ -280,7 +280,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net452/RestSharp.Net452.csproj b/RestSharp.Net452/RestSharp.Net452.csproj index 03d8c4c0c..47f0faa4b 100644 --- a/RestSharp.Net452/RestSharp.Net452.csproj +++ b/RestSharp.Net452/RestSharp.Net452.csproj @@ -269,7 +269,6 @@ Validation\Validate.cs - diff --git a/RestSharp.Net46/Properties/AssemblyInfo.cs b/RestSharp.Net46/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..9c1b96b16 --- /dev/null +++ b/RestSharp.Net46/Properties/AssemblyInfo.cs @@ -0,0 +1,24 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("RestSharp")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("97044cbf-6c9d-4b08-87e3-bf30fbde1933")] + +#if SIGNED +[assembly: InternalsVisibleTo("RestSharp.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d"), + InternalsVisibleTo("RestSharp.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d")] +#else +[assembly: InternalsVisibleTo("RestSharp.IntegrationTests"), + InternalsVisibleTo("RestSharp.Tests")] +#endif diff --git a/RestSharp.Net46/RestSharp.Net46.Signed.csproj b/RestSharp.Net46/RestSharp.Net46.Signed.csproj new file mode 100644 index 000000000..b47f077c9 --- /dev/null +++ b/RestSharp.Net46/RestSharp.Net46.Signed.csproj @@ -0,0 +1,300 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110} + Library + Properties + RestSharp + RestSharp + v4.5.2 + 512 + ..\ + true + + + + true + full + false + bin\DebugSigned\ + obj\DebugSigned\ + TRACE;DEBUG;FRAMEWORK, NET4, SIGNED + prompt + 4 + bin\DebugSigned\RestSharp.xml + 1591,1584,1572,1574,1658 + false + + + pdbonly + true + bin\ReleaseSigned\ + obj\ReleaseSigned\ + TRACE;FRAMEWORK, NET4, SIGNED + prompt + 4 + bin\ReleaseSigned\RestSharp.xml + 1591,1573,1658,1584,1574,1572 + true + false + + + true + + + ..\RestSharp.snk + + + false + + + + + + + + + + + + + Authenticators\HttpBasicAuthenticator.cs + + + Authenticators\IAuthenticator.cs + + + Authenticators\JwtAuthenticator.cs + + + Authenticators\NtlmAuthenticator.cs + + + Authenticators\OAuth1Authenticator.cs + + + Authenticators\OAuth2Authenticator.cs + + + Authenticators\OAuth\Extensions\CollectionExtensions.cs + + + Authenticators\OAuth\Extensions\OAuthExtensions.cs + + + Authenticators\OAuth\Extensions\StringExtensions.cs + + + Authenticators\OAuth\Extensions\TimeExtensions.cs + + + Authenticators\OAuth\HttpPostParameter.cs + + + Authenticators\OAuth\HttpPostParameterType.cs + + + Authenticators\OAuth\OAuthParameterHandling.cs + + + Authenticators\OAuth\OAuthSignatureMethod.cs + + + Authenticators\OAuth\OAuthSignatureTreatment.cs + + + Authenticators\OAuth\OAuthTools.cs + + + Authenticators\OAuth\OAuthType.cs + + + Authenticators\OAuth\OAuthWebQueryInfo.cs + + + Authenticators\OAuth\OAuthWorkflow.cs + + + Authenticators\OAuth\WebPair.cs + + + Authenticators\OAuth\WebPairCollection.cs + + + Authenticators\OAuth\WebParameter.cs + + + Authenticators\OAuth\WebParameterCollection.cs + + + Authenticators\SimpleAuthenticator.cs + + + Deserializers\DeserializeAsAttribute.cs + + + Deserializers\DotNetXmlDeserializer.cs + + + Deserializers\IDeserializer.cs + + + Deserializers\JsonDeserializer.cs + + + Deserializers\XmlAttributeDeserializer.cs + + + Deserializers\XmlDeserializer.cs + + + Enum.cs + + + Extensions\MiscExtensions.cs + + + Extensions\MonoHttp\Helpers.cs + + + Extensions\MonoHttp\HtmlEncoder.cs + + + Extensions\MonoHttp\HttpUtility.cs + + + Extensions\ReflectionExtensions.cs + + + Extensions\ResponseExtensions.cs + + + Extensions\ResponseStatusExtensions.cs + + + Extensions\StringExtensions.cs + + + Extensions\XmlExtensions.cs + + + FileParameter.cs + + + Http.Async.cs + + + Http.cs + + + Http.Sync.cs + + + HttpCookie.cs + + + HttpFile.cs + + + HttpHeader.cs + + + HttpParameter.cs + + + HttpResponse.cs + + + IHttp.cs + + + IHttpFactory.cs + + + IHttpResponse.cs + + + IRestClient.cs + + + IRestRequest.cs + + + IRestResponse.cs + + + Parameter.cs + + + RestClient.Async.cs + + + RestClient.cs + + + RestClient.Sync.cs + + + RestClientExtensions.cs + + + RestRequest.cs + + + RestRequestAsyncHandle.cs + + + RestResponse.cs + + + RestResponseCookie.cs + + + Serializers\DotNetXmlSerializer.cs + + + Serializers\ISerializer.cs + + + Serializers\JsonSerializer.cs + + + Serializers\SerializeAsAttribute.cs + + + Serializers\XmlSerializer.cs + + + SharedAssemblyInfo.cs + + + Validation\Require.cs + + + SimpleJson.cs + + + Validation\Validate.cs + + + + + + RestSharp.snk + + + + + + + \ No newline at end of file diff --git a/RestSharp.Net46/RestSharp.Net46.csproj b/RestSharp.Net46/RestSharp.Net46.csproj new file mode 100644 index 000000000..97b7a43d1 --- /dev/null +++ b/RestSharp.Net46/RestSharp.Net46.csproj @@ -0,0 +1,288 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {47C29B0E-D6F9-4FAA-B321-20053A1E3EE2} + Library + Properties + RestSharp + RestSharp + v4.6 + 512 + ..\ + true + + + + true + full + false + bin\Debug\ + TRACE;DEBUG;FRAMEWORK, NET4 + prompt + 4 + bin\Debug\RestSharp.xml + 1591,1584,1572,1574,1658 + false + + + pdbonly + true + bin\Release\ + TRACE;FRAMEWORK, NET4 + prompt + 4 + bin\Release\RestSharp.xml + 1591,1573,1658,1584,1574,1572 + true + false + + + + + + + + + + + + + Authenticators\HttpBasicAuthenticator.cs + + + Authenticators\IAuthenticator.cs + + + Authenticators\JwtAuthenticator.cs + + + Authenticators\NtlmAuthenticator.cs + + + Authenticators\OAuth1Authenticator.cs + + + Authenticators\OAuth2Authenticator.cs + + + Authenticators\OAuth\Extensions\CollectionExtensions.cs + + + Authenticators\OAuth\Extensions\OAuthExtensions.cs + + + Authenticators\OAuth\Extensions\StringExtensions.cs + + + Authenticators\OAuth\Extensions\TimeExtensions.cs + + + Authenticators\OAuth\HttpPostParameter.cs + + + Authenticators\OAuth\HttpPostParameterType.cs + + + Authenticators\OAuth\OAuthParameterHandling.cs + + + Authenticators\OAuth\OAuthSignatureMethod.cs + + + Authenticators\OAuth\OAuthSignatureTreatment.cs + + + Authenticators\OAuth\OAuthTools.cs + + + Authenticators\OAuth\OAuthType.cs + + + Authenticators\OAuth\OAuthWebQueryInfo.cs + + + Authenticators\OAuth\OAuthWorkflow.cs + + + Authenticators\OAuth\WebPair.cs + + + Authenticators\OAuth\WebPairCollection.cs + + + Authenticators\OAuth\WebParameter.cs + + + Authenticators\OAuth\WebParameterCollection.cs + + + Authenticators\SimpleAuthenticator.cs + + + Deserializers\DeserializeAsAttribute.cs + + + Deserializers\DotNetXmlDeserializer.cs + + + Deserializers\IDeserializer.cs + + + Deserializers\JsonDeserializer.cs + + + Deserializers\XmlAttributeDeserializer.cs + + + Deserializers\XmlDeserializer.cs + + + Enum.cs + + + Extensions\MiscExtensions.cs + + + Extensions\MonoHttp\Helpers.cs + + + Extensions\MonoHttp\HtmlEncoder.cs + + + Extensions\MonoHttp\HttpUtility.cs + + + Extensions\ReflectionExtensions.cs + + + Extensions\ResponseExtensions.cs + + + Extensions\ResponseStatusExtensions.cs + + + Extensions\StringExtensions.cs + + + Extensions\XmlExtensions.cs + + + FileParameter.cs + + + Http.Async.cs + + + Http.cs + + + Http.Sync.cs + + + HttpCookie.cs + + + HttpFile.cs + + + HttpHeader.cs + + + HttpParameter.cs + + + HttpResponse.cs + + + IHttp.cs + + + IHttpFactory.cs + + + IHttpResponse.cs + + + IRestClient.cs + + + IRestRequest.cs + + + IRestResponse.cs + + + Parameter.cs + + + RestClient.Async.cs + + + RestClient.cs + + + RestClient.Sync.cs + + + RestClientExtensions.cs + + + RestRequest.cs + + + RestRequestAsyncHandle.cs + + + RestResponse.cs + + + RestResponseCookie.cs + + + Serializers\DotNetXmlSerializer.cs + + + Serializers\ISerializer.cs + + + Serializers\JsonSerializer.cs + + + Serializers\SerializeAsAttribute.cs + + + Serializers\XmlSerializer.cs + + + SharedAssemblyInfo.cs + + + Validation\Require.cs + + + SimpleJson.cs + + + Validation\Validate.cs + + + + + + Designer + + + + + + \ No newline at end of file diff --git a/RestSharp.Net46/packages.config b/RestSharp.Net46/packages.config new file mode 100644 index 000000000..6b8deb9c9 --- /dev/null +++ b/RestSharp.Net46/packages.config @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/RestSharp.Signed.sln b/RestSharp.Signed.sln index 1973b999f..73fed770b 100644 --- a/RestSharp.Signed.sln +++ b/RestSharp.Signed.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 -VisualStudioVersion = 12.0.30723.0 +VisualStudioVersion = 12.0.40629.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{E709A928-A45C-4622-A35C-CCD8EE44CA80}" ProjectSection(SolutionItems) = preProject @@ -25,8 +25,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Meta", "Meta", "{C5B02FAA-6 releasenotes.markdown = releasenotes.markdown EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Signed", "RestSharp\RestSharp.Signed.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests.Signed", "RestSharp.Tests\RestSharp.Tests.Signed.csproj", "{1464E4AC-18BB-4F23-8A0B-68196F9E1871}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.IntegrationTests.Signed", "RestSharp.IntegrationTests\RestSharp.IntegrationTests.Signed.csproj", "{47D3EBB9-0300-4AF8-BAC5-740D51454A63}" @@ -45,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net451.Signed", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net452.Signed", "RestSharp.Net452\RestSharp.Net452.Signed.csproj", "{BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net35.Signed", "RestSharp\RestSharp.Net35.Signed.csproj", "{3190E0DC-674C-4C41-A7A3-BD2F406963B0}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -57,18 +57,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|ARM.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|ARM.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.Build.0 = Debug|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -179,6 +167,18 @@ Global {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|Mixed Platforms.Build.0 = Release|Any CPU {BD61DB80-63AC-4BFD-8232-A5C4DD9B8110}.Release|x86.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|ARM.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Debug|x86.ActiveCfg = Debug|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Any CPU.Build.0 = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|ARM.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {3190E0DC-674C-4C41-A7A3-BD2F406963B0}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/RestSharp.Tests/AddRangeTests.cs b/RestSharp.Tests/AddRangeTests.cs index e529f70f2..e19127656 100644 --- a/RestSharp.Tests/AddRangeTests.cs +++ b/RestSharp.Tests/AddRangeTests.cs @@ -8,11 +8,11 @@ public class AddRangeTests [Test] public void ShouldParseOutRangeSpecifier() { - var restClient = new RestClient("http://localhost"); - var req = new RestRequest("bob", Method.GET); - + RestClient restClient = new RestClient("http://localhost"); + RestRequest req = new RestRequest("bob", Method.GET); + req.AddHeader("Range", "pages=1-2"); restClient.Execute(req); } } -} \ No newline at end of file +} diff --git a/RestSharp.Tests/CultureChange.cs b/RestSharp.Tests/CultureChange.cs index 90f04dfd5..ac76123de 100644 --- a/RestSharp.Tests/CultureChange.cs +++ b/RestSharp.Tests/CultureChange.cs @@ -11,15 +11,15 @@ public class CultureChange : IDisposable public CultureChange(string culture) { if (culture == null) + { throw new ArgumentNullException("culture"); + } this.PreviousCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); } - #region IDisposable Members - public void Dispose() { if (this.PreviousCulture != null) @@ -29,7 +29,5 @@ public void Dispose() this.PreviousCulture = null; } } - - #endregion } } diff --git a/RestSharp.Tests/Fakes/NullHttp.cs b/RestSharp.Tests/Fakes/NullHttp.cs index 9634ec45c..5c0ccbfb6 100644 --- a/RestSharp.Tests/Fakes/NullHttp.cs +++ b/RestSharp.Tests/Fakes/NullHttp.cs @@ -1,5 +1,4 @@ - -namespace RestSharp.Tests.Fakes +namespace RestSharp.Tests.Fakes { public class NullHttp : Http { diff --git a/RestSharp.Tests/InterfaceImplementationTests.cs b/RestSharp.Tests/InterfaceImplementationTests.cs index a78c110cc..8a9491cd9 100644 --- a/RestSharp.Tests/InterfaceImplementationTests.cs +++ b/RestSharp.Tests/InterfaceImplementationTests.cs @@ -13,24 +13,28 @@ public class InterfaceImplementationTests public void IRestSharp_Has_All_RestSharp_Signatures() { // Arrange - var restClientImplementationType = typeof(RestClient); - var restClientInterfaceType = typeof(IRestClient); + Type restClientImplementationType = typeof(RestClient); + Type restClientInterfaceType = typeof(IRestClient); const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; // Act - IEnumerable compareResult = CompareTypes(restClientImplementationType, restClientInterfaceType, bindingFlags); - compareResult.ToList().ForEach(x => Console.WriteLine("Method {0} exists in {1} but not in {2}", x, restClientImplementationType.FullName, restClientInterfaceType.FullName)); + List compareResult = CompareTypes(restClientImplementationType, restClientInterfaceType, + bindingFlags).ToList(); + + compareResult.ForEach(x => Console.WriteLine("Method {0} exists in {1} but not in {2}", x, + restClientImplementationType.FullName, restClientInterfaceType.FullName)); // Assert Assert.AreEqual(0, compareResult.Count()); } - private static IEnumerable CompareTypes(Type type1, Type type2, BindingFlags bindingFlags) + private static IEnumerable CompareTypes(IReflect type1, IReflect type2, BindingFlags bindingFlags) { MethodInfo[] typeTMethodInfo = type1.GetMethods(bindingFlags); MethodInfo[] typeXMethodInfo = type2.GetMethods(bindingFlags); - return typeTMethodInfo.Select(x => x.Name).Except(typeXMethodInfo.Select(x => x.Name)); + return typeTMethodInfo.Select(x => x.Name) + .Except(typeXMethodInfo.Select(x => x.Name)); } } } diff --git a/RestSharp.Tests/JsonTests.cs b/RestSharp.Tests/JsonTests.cs index ab1659b60..bda88777c 100644 --- a/RestSharp.Tests/JsonTests.cs +++ b/RestSharp.Tests/JsonTests.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -37,9 +39,9 @@ public class JsonTests public void Can_Deserialize_Exponential_Notation() { const string content = "{ \"Value\": 4.8e-04 }"; - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = content }); - var expected = Decimal.Parse("4.8e-04", NumberStyles.Float, CultureInfo.InvariantCulture); + JsonDeserializer json = new JsonDeserializer(); + DecimalNumber output = json.Deserialize(new RestResponse { Content = content }); + decimal expected = decimal.Parse("4.8e-04", NumberStyles.Float, CultureInfo.InvariantCulture); Assert.NotNull(output); Assert.AreEqual(expected, output.Value); @@ -49,8 +51,8 @@ public void Can_Deserialize_Exponential_Notation() public void Can_Deserialize_Into_Struct() { const string content = "{\"one\":\"oneOneOne\", \"two\":\"twoTwoTwo\", \"three\":3}"; - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer(); + SimpleStruct output = json.Deserialize(new RestResponse { Content = content }); Assert.NotNull(output); Assert.AreEqual("oneOneOne", output.One); @@ -61,10 +63,10 @@ public void Can_Deserialize_Into_Struct() [Test] public void Can_Deserialize_Select_Tokens() { - var data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var output = json.Deserialize(response); + string data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + StatusComplexList output = json.Deserialize(response); Assert.AreEqual(4, output.Count); } @@ -72,10 +74,9 @@ public void Can_Deserialize_Select_Tokens() [Test] public void Can_Deserialize_4sq_Json_With_Root_Element_Specified() { - var doc = File.ReadAllText(Path.Combine("SampleData", "4sq.txt")); - var json = new JsonDeserializer { RootElement = "response" }; - - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "4sq.txt")); + JsonDeserializer json = new JsonDeserializer { RootElement = "response" }; + VenuesResponse output = json.Deserialize(new RestResponse { Content = doc }); Assert.IsNotEmpty(output.Groups); } @@ -83,9 +84,9 @@ public void Can_Deserialize_4sq_Json_With_Root_Element_Specified() [Test] public void Can_Deserialize_Lists_of_Simple_Types() { - var doc = File.ReadAllText(Path.Combine("SampleData", "jsonlists.txt")); - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "jsonlists.txt")); + JsonDeserializer json = new JsonDeserializer(); + JsonLists output = json.Deserialize(new RestResponse { Content = doc }); Assert.IsNotEmpty(output.Names); Assert.IsNotEmpty(output.Numbers); @@ -95,8 +96,8 @@ public void Can_Deserialize_Lists_of_Simple_Types() public void Can_Deserialize_Simple_Generic_List_of_Simple_Types() { const string content = "{\"users\":[\"johnsheehan\",\"jagregory\",\"drusellers\",\"structuremap\"]}"; - var json = new JsonDeserializer { RootElement = "users" }; - var output = json.Deserialize>(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer { RootElement = "users" }; + List output = json.Deserialize>(new RestResponse { Content = content }); Assert.IsNotEmpty(output); } @@ -105,8 +106,8 @@ public void Can_Deserialize_Simple_Generic_List_of_Simple_Types() public void Can_Deserialize_Simple_Generic_List_of_Simple_Types_With_Nulls() { const string content = "{\"users\":[\"johnsheehan\",\"jagregory\",null,\"drusellers\",\"structuremap\"]}"; - var json = new JsonDeserializer { RootElement = "users" }; - var output = json.Deserialize>(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer { RootElement = "users" }; + List output = json.Deserialize>(new RestResponse { Content = content }); Assert.IsNotEmpty(output); Assert.AreEqual(null, output[2]); @@ -117,8 +118,8 @@ public void Can_Deserialize_Simple_Generic_List_of_Simple_Types_With_Nulls() public void Can_Deserialize_Simple_Generic_List_Given_Item_Without_Array() { const string content = "{\"users\":\"johnsheehan\"}"; - var json = new JsonDeserializer { RootElement = "users" }; - var output = json.Deserialize>(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer { RootElement = "users" }; + List output = json.Deserialize>(new RestResponse { Content = content }); Assert.True(output.SequenceEqual(new[] { "johnsheehan" })); } @@ -127,8 +128,8 @@ public void Can_Deserialize_Simple_Generic_List_Given_Item_Without_Array() public void Can_Deserialize_Simple_Generic_List_Given_Toplevel_Item_Without_Array() { const string content = "\"johnsheehan\""; - var json = new JsonDeserializer(); - var output = json.Deserialize>(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer(); + List output = json.Deserialize>(new RestResponse { Content = content }); Assert.True(output.SequenceEqual(new[] { "johnsheehan" })); } @@ -136,10 +137,9 @@ public void Can_Deserialize_Simple_Generic_List_Given_Toplevel_Item_Without_Arra [Test] public void Can_Deserialize_From_Root_Element() { - var doc = File.ReadAllText(Path.Combine("SampleData", "sojson.txt")); - var json = new JsonDeserializer { RootElement = "User" }; - - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "sojson.txt")); + JsonDeserializer json = new JsonDeserializer { RootElement = "User" }; + SoUser output = json.Deserialize(new RestResponse { Content = doc }); Assert.AreEqual("John Sheehan", output.DisplayName); } @@ -147,13 +147,14 @@ public void Can_Deserialize_From_Root_Element() [Test] public void Can_Deserialize_To_Dictionary_String_Object() { - var doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary.txt")); - var json = new JsonDeserializer(); - var output = json.Deserialize>(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary.txt")); + JsonDeserializer json = new JsonDeserializer(); + Dictionary output = + json.Deserialize>(new RestResponse { Content = doc }); Assert.AreEqual(output.Keys.Count, 3); - var firstKeysVal = output.FirstOrDefault().Value; + object firstKeysVal = output.FirstOrDefault().Value; Assert.IsInstanceOf(firstKeysVal); } @@ -161,13 +162,14 @@ public void Can_Deserialize_To_Dictionary_String_Object() [Test] public void Can_Deserialize_To_Dictionary_Int_Object() { - var doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary_KeysType.txt")); - var json = new JsonDeserializer(); - var output = json.Deserialize>(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary_KeysType.txt")); + JsonDeserializer json = new JsonDeserializer(); + Dictionary output = + json.Deserialize>(new RestResponse { Content = doc }); Assert.AreEqual(output.Keys.Count, 2); - var firstKeysVal = output.FirstOrDefault().Value; + object firstKeysVal = output.FirstOrDefault().Value; Assert.IsInstanceOf(firstKeysVal); } @@ -175,9 +177,10 @@ public void Can_Deserialize_To_Dictionary_Int_Object() [Test] public void Can_Deserialize_Generic_Members() { - var doc = File.ReadAllText(Path.Combine("SampleData", "GenericWithList.txt")); - var json = new JsonDeserializer(); - var output = json.Deserialize>>(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "GenericWithList.txt")); + JsonDeserializer json = new JsonDeserializer(); + Generic> output = + json.Deserialize>>(new RestResponse { Content = doc }); Assert.AreEqual("Foe sho", output.Data.Items[0].Nickname); } @@ -187,13 +190,13 @@ public void Can_Deserialize_List_of_Guid() { Guid id1 = new Guid("b0e5c11f-e944-478c-aadd-753b956d0c8c"); Guid id2 = new Guid("809399fa-21c4-4dca-8dcd-34cb697fbca0"); - var data = new JsonObject(); + JsonObject data = new JsonObject(); data["Ids"] = new JsonArray { id1, id2 }; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = data.ToString() }; - var p = d.Deserialize(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = data.ToString() }; + GuidList p = d.Deserialize(response); Assert.AreEqual(2, p.Ids.Count); Assert.AreEqual(id1, p.Ids[0]); @@ -205,13 +208,17 @@ public void Can_Deserialize_Generic_List_of_DateTime() { DateTime item1 = new DateTime(2010, 2, 8, 11, 11, 11); DateTime item2 = item1.AddSeconds(12345); - var data = new JsonObject(); + JsonObject data = new JsonObject(); - data["Items"] = new JsonArray { item1.ToString("u"), item2.ToString("u") }; + data["Items"] = new JsonArray + { + item1.ToString("u"), + item2.ToString("u") + }; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = data.ToString() }; - var p = d.Deserialize>(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = data.ToString() }; + GenericWithList p = d.Deserialize>(response); Assert.AreEqual(2, p.Items.Count); Assert.AreEqual(item1, p.Items[0]); @@ -224,7 +231,7 @@ public void Can_Deserialize_DateTime_With_DateTimeStyles() DateTime item0 = new DateTime(2010, 2, 8, 11, 11, 11, DateTimeKind.Local); DateTime item1 = new DateTime(2011, 2, 8, 11, 11, 11, DateTimeKind.Utc); DateTime item2 = new DateTime(2012, 2, 8, 11, 11, 11, DateTimeKind.Unspecified); - var data = new JsonObject(); + JsonObject data = new JsonObject(); data["Items"] = new JsonArray { @@ -234,9 +241,9 @@ public void Can_Deserialize_DateTime_With_DateTimeStyles() "/Date(1309421746929+0000)/" }; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = data.ToString() }; - var p = d.Deserialize>(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = data.ToString() }; + GenericWithList p = d.Deserialize>(response); Assert.AreNotEqual(item0.Kind, p.Items[0].Kind); Assert.AreEqual(item1.Kind, p.Items[1].Kind); @@ -247,9 +254,9 @@ public void Can_Deserialize_DateTime_With_DateTimeStyles() [Test] public void Can_Deserialize_Null_Elements_to_Nullable_Values() { - var doc = this.CreateJsonWithNullValues(); - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = CreateJsonWithNullValues(); + JsonDeserializer json = new JsonDeserializer(); + NullableValues output = json.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -259,9 +266,9 @@ public void Can_Deserialize_Null_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { - var doc = this.CreateJsonWithEmptyValues(); - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = CreateJsonWithEmptyValues(); + JsonDeserializer json = new JsonDeserializer(); + NullableValues output = json.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -271,9 +278,9 @@ public void Can_Deserialize_Empty_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_Elements_to_Nullable_Values() { - var doc = this.CreateJsonWithoutEmptyValues(); - var json = new JsonDeserializer(); - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = CreateJsonWithoutEmptyValues(); + JsonDeserializer json = new JsonDeserializer(); + NullableValues output = json.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); @@ -291,8 +298,8 @@ public void Can_Deserialize_Elements_to_Nullable_Values() public void Can_Deserialize_Json_Using_DeserializeAs_Attribute() { const string content = "{\"sid\":\"asdasdasdasdasdasdasda\",\"friendlyName\":\"VeryNiceName\",\"oddballPropertyName\":\"blahblah\"}"; - var json = new JsonDeserializer { RootElement = "users" }; - var output = json.Deserialize(new RestResponse { Content = content }); + JsonDeserializer json = new JsonDeserializer { RootElement = "users" }; + Oddball output = json.Deserialize(new RestResponse { Content = content }); Assert.NotNull(output); Assert.AreEqual("blahblah", output.GoodPropertyName); @@ -301,14 +308,18 @@ public void Can_Deserialize_Json_Using_DeserializeAs_Attribute() [Test] public void Can_Deserialize_Custom_Formatted_Date() { - var culture = CultureInfo.InvariantCulture; + CultureInfo culture = CultureInfo.InvariantCulture; const string format = "dd yyyy MMM, hh:mm ss tt"; - var date = new DateTime(2010, 2, 8, 11, 11, 11); + DateTime date = new DateTime(2010, 2, 8, 11, 11, 11); var formatted = new { StartDate = date.ToString(format, culture) }; - var data = SimpleJson.SerializeObject(formatted); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer { DateFormat = format, Culture = culture }; - var output = json.Deserialize(response); + string data = SimpleJson.SerializeObject(formatted); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer + { + DateFormat = format, + Culture = culture + }; + PersonForJson output = json.Deserialize(response); Assert.AreEqual(date, output.StartDate); } @@ -316,10 +327,10 @@ public void Can_Deserialize_Custom_Formatted_Date() [Test] public void Can_Deserialize_Root_Json_Array_To_List() { - var data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var output = json.Deserialize>(response); + string data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + List output = json.Deserialize>(response); Assert.AreEqual(4, output.Count); } @@ -327,10 +338,10 @@ public void Can_Deserialize_Root_Json_Array_To_List() [Test] public void Can_Deserialize_Root_Json_Array_To_Inherited_List() { - var data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var output = json.Deserialize(response); + string data = File.ReadAllText(Path.Combine("SampleData", "jsonarray.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + StatusList output = json.Deserialize(response); Assert.AreEqual(4, output.Count); } @@ -338,10 +349,10 @@ public void Can_Deserialize_Root_Json_Array_To_Inherited_List() [Test] public void Can_Deserialize_Various_Enum_Values() { - var data = File.ReadAllText(Path.Combine("SampleData", "jsonenums.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var output = json.Deserialize(response); + string data = File.ReadAllText(Path.Combine("SampleData", "jsonenums.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + JsonEnumsTestStructure output = json.Deserialize(response); Assert.AreEqual(Disposition.Friendly, output.Upper); Assert.AreEqual(Disposition.Friendly, output.Lower); @@ -356,10 +367,10 @@ public void Can_Deserialize_Various_Enum_Values() [Test] public void Can_Deserialize_Various_Enum_Types() { - var data = File.ReadAllText(Path.Combine("SampleData", "jsonenumtypes.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var output = json.Deserialize(response); + string data = File.ReadAllText(Path.Combine("SampleData", "jsonenumtypes.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + JsonEnumTypesTestStructure output = json.Deserialize(response); Assert.AreEqual(ByteEnum.EnumMin, output.ByteEnumType); Assert.AreEqual(SByteEnum.EnumMin, output.SByteEnumType); @@ -375,9 +386,9 @@ public void Can_Deserialize_Various_Enum_Types() public void Deserialization_Of_Undefined_Int_Value_Returns_Enum_Default() { const string data = @"{ ""Integer"" : 1024 }"; - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer(); - var result = json.Deserialize(response); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer(); + JsonEnumsTestStructure result = json.Deserialize(response); Assert.AreEqual(Disposition.Friendly, result.Integer); } @@ -385,13 +396,13 @@ public void Deserialization_Of_Undefined_Int_Value_Returns_Enum_Default() [Test] public void Can_Deserialize_Guid_String_Fields() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Guid"] = GUID_STRING; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc.ToString() }; - var p = d.Deserialize(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc.ToString() }; + PersonForJson p = d.Deserialize(response); Assert.AreEqual(new Guid(GUID_STRING), p.Guid); } @@ -399,13 +410,13 @@ public void Can_Deserialize_Guid_String_Fields() [Test] public void Can_Deserialize_Quoted_Primitive() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Age"] = "28"; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc.ToString() }; - var p = d.Deserialize(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc.ToString() }; + PersonForJson p = d.Deserialize(response); Assert.AreEqual(28, p.Age); } @@ -413,13 +424,13 @@ public void Can_Deserialize_Quoted_Primitive() [Test] public void Can_Deserialize_Int_to_Bool() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["IsCool"] = 1; - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc.ToString() }; - var p = d.Deserialize(response); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc.ToString() }; + PersonForJson p = d.Deserialize(response); Assert.True(p.IsCool); } @@ -427,10 +438,10 @@ public void Can_Deserialize_Int_to_Bool() [Test] public void Can_Deserialize_With_Default_Root() { - var doc = this.CreateJson(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var p = d.Deserialize(response); + string doc = CreateJson(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + PersonForJson p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc), p.StartDate); @@ -466,11 +477,10 @@ public void Can_Deserialize_With_Default_Root_Alternative_Culture() [Test] public void Can_Deserialize_Names_With_Underscore_Prefix() { - var data = File.ReadAllText(Path.Combine("SampleData", "underscore_prefix.txt")); - var response = new RestResponse { Content = data }; - var json = new JsonDeserializer { RootElement = "User" }; - - var output = json.Deserialize(response); + string data = File.ReadAllText(Path.Combine("SampleData", "underscore_prefix.txt")); + RestResponse response = new RestResponse { Content = data }; + JsonDeserializer json = new JsonDeserializer { RootElement = "User" }; + SoUser output = json.Deserialize(response); Assert.AreEqual("John Sheehan", output.DisplayName); Assert.AreEqual(1786, output.Id); @@ -479,10 +489,10 @@ public void Can_Deserialize_Names_With_Underscore_Prefix() [Test] public void Can_Deserialize_Names_With_Underscores_With_Default_Root() { - var doc = this.CreateJsonWithUnderscores(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var p = d.Deserialize(response); + string doc = CreateJsonWithUnderscores(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + PersonForJson p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -514,10 +524,10 @@ public void Can_Deserialize_Names_With_Underscores_With_Default_Root_Alternative [Test] public void Can_Deserialize_Names_With_Dashes_With_Default_Root() { - var doc = this.CreateJsonWithDashes(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var p = d.Deserialize(response); + string doc = CreateJsonWithDashes(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + PersonForJson p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); //Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc), p.StartDate); @@ -549,10 +559,10 @@ public void Can_Deserialize_Names_With_Dashes_With_Default_Root_Alternative_Cult [Test] public void Ignore_Protected_Property_That_Exists_In_Data() { - var doc = this.CreateJson(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var p = d.Deserialize(response); + string doc = CreateJson(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + PersonForJson p = d.Deserialize(response); Assert.Null(p.IgnoreProxy); } @@ -560,10 +570,10 @@ public void Ignore_Protected_Property_That_Exists_In_Data() [Test] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { - var doc = this.CreateJson(); - var response = new RestResponse { Content = doc }; - var d = new JsonDeserializer(); - var p = d.Deserialize(response); + string doc = CreateJson(); + RestResponse response = new RestResponse { Content = doc }; + JsonDeserializer d = new JsonDeserializer(); + PersonForJson p = d.Deserialize(response); Assert.Null(p.ReadOnlyProxy); } @@ -571,7 +581,7 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() [Test] public void Can_Deserialize_TimeSpan() { - var payload = this.GetPayLoad("timespans.txt"); + TimeSpanTestStructure payload = GetPayLoad("timespans.txt"); Assert.AreEqual(new TimeSpan(468006), payload.Tick); Assert.AreEqual(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond); @@ -594,10 +604,10 @@ public void Can_Deserialize_TimeSpan() [Test] public void Can_Deserialize_Iso_Json_Dates() { - var doc = this.CreateIsoDateJson(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var bd = d.Deserialize(response); + string doc = CreateIsoDateJson(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + Birthdate bd = d.Deserialize(response); Assert.AreEqual(new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc), bd.Value); } @@ -605,10 +615,10 @@ public void Can_Deserialize_Iso_Json_Dates() [Test] public void Can_Deserialize_Unix_Json_Dates() { - var doc = this.CreateUnixDateJson(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var bd = d.Deserialize(response); + string doc = CreateUnixDateJson(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + Birthdate bd = d.Deserialize(response); Assert.AreEqual(new DateTime(2011, 6, 30, 8, 15, 46, DateTimeKind.Utc), bd.Value); } @@ -616,7 +626,7 @@ public void Can_Deserialize_Unix_Json_Dates() [Test] public void Can_Deserialize_JsonNet_Dates() { - var person = this.GetPayLoad("person.json.txt"); + PersonForJson person = GetPayLoad("person.json.txt"); Assert.AreEqual( new DateTime(2011, 6, 30, 8, 15, 46, 929, DateTimeKind.Utc), @@ -626,7 +636,7 @@ public void Can_Deserialize_JsonNet_Dates() [Test] public void Can_Deserialize_DateTime() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.AreEqual( new DateTime(2011, 6, 30, 8, 15, 46, 929, DateTimeKind.Utc), @@ -636,7 +646,7 @@ public void Can_Deserialize_DateTime() [Test] public void Can_Deserialize_Nullable_DateTime_With_Value() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.NotNull(payload.NullableDateTimeWithValue); Assert.AreEqual( @@ -647,7 +657,7 @@ public void Can_Deserialize_Nullable_DateTime_With_Value() [Test] public void Can_Deserialize_Nullable_DateTime_With_Null() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.Null(payload.NullableDateTimeWithNull); } @@ -655,7 +665,7 @@ public void Can_Deserialize_Nullable_DateTime_With_Null() [Test] public void Can_Deserialize_DateTimeOffset() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.AreEqual( new DateTime(2011, 6, 30, 8, 15, 46, 929, DateTimeKind.Utc).ToString("yyyy-MM-dd HH:mm:ss.fff"), @@ -665,7 +675,7 @@ public void Can_Deserialize_DateTimeOffset() [Test] public void Can_Deserialize_Iso8601DateTimeLocal() { - var payload = this.GetPayLoad("iso8601datetimes.txt"); + Iso8601DateTimeTestStructure payload = GetPayLoad("iso8601datetimes.txt"); Assert.AreEqual( new DateTime(2012, 7, 19, 10, 23, 25, DateTimeKind.Utc), @@ -675,7 +685,7 @@ public void Can_Deserialize_Iso8601DateTimeLocal() [Test] public void Can_Deserialize_Iso8601DateTimeZulu() { - var payload = this.GetPayLoad("iso8601datetimes.txt"); + Iso8601DateTimeTestStructure payload = GetPayLoad("iso8601datetimes.txt"); Assert.AreEqual( new DateTime(2012, 7, 19, 10, 23, 25, 544, DateTimeKind.Utc), @@ -685,7 +695,7 @@ public void Can_Deserialize_Iso8601DateTimeZulu() [Test] public void Can_Deserialize_Iso8601DateTimeWithOffset() { - var payload = this.GetPayLoad("iso8601datetimes.txt"); + Iso8601DateTimeTestStructure payload = GetPayLoad("iso8601datetimes.txt"); Assert.AreEqual( new DateTime(2012, 7, 19, 10, 23, 25, 544, DateTimeKind.Utc), @@ -695,7 +705,7 @@ public void Can_Deserialize_Iso8601DateTimeWithOffset() [Test] public void Can_Deserialize_Nullable_DateTimeOffset_With_Value() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.NotNull(payload.NullableDateTimeOffsetWithValue); Assert.AreEqual( @@ -706,7 +716,7 @@ public void Can_Deserialize_Nullable_DateTimeOffset_With_Value() [Test] public void Can_Deserialize_Nullable_DateTimeOffset_With_Null() { - var payload = this.GetPayLoad("datetimes.txt"); + DateTimeTestStructure payload = GetPayLoad("datetimes.txt"); Assert.Null(payload.NullableDateTimeOffsetWithNull); } @@ -714,10 +724,10 @@ public void Can_Deserialize_Nullable_DateTimeOffset_With_Null() [Test] public void Can_Deserialize_To_Dictionary_String_String() { - var doc = this.CreateJsonStringDictionary(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var bd = d.Deserialize>(response); + string doc = this.CreateJsonStringDictionary(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + Dictionary bd = d.Deserialize>(response); Assert.AreEqual(bd["Thing1"], "Thing1"); Assert.AreEqual(bd["Thing2"], "Thing2"); @@ -728,10 +738,10 @@ public void Can_Deserialize_To_Dictionary_String_String() [Test] public void Can_Deserialize_To_Dictionary_String_String_With_Dynamic_Values() { - var doc = this.CreateDynamicJsonStringDictionary(); - var d = new JsonDeserializer(); - var response = new RestResponse { Content = doc }; - var bd = d.Deserialize>(response); + string doc = this.CreateDynamicJsonStringDictionary(); + JsonDeserializer d = new JsonDeserializer(); + RestResponse response = new RestResponse { Content = doc }; + Dictionary bd = d.Deserialize>(response); Assert.AreEqual("[\"Value1\",\"Value2\"]", bd["Thing1"]); Assert.AreEqual("Thing2", bd["Thing2"]); @@ -743,9 +753,9 @@ public void Can_Deserialize_To_Dictionary_String_String_With_Dynamic_Values() public void Can_Deserialize_Decimal_With_Four_Zeros_After_Floating_Point() { const string json = "{\"Value\":0.00005557}"; - var response = new RestResponse { Content = json }; - var d = new JsonDeserializer(); - var result = d.Deserialize(response); + RestResponse response = new RestResponse { Content = json }; + JsonDeserializer d = new JsonDeserializer(); + DecimalNumber result = d.Deserialize(response); Assert.AreEqual(result.Value, .00005557m); } @@ -753,7 +763,7 @@ public void Can_Deserialize_Decimal_With_Four_Zeros_After_Floating_Point() [Test] public void Can_Deserialize_Object_Type_Property_With_Primitive_Vale() { - var payload = this.GetPayLoad("objectproperty.txt"); + ObjectProperties payload = GetPayLoad("objectproperty.txt"); Assert.AreEqual(42L, payload.ObjectProperty); } @@ -761,19 +771,18 @@ public void Can_Deserialize_Object_Type_Property_With_Primitive_Vale() [Test] public void Can_Deserialize_Dictionary_of_Lists() { - var doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary.txt")); - var json = new JsonDeserializer { RootElement = "response" }; - - var output = json.Deserialize(new RestResponse { Content = doc }); + string doc = File.ReadAllText(Path.Combine("SampleData", "jsondictionary.txt")); + JsonDeserializer json = new JsonDeserializer { RootElement = "response" }; + EmployeeTracker output = json.Deserialize(new RestResponse { Content = doc }); Assert.IsNotEmpty(output.EmployeesMail); Assert.IsNotEmpty(output.EmployeesTime); Assert.IsNotEmpty(output.EmployeesPay); } - private string CreateJsonWithUnderscores() + private static string CreateJsonWithUnderscores() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["name"] = "John Sheehan"; doc["start_date"] = new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc); @@ -786,38 +795,38 @@ private string CreateJsonWithUnderscores() doc["url"] = "http://example.com"; doc["url_path"] = "/foo/bar"; doc["best_friend"] = new JsonObject - { - {"name", "The Fonz"}, - {"since", 1952} - }; + { + { "name", "The Fonz" }, + { "since", 1952 } + }; - var friendsArray = new JsonArray(); + JsonArray friendsArray = new JsonArray(); for (int i = 0; i < 10; i++) { friendsArray.Add(new JsonObject - { - {"name", "Friend" + i}, - {"since", DateTime.Now.Year - i} - }); + { + { "name", "Friend" + i }, + { "since", DateTime.Now.Year - i } + }); } doc["friends"] = friendsArray; - var foesArray = new JsonObject - { - {"dict1", new JsonObject {{"nickname", "Foe 1"}}}, - {"dict2", new JsonObject {{"nickname", "Foe 2"}}} - }; + JsonObject foesArray = new JsonObject + { + { "dict1", new JsonObject { { "nickname", "Foe 1" } } }, + { "dict2", new JsonObject { { "nickname", "Foe 2" } } } + }; doc["foes"] = foesArray; return doc.ToString(); } - private string CreateJsonWithDashes() + private static string CreateJsonWithDashes() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["name"] = "John Sheehan"; doc["start-date"] = new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc); @@ -829,59 +838,58 @@ private string CreateJsonWithDashes() doc["read-only"] = "dummy"; doc["url"] = "http://example.com"; doc["url-path"] = "/foo/bar"; - doc["best-friend"] = new JsonObject - { - {"name", "The Fonz"}, - {"since", 1952} - }; + { + { "name", "The Fonz" }, + { "since", 1952 } + }; - var friendsArray = new JsonArray(); + JsonArray friendsArray = new JsonArray(); for (int i = 0; i < 10; i++) { friendsArray.Add(new JsonObject - { - {"name", "Friend" + i}, - {"since", DateTime.Now.Year - i} - }); + { + { "name", "Friend" + i }, + { "since", DateTime.Now.Year - i } + }); } doc["friends"] = friendsArray; - var foesArray = new JsonObject - { - {"dict1", new JsonObject {{"nickname", "Foe 1"}}}, - {"dict2", new JsonObject {{"nickname", "Foe 2"}}} - }; + JsonObject foesArray = new JsonObject + { + { "dict1", new JsonObject { { "nickname", "Foe 1" } } }, + { "dict2", new JsonObject { { "nickname", "Foe 2" } } } + }; doc["foes"] = foesArray; return doc.ToString(); } - private string CreateIsoDateJson() + private static string CreateIsoDateJson() { - var bd = new Birthdate - { - Value = new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc) - }; + Birthdate bd = new Birthdate + { + Value = new DateTime(1910, 9, 25, 9, 30, 25, DateTimeKind.Utc) + }; return SimpleJson.SerializeObject(bd); } - private string CreateUnixDateJson() + private static string CreateUnixDateJson() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Value"] = 1309421746; return doc.ToString(); } - private string CreateJson() + private static string CreateJson() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Name"] = "John Sheehan"; doc["StartDate"] = new DateTime(2009, 9, 25, 0, 6, 1, DateTimeKind.Utc); @@ -898,38 +906,38 @@ private string CreateJson() doc["Guid"] = new Guid(GUID_STRING).ToString(); doc["EmptyGuid"] = ""; doc["BestFriend"] = new JsonObject - { - {"Name", "The Fonz"}, - {"Since", 1952} - }; + { + { "Name", "The Fonz" }, + { "Since", 1952 } + }; - var friendsArray = new JsonArray(); + JsonArray friendsArray = new JsonArray(); for (int i = 0; i < 10; i++) { friendsArray.Add(new JsonObject - { - {"Name", "Friend" + i}, - {"Since", DateTime.Now.Year - i} - }); + { + { "Name", "Friend" + i }, + { "Since", DateTime.Now.Year - i } + }); } doc["Friends"] = friendsArray; - var foesArray = new JsonObject - { - {"dict1", new JsonObject {{"Nickname", "Foe 1"}}}, - {"dict2", new JsonObject {{"Nickname", "Foe 2"}}} - }; + JsonObject foesArray = new JsonObject + { + { "dict1", new JsonObject { { "nickname", "Foe 1" } } }, + { "dict2", new JsonObject { { "nickname", "Foe 2" } } } + }; doc["Foes"] = foesArray; return doc.ToString(); } - private string CreateJsonWithNullValues() + private static string CreateJsonWithNullValues() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Id"] = null; doc["StartDate"] = null; @@ -938,9 +946,9 @@ private string CreateJsonWithNullValues() return doc.ToString(); } - private string CreateJsonWithEmptyValues() + private static string CreateJsonWithEmptyValues() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Id"] = ""; doc["StartDate"] = ""; @@ -949,9 +957,9 @@ private string CreateJsonWithEmptyValues() return doc.ToString(); } - private string CreateJsonWithoutEmptyValues() + private static string CreateJsonWithoutEmptyValues() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Id"] = 123; doc["StartDate"] = new DateTime(2010, 2, 21, 9, 35, 00, DateTimeKind.Utc); @@ -962,7 +970,7 @@ private string CreateJsonWithoutEmptyValues() public string CreateJsonStringDictionary() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); doc["Thing1"] = "Thing1"; doc["Thing2"] = "Thing2"; @@ -974,21 +982,33 @@ public string CreateJsonStringDictionary() public string CreateDynamicJsonStringDictionary() { - var doc = new JsonObject(); + JsonObject doc = new JsonObject(); - doc["Thing1"] = new JsonArray { "Value1", "Value2" }; + doc["Thing1"] = new JsonArray + { + "Value1", + "Value2" + }; doc["Thing2"] = "Thing2"; - doc["ThingRed"] = new JsonObject { { "Name", "ThingRed" }, { "Color", "Red" } }; - doc["ThingBlue"] = new JsonObject { { "Name", "ThingBlue" }, { "Color", "Blue" } }; + doc["ThingRed"] = new JsonObject + { + { "Name", "ThingRed" }, + { "Color", "Red" } + }; + doc["ThingBlue"] = new JsonObject + { + { "Name", "ThingBlue" }, + { "Color", "Blue" } + }; return doc.ToString(); } - private T GetPayLoad(string fileName) + private static T GetPayLoad(string fileName) { - var doc = File.ReadAllText(Path.Combine("SampleData", fileName)); - var response = new RestResponse { Content = doc }; - var d = new JsonDeserializer(); + string doc = File.ReadAllText(Path.Combine("SampleData", fileName)); + RestResponse response = new RestResponse { Content = doc }; + JsonDeserializer d = new JsonDeserializer(); return d.Deserialize(response); } diff --git a/RestSharp.Tests/JwtAuthTests.cs b/RestSharp.Tests/JwtAuthTests.cs index d5f803d69..6172a88ab 100644 --- a/RestSharp.Tests/JwtAuthTests.cs +++ b/RestSharp.Tests/JwtAuthTests.cs @@ -1,47 +1,51 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Threading; using NUnit.Framework; +using RestSharp.Authenticators; namespace RestSharp.Tests { [TestFixture] public class JwtAuthTests { - readonly string testJwt; - readonly string expectedAuthHeaderContent; - + private readonly string testJwt; + + private readonly string expectedAuthHeaderContent; + public JwtAuthTests() { - System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; - System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture; this.testJwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" + "." + - "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo" + - "gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" + "." + - "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo" + + "gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" + "." + + "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; - this.expectedAuthHeaderContent = String.Format("Bearer {0}", this.testJwt); + this.expectedAuthHeaderContent = string.Format("Bearer {0}", this.testJwt); } - + [Test] public void Throw_Argument_Null_Exception() { - var exception = Assert.Throws(() => new JwtAuthenticator(null)); - + ArgumentNullException exception = Assert.Throws(() => new JwtAuthenticator(null)); + Assert.AreEqual("accessToken", exception.ParamName); } [Test] public void Can_Set_ValidFormat_Auth_Header() { - var client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) }; - var request = new RestRequest(); + RestClient client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) }; + RestRequest request = new RestRequest(); //In real case client.Execute(request) will invoke Authenticate method client.Authenticator.Authenticate(client, request); - var authParam = request.Parameters.Single(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)); + Parameter authParam = request.Parameters.Single(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)); Assert.True(authParam.Type == ParameterType.HttpHeader); Assert.AreEqual(this.expectedAuthHeaderContent, authParam.Value); @@ -50,8 +54,8 @@ public void Can_Set_ValidFormat_Auth_Header() [Test] public void Check_Only_Header_Authorization() { - var client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) }; - var request = new RestRequest(); + RestClient client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) }; + RestRequest request = new RestRequest(); //Paranoic server needs "two-factor authentication": jwt header and query param key for example request.AddParameter("Authorization", "manualAuth", ParameterType.QueryString); @@ -59,12 +63,12 @@ public void Check_Only_Header_Authorization() //In real case client.Execute(request) will invoke Authenticate method client.Authenticator.Authenticate(client, request); - var paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization")); + List paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization")); Assert.AreEqual(2, paramList.Count); - var queryAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.QueryString)); - var headerAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.HttpHeader)); + Parameter queryAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.QueryString)); + Parameter headerAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.HttpHeader)); Assert.AreEqual("manualAuth", queryAuthParam.Value); Assert.AreEqual(this.expectedAuthHeaderContent, headerAuthParam.Value); @@ -73,8 +77,8 @@ public void Check_Only_Header_Authorization() [Test] public void Set_Auth_Header_Only_Once() { - var client = new RestClient(); - var request = new RestRequest(); + RestClient client = new RestClient(); + RestRequest request = new RestRequest(); request.AddHeader("Authorization", this.expectedAuthHeaderContent); @@ -83,11 +87,11 @@ public void Set_Auth_Header_Only_Once() //In real case client.Execute(...) will invoke Authenticate method client.Authenticator.Authenticate(client, request); - var paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization")); + List paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization")); Assert.AreEqual(1, paramList.Count); - var authParam = paramList[0]; + Parameter authParam = paramList[0]; Assert.True(authParam.Type == ParameterType.HttpHeader); Assert.AreEqual(this.expectedAuthHeaderContent, authParam.Value); diff --git a/RestSharp.Tests/NamespacedXmlTests.cs b/RestSharp.Tests/NamespacedXmlTests.cs index 66eb1baff..9cb96a7ec 100644 --- a/RestSharp.Tests/NamespacedXmlTests.cs +++ b/RestSharp.Tests/NamespacedXmlTests.cs @@ -1,4 +1,5 @@ #region Licensed + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -19,6 +21,7 @@ using System.Xml.Linq; using NUnit.Framework; using RestSharp.Deserializers; +using RestSharp.Tests.SampleClasses; using RestSharp.Tests.SampleClasses.Lastfm; namespace RestSharp.Tests @@ -31,10 +34,10 @@ public class NamespacedXmlTests [Test] public void Can_Deserialize_Elements_With_Namespace() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -55,10 +58,10 @@ public void Can_Deserialize_Elements_With_Namespace() [Test] public void Can_Deserialize_Elements_With_Namespace_Autodetect_Namespace() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -79,10 +82,10 @@ public void Can_Deserialize_Elements_With_Namespace_Autodetect_Namespace() [Test] public void Can_Deserialize_Attributes_With_Namespace() { - var doc = CreateAttributesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var p = d.Deserialize(response); + string doc = CreateAttributesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -101,10 +104,10 @@ public void Can_Deserialize_Attributes_With_Namespace() [Test] public void Ignore_Protected_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + PersonForXml p = d.Deserialize(response); Assert.Null(p.IgnoreProxy); } @@ -112,10 +115,10 @@ public void Ignore_Protected_Property_That_Exists_In_Data() [Test] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + PersonForXml p = d.Deserialize(response); Assert.Null(p.ReadOnlyProxy); } @@ -123,10 +126,10 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() [Test] public void Can_Deserialize_Names_With_Underscores_With_Namespace() { - var doc = CreateUnderscoresXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var p = d.Deserialize(response); + string doc = CreateUnderscoresXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -150,10 +153,10 @@ public void Can_Deserialize_Names_With_Underscores_With_Namespace() [Test] public void Can_Deserialize_List_Of_Primitives_With_Namespace() { - var doc = CreateListOfPrimitivesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer { Namespace = "http://restsharp.org" }; - var a = d.Deserialize>(response); + string doc = CreateListOfPrimitivesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer { Namespace = "http://restsharp.org" }; + List a = d.Deserialize>(response); Assert.AreEqual(2, a.Count); Assert.AreEqual("first", a[0].Value); @@ -162,9 +165,9 @@ public void Can_Deserialize_List_Of_Primitives_With_Namespace() private static string CreateListOfPrimitivesXml() { - var doc = new XDocument(); - var ns = XNamespace.Get("http://restsharp.org"); - var root = new XElement(ns + "artists"); + XDocument doc = new XDocument(); + XNamespace ns = XNamespace.Get("http://restsharp.org"); + XElement root = new XElement(ns + "artists"); root.Add(new XElement(ns + "artist", "first")); root.Add(new XElement(ns + "artist", "second")); @@ -175,9 +178,9 @@ private static string CreateListOfPrimitivesXml() private static string CreateUnderscoresXml() { - var doc = new XDocument(); - var ns = XNamespace.Get("http://restsharp.org"); - var root = new XElement(ns + "Person"); + XDocument doc = new XDocument(); + XNamespace ns = XNamespace.Get("http://restsharp.org"); + XElement root = new XElement(ns + "Person"); root.Add(new XElement(ns + "Name", "John Sheehan")); root.Add(new XElement(ns + "Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -194,7 +197,7 @@ private static string CreateUnderscoresXml() new XElement(ns + "Name", "The Fonz"), new XAttribute(ns + "Since", 1952))); - var friends = new XElement(ns + "Friends"); + XElement friends = new XElement(ns + "Friends"); for (int i = 0; i < 10; i++) { @@ -205,7 +208,7 @@ private static string CreateUnderscoresXml() root.Add(friends); - var foes = new XElement(ns + "Foes"); + XElement foes = new XElement(ns + "Foes"); foes.Add(new XAttribute(ns + "Team", "Yankees")); @@ -222,9 +225,9 @@ private static string CreateUnderscoresXml() private static string CreateElementsXml() { - var doc = new XDocument(); - var ns = XNamespace.Get("http://restsharp.org"); - var root = new XElement(ns + "Person"); + XDocument doc = new XDocument(); + XNamespace ns = XNamespace.Get("http://restsharp.org"); + XElement root = new XElement(ns + "Person"); root.Add(new XElement(ns + "Name", "John Sheehan")); root.Add(new XElement(ns + "StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -241,7 +244,7 @@ private static string CreateElementsXml() new XElement(ns + "Name", "The Fonz"), new XElement(ns + "Since", 1952))); - var friends = new XElement(ns + "Friends"); + XElement friends = new XElement(ns + "Friends"); for (int i = 0; i < 10; i++) { @@ -255,14 +258,15 @@ private static string CreateElementsXml() new XElement(ns + "Name", "Goldfinger"))); doc.Add(root); + return doc.ToString(); } private static string CreateAttributesXml() { - var doc = new XDocument(); - var ns = XNamespace.Get("http://restsharp.org"); - var root = new XElement(ns + "Person"); + XDocument doc = new XDocument(); + XNamespace ns = XNamespace.Get("http://restsharp.org"); + XElement root = new XElement(ns + "Person"); root.Add(new XAttribute(ns + "Name", "John Sheehan")); root.Add(new XAttribute(ns + "StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); diff --git a/RestSharp.Tests/NuSpecUpdateTask.cs b/RestSharp.Tests/NuSpecUpdateTask.cs index 61aaebe35..d9dfd3578 100644 --- a/RestSharp.Tests/NuSpecUpdateTask.cs +++ b/RestSharp.Tests/NuSpecUpdateTask.cs @@ -34,7 +34,8 @@ public class WhenSpecFileNotSpecified [Test] public void ReturnsFalse() { - var task = new Build.NuSpecUpdateTask(); + Build.NuSpecUpdateTask task = new Build.NuSpecUpdateTask(); + Assert.False(task.Execute()); } } @@ -47,11 +48,11 @@ protected override void Setup() { } [Test] public void PullsVersionAttributeInstead() { - var task = new Build.NuSpecUpdateTask - { - SpecFile = FileName, - SourceAssemblyFile = "RestSharp.Tests.dll" - }; + Build.NuSpecUpdateTask task = new Build.NuSpecUpdateTask + { + SpecFile = FileName, + SourceAssemblyFile = "RestSharp.Tests.dll" + }; task.Execute(); @@ -63,6 +64,7 @@ public void PullsVersionAttributeInstead() public class WhenSpecFileIsValid : BaseNuSpecUpdateTest { private readonly Build.NuSpecUpdateTask subject = new Build.NuSpecUpdateTask(); + private bool result; #if SIGNED @@ -70,9 +72,13 @@ public class WhenSpecFileIsValid : BaseNuSpecUpdateTest #else private const string EXPECTED_ID = "RestSharp"; #endif + private const string EXPECTED_DESCRIPTION = "Simple REST and HTTP API Client"; + private const string EXPECTED_AUTHORS = "John Sheehan, RestSharp Community"; + private const string EXPECTED_OWNERS = "John Sheehan, RestSharp Community"; + private readonly Regex expectedVersion = new Regex(@"^\d+\.\d+\.\d+(-\w+)?$", RegexOptions.Compiled); protected override void Setup() @@ -115,7 +121,7 @@ public void PullsAuthorsFromAssemblyInfo() [Test] public void UpdatesSpecFile() { - var doc = XDocument.Load(ComputedFileName); + XDocument doc = XDocument.Load(ComputedFileName); Assert.AreEqual(EXPECTED_ID, doc.Descendants("id").First().Value); Assert.AreEqual(EXPECTED_DESCRIPTION, doc.Descendants("description").First().Value); diff --git a/RestSharp.Tests/OAuthTests.cs b/RestSharp.Tests/OAuthTests.cs index d64f27f29..aea66b060 100644 --- a/RestSharp.Tests/OAuthTests.cs +++ b/RestSharp.Tests/OAuthTests.cs @@ -4,7 +4,6 @@ using RestSharp.Authenticators.OAuth; using RestSharp.Authenticators.OAuth.Extensions; - namespace RestSharp.Tests { [TestFixture] @@ -28,7 +27,8 @@ public OAuthTests() [TestCase("\x00\x01\a\b\f\n\r\t\v", @"%00%01%07%08%0C%0A%0D%09%0B")] public void UrlStrictEncode_Encodes_Correctly(string value, string expected) { - var actual = OAuthTools.UrlEncodeStrict(value); + string actual = OAuthTools.UrlEncodeStrict(value); + Assert.AreEqual(expected, actual); } @@ -38,7 +38,8 @@ public void UrlStrictEncode_Encodes_Correctly(string value, string expected) [TestCase("\r\n\t", "%0D%0A%09")] public void PercentEncode_Encodes_Correctly(string value, string expected) { - var actual = value.PercentEncode(); + string actual = value.PercentEncode(); + Assert.AreEqual(expected, actual); } } diff --git a/RestSharp.Tests/Properties/AssemblyInfo.cs b/RestSharp.Tests/Properties/AssemblyInfo.cs index 0dcc7f28d..4627fbf82 100644 --- a/RestSharp.Tests/Properties/AssemblyInfo.cs +++ b/RestSharp.Tests/Properties/AssemblyInfo.cs @@ -1,10 +1,10 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("RestSharp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -17,9 +17,11 @@ // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. + [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("82c9d878-3d67-40fe-ac6b-6842605a04be")] // Version information for an assembly consists of the following four values: @@ -32,5 +34,6 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] + [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/RestSharp.Tests/RestRequestTests.cs b/RestSharp.Tests/RestRequestTests.cs index 71eff1182..bce7489f3 100644 --- a/RestSharp.Tests/RestRequestTests.cs +++ b/RestSharp.Tests/RestRequestTests.cs @@ -16,15 +16,16 @@ public RestRequestTests() [Test] public void Can_Add_Object_With_IntegerArray_property() { - var request = new RestRequest(); + RestRequest request = new RestRequest(); + request.AddObject(new { Items = new [] { 2, 3, 4 } }); } [Test] public void Cannot_Set_Empty_Host_Header() { - var request = new RestRequest(); - var exception = Assert.Throws(() => request.AddHeader("Host", string.Empty)); + RestRequest request = new RestRequest(); + ArgumentException exception = Assert.Throws(() => request.AddHeader("Host", string.Empty)); Assert.AreEqual("value", exception.ParamName); } @@ -45,8 +46,8 @@ public void Cannot_Set_Empty_Host_Header() [TestCase("foo:bar:baz")] public void Cannot_Set_Invalid_Host_Header(string value) { - var request = new RestRequest(); - var exception = Assert.Throws(() => request.AddHeader("Host", value)); + RestRequest request = new RestRequest(); + ArgumentException exception = Assert.Throws(() => request.AddHeader("Host", value)); Assert.AreEqual("value", exception.ParamName); } @@ -66,7 +67,7 @@ public void Cannot_Set_Invalid_Host_Header(string value) [TestCase("multi--hyphens")] public void Can_Set_Valid_Host_Header(string value) { - var request = new RestRequest(); + RestRequest request = new RestRequest(); Assert.DoesNotThrow(() => request.AddHeader("Host", value)); } diff --git a/RestSharp.Tests/RestSharp.Tests.Signed.csproj b/RestSharp.Tests/RestSharp.Tests.Signed.csproj index 578d9f9e6..84304cb35 100644 --- a/RestSharp.Tests/RestSharp.Tests.Signed.csproj +++ b/RestSharp.Tests/RestSharp.Tests.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 9.0.30729 2.0 - {1464E4AC-18BB-4F23-8A0B-68196F9E1871} + {25D4AAB0-B538-4F13-AB0E-96247307858B} Library Properties RestSharp.Tests @@ -127,6 +127,9 @@ Always + + Always + Always @@ -225,12 +228,12 @@ - {ccc30138-3d68-44d8-af1a-d22f769ee8dc} + {60cf35b5-abe3-47e4-ba0c-0abaf1618475} RestSharp.Build.Signed - - {2ececfbf-5f3e-40ee-a963-72336dc7abe2} - RestSharp.Signed + + {3190e0dc-674c-4c41-a7a3-bd2f406963b0} + RestSharp.Net35.Signed diff --git a/RestSharp.Tests/RestSharp.Tests.csproj b/RestSharp.Tests/RestSharp.Tests.csproj index 75f9d8ef9..3a675257c 100644 --- a/RestSharp.Tests/RestSharp.Tests.csproj +++ b/RestSharp.Tests/RestSharp.Tests.csproj @@ -102,7 +102,7 @@ - + @@ -120,6 +120,9 @@ Always + + Always + Always @@ -226,9 +229,9 @@ {CCC30138-3D68-44D8-AF1A-D22F769EE8DC} RestSharp.Build - - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2} - RestSharp + + {2ececfbf-5f3e-40ee-a963-72336dc7abe2} + RestSharp.Net35 diff --git a/RestSharp.Tests/SampleClasses/BooleanTest.cs b/RestSharp.Tests/SampleClasses/BooleanTest.cs index fc6621ef2..6ba70e851 100644 --- a/RestSharp.Tests/SampleClasses/BooleanTest.cs +++ b/RestSharp.Tests/SampleClasses/BooleanTest.cs @@ -1,5 +1,4 @@ - -namespace RestSharp.Tests.SampleClasses +namespace RestSharp.Tests.SampleClasses { public class BooleanTest { diff --git a/RestSharp.Tests/SampleClasses/EmployeeTracker.cs b/RestSharp.Tests/SampleClasses/EmployeeTracker.cs index 84fcf7e19..02bec0162 100644 --- a/RestSharp.Tests/SampleClasses/EmployeeTracker.cs +++ b/RestSharp.Tests/SampleClasses/EmployeeTracker.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace RestSharp.Tests.SampleClasses { @@ -9,26 +8,26 @@ public class EmployeeTracker /// Key: Employee name. /// Value: Messages sent to employee. /// - public Dictionary> EmployeesMail { get; set; } + public Dictionary> EmployeesMail { get; set; } /// /// Key: Employee name. /// Value: Hours worked this each week. /// - public Dictionary>> EmployeesTime { get; set; } + public Dictionary>> EmployeesTime { get; set; } /// /// Key: Employee name. /// Value: Payments made to employee /// - public Dictionary> EmployeesPay { get; set; } + public Dictionary> EmployeesPay { get; set; } } public class Payment { public PaymentType Type { get; set; } - public Int32 Amount { get; set; } + public int Amount { get; set; } } public enum PaymentType diff --git a/RestSharp.Tests/SampleClasses/EnumTest.cs b/RestSharp.Tests/SampleClasses/EnumTest.cs index b3d821f71..50ce9307b 100644 --- a/RestSharp.Tests/SampleClasses/EnumTest.cs +++ b/RestSharp.Tests/SampleClasses/EnumTest.cs @@ -1,4 +1,5 @@ -namespace RestSharp.Tests.SampleClasses + +namespace RestSharp.Tests.SampleClasses { public enum ByteEnum : byte { @@ -24,7 +25,7 @@ public enum UShortEnum : ushort EnumMax = 65535 } - public enum IntEnum : int + public enum IntEnum { EnumMin = -2147483648, EnumMax = 2147483647 diff --git a/RestSharp.Tests/SampleClasses/Goodreads.cs b/RestSharp.Tests/SampleClasses/Goodreads.cs index 796a4ad6c..7f0109d0a 100644 --- a/RestSharp.Tests/SampleClasses/Goodreads.cs +++ b/RestSharp.Tests/SampleClasses/Goodreads.cs @@ -5,14 +5,18 @@ namespace RestSharp.Tests.SampleClasses public class GoodReadsReviewCollection { public int Start { get; set; } + public int End { get; set; } + public int Total { get; set; } + public List Reviews { get; set; } } public class GoodReadsReview { public string Id { get; set; } + public GoodReadsBook Book { get; set; } } diff --git a/RestSharp.Tests/SampleClasses/ListSamples.cs b/RestSharp.Tests/SampleClasses/ListSamples.cs index 2417cc54b..888f210da 100644 --- a/RestSharp.Tests/SampleClasses/ListSamples.cs +++ b/RestSharp.Tests/SampleClasses/ListSamples.cs @@ -16,7 +16,6 @@ public class InlineListSample public List images { get; set; } public List Images { get; set; } - } public class NestedListSample @@ -36,6 +35,7 @@ public class EmptyListSample public class Image { public string Src { get; set; } + public string Value { get; set; } } diff --git a/RestSharp.Tests/SampleClasses/Oddball.cs b/RestSharp.Tests/SampleClasses/Oddball.cs index c2142bbd9..9fb272c75 100644 --- a/RestSharp.Tests/SampleClasses/Oddball.cs +++ b/RestSharp.Tests/SampleClasses/Oddball.cs @@ -1,5 +1,4 @@ - -namespace RestSharp.Tests.SampleClasses +namespace RestSharp.Tests.SampleClasses { [Deserializers.DeserializeAs(Name = "oddballRootName")] public class Oddball diff --git a/RestSharp.Tests/SampleClasses/SOUser.cs b/RestSharp.Tests/SampleClasses/SOUser.cs index e57c86eec..c2b490cc7 100644 --- a/RestSharp.Tests/SampleClasses/SOUser.cs +++ b/RestSharp.Tests/SampleClasses/SOUser.cs @@ -1,7 +1,6 @@ - -namespace RestSharp.Tests.SampleClasses +namespace RestSharp.Tests.SampleClasses { - public class SOUser + public class SoUser { public int Id { get; set; } diff --git a/RestSharp.Tests/SampleClasses/Struct.cs b/RestSharp.Tests/SampleClasses/Struct.cs index feb401542..e09f74817 100644 --- a/RestSharp.Tests/SampleClasses/Struct.cs +++ b/RestSharp.Tests/SampleClasses/Struct.cs @@ -1,5 +1,4 @@ - -namespace RestSharp.Tests.SampleClasses +namespace RestSharp.Tests.SampleClasses { public struct SimpleStruct { diff --git a/RestSharp.Tests/SampleClasses/misc.cs b/RestSharp.Tests/SampleClasses/misc.cs index e90cfe626..80dc23671 100644 --- a/RestSharp.Tests/SampleClasses/misc.cs +++ b/RestSharp.Tests/SampleClasses/misc.cs @@ -1,4 +1,5 @@ #region Licensed + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,13 +13,14 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Collections.Generic; using RestSharp.Serializers; -namespace RestSharp.Tests +namespace RestSharp.Tests.SampleClasses { public class PersonForXml { @@ -40,11 +42,20 @@ public class PersonForXml protected string Ignore { get; set; } - public string IgnoreProxy { get { return Ignore; } } + public string IgnoreProxy + { + get { return this.Ignore; } + } - protected string ReadOnly { get { return null; } } + protected string ReadOnly + { + get { return null; } + } - public string ReadOnlyProxy { get { return ReadOnly; } } + public string ReadOnlyProxy + { + get { return this.ReadOnly; } + } public FoeList Foes { get; set; } @@ -66,7 +77,6 @@ public class Band { public string Name { get; set; } } - } public class IncomingInvoice @@ -102,11 +112,20 @@ public class PersonForJson protected string Ignore { get; set; } - public string IgnoreProxy { get { return Ignore; } } + public string IgnoreProxy + { + get { return this.Ignore; } + } - protected string ReadOnly { get { return null; } } + protected string ReadOnly + { + get { return null; } + } - public string ReadOnlyProxy { get { return ReadOnly; } } + public string ReadOnlyProxy + { + get { return this.ReadOnly; } + } public Dictionary Foes { get; set; } @@ -118,14 +137,18 @@ public class PersonForJson public enum Order { First, + Second, + Third } public enum Disposition { Friendly, + SoSo, + SteerVeryClear } diff --git a/RestSharp.Tests/SampleClasses/nullables.cs b/RestSharp.Tests/SampleClasses/nullables.cs index 4a42de607..4865a56d9 100644 --- a/RestSharp.Tests/SampleClasses/nullables.cs +++ b/RestSharp.Tests/SampleClasses/nullables.cs @@ -1,6 +1,6 @@ using System; -namespace RestSharp.Tests +namespace RestSharp.Tests.SampleClasses { public class NullableValues { diff --git a/RestSharp.Tests/SampleData/deserialize_as_list.xml b/RestSharp.Tests/SampleData/deserialize_as_list.xml new file mode 100644 index 000000000..3509f55fb --- /dev/null +++ b/RestSharp.Tests/SampleData/deserialize_as_list.xml @@ -0,0 +1,17 @@ + + + + + 1 + Jackson + oddball + + + + + 1 + Jackson + evenball + + + \ No newline at end of file diff --git a/RestSharp.Tests/SerializerTests.cs b/RestSharp.Tests/SerializerTests.cs index ac5cfcae9..f872e7910 100644 --- a/RestSharp.Tests/SerializerTests.cs +++ b/RestSharp.Tests/SerializerTests.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -21,6 +23,7 @@ using System.Xml.Linq; using NUnit.Framework; using RestSharp.Serializers; +using RestSharp.Tests.SampleClasses; namespace RestSharp.Tests { @@ -36,16 +39,15 @@ public SerializerTests() [Test] public void Serializes_Properties_In_Specified_Order() { - var ordered = new OrderedProperties - { - Name = "Name", - Age = 99, - StartDate = new DateTime(2010, 1, 1) - }; - - var xml = new XmlSerializer(); - var doc = xml.Serialize(ordered); - var expected = GetSortedPropsXDoc(); + OrderedProperties ordered = new OrderedProperties + { + Name = "Name", + Age = 99, + StartDate = new DateTime(2010, 1, 1) + }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(ordered); + XDocument expected = GetSortedPropsXDoc(); Assert.AreEqual(expected.ToString(), doc); } @@ -53,22 +55,22 @@ public void Serializes_Properties_In_Specified_Order() [Test] public void Can_serialize_simple_POCO() { - var poco = new Person - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - Items = new List - { - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } - } - }; - var xml = new XmlSerializer(); - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDoc(); + Person poco = new Person + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + Items = new List + { + new Item { Name = "One", Value = 1 }, + new Item { Name = "Two", Value = 2 }, + new Item { Name = "Three", Value = 3 } + } + }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDoc(); Assert.AreEqual(expected.ToString(), doc); } @@ -76,11 +78,11 @@ public void Can_serialize_simple_POCO() [Test] public void Can_serialize_Enum() { - var enumClass = new ClassWithEnum { Color = Color.Red }; - var xml = new XmlSerializer(); - var doc = xml.Serialize(enumClass); - var expected = new XDocument(); - var root = new XElement("ClassWithEnum"); + ClassWithEnum enumClass = new ClassWithEnum { Color = Color.Red }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(enumClass); + XDocument expected = new XDocument(); + XElement root = new XElement("ClassWithEnum"); root.Add(new XElement("Color", "Red")); expected.Add(root); @@ -91,16 +93,16 @@ public void Can_serialize_Enum() [Test] public void Can_serialize_simple_POCO_With_DateFormat_Specified() { - var poco = new Person - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) - }; - var xml = new XmlSerializer { DateFormat = DateFormat.Iso8601 }; - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDocWithIsoDate(); + Person poco = new Person + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + }; + XmlSerializer xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDocWithIsoDate(); Assert.AreEqual(expected.ToString(), doc); } @@ -108,17 +110,17 @@ public void Can_serialize_simple_POCO_With_DateFormat_Specified() [Test] public void Can_serialize_simple_POCO_With_XmlFormat_Specified() { - var poco = new Person - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - IsCool = false - }; - var xml = new XmlSerializer { DateFormat = DateFormat.Iso8601 }; - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDocWithXmlProperty(); + Person poco = new Person + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + IsCool = false + }; + XmlSerializer xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDocWithXmlProperty(); Assert.AreEqual(expected.ToString(), doc); } @@ -126,16 +128,16 @@ public void Can_serialize_simple_POCO_With_XmlFormat_Specified() [Test] public void Can_serialize_simple_POCO_With_Different_Root_Element() { - var poco = new Person - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) - }; - var xml = new XmlSerializer {RootElement = "Result"}; - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDocWithRoot(); + Person poco = new Person + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + }; + XmlSerializer xml = new XmlSerializer { RootElement = "Result" }; + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDocWithRoot(); Assert.AreEqual(expected.ToString(), doc); } @@ -143,16 +145,16 @@ public void Can_serialize_simple_POCO_With_Different_Root_Element() [Test] public void Can_serialize_simple_POCO_With_Attribute_Options_Defined() { - var poco = new WackyPerson - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) - }; - var xml = new XmlSerializer(); - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDocWackyNames(); + WackyPerson poco = new WackyPerson + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDocWackyNames(); Assert.AreEqual(expected.ToString(), doc); } @@ -160,27 +162,27 @@ public void Can_serialize_simple_POCO_With_Attribute_Options_Defined() [Test] public void Can_serialize_simple_POCO_With_Attribute_Options_Defined_And_Property_Containing_IList_Elements() { - var poco = new WackyPerson - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - ContactData = new ContactData - { - EmailAddresses = new List - { - new EmailAddress - { - Address = "test@test.com", - Location = "Work" - } - } - } - }; - var xml = new XmlSerializer(); - var doc = xml.Serialize(poco); - var expected = GetSimplePocoXDocWackyNamesWithIListProperty(); + WackyPerson poco = new WackyPerson + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + ContactData = new ContactData + { + EmailAddresses = new List + { + new EmailAddress + { + Address = "test@test.com", + Location = "Work" + } + } + } + }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(poco); + XDocument expected = GetSimplePocoXDocWackyNamesWithIListProperty(); Assert.AreEqual(expected.ToString(), doc); } @@ -188,38 +190,38 @@ public void Can_serialize_simple_POCO_With_Attribute_Options_Defined_And_Propert [Test] public void Can_serialize_a_list_which_is_the_root_element() { - var pocoList = new PersonList - { - new Person - { - Name = "Foo", - Age = 50, - Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - Items = new List - { - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } - } - }, - new Person - { - Name = "Bar", - Age = 23, - Price = 23.23m, - StartDate = new DateTime(2009, 12, 23, 10, 23, 23), - Items = new List - { - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } - } - } - }; - var xml = new XmlSerializer(); - var doc = xml.Serialize(pocoList); - var expected = GetPeopleXDoc(CultureInfo.InvariantCulture); + PersonList pocoList = new PersonList + { + new Person + { + Name = "Foo", + Age = 50, + Price = 19.95m, + StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + Items = new List + { + new Item { Name = "One", Value = 1 }, + new Item { Name = "Two", Value = 2 }, + new Item { Name = "Three", Value = 3 } + } + }, + new Person + { + Name = "Bar", + Age = 23, + Price = 23.23m, + StartDate = new DateTime(2009, 12, 23, 10, 23, 23), + Items = new List + { + new Item { Name = "One", Value = 1 }, + new Item { Name = "Two", Value = 2 }, + new Item { Name = "Three", Value = 3 } + } + } + }; + XmlSerializer xml = new XmlSerializer(); + string doc = xml.Serialize(pocoList); + XDocument expected = GetPeopleXDoc(CultureInfo.InvariantCulture); Assert.AreEqual(expected.ToString(), doc); } @@ -249,7 +251,9 @@ private class Item private enum Color { Red, + Blue, + Green } @@ -302,15 +306,15 @@ private class EmailAddress private static XDocument GetSimplePocoXDoc() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "Foo"), new XElement("Age", 50), new XElement("Price", 19.95m), new XElement("StartDate", new DateTime(2009, 12, 18, 10, 2, 23).ToString(CultureInfo.InvariantCulture))); - var items = new XElement("Items"); + XElement items = new XElement("Items"); items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1))); items.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2))); @@ -324,8 +328,8 @@ private static XDocument GetSimplePocoXDoc() private static XDocument GetSimplePocoXDocWithIsoDate() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "Foo"), new XElement("Age", 50), @@ -339,8 +343,8 @@ private static XDocument GetSimplePocoXDocWithIsoDate() private static XDocument GetSimplePocoXDocWithXmlProperty() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "Foo"), new XElement("Age", 50), @@ -355,9 +359,9 @@ private static XDocument GetSimplePocoXDocWithXmlProperty() private static XDocument GetSimplePocoXDocWithRoot() { - var doc = new XDocument(); - var root = new XElement("Result"); - var start = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Result"); + XElement start = new XElement("Person"); start.Add(new XElement("Name", "Foo"), new XElement("Age", 50), @@ -372,8 +376,8 @@ private static XDocument GetSimplePocoXDocWithRoot() private static XDocument GetSimplePocoXDocWackyNames() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XAttribute("WackyName", "Foo"), new XElement("Age", 50), @@ -387,8 +391,8 @@ private static XDocument GetSimplePocoXDocWackyNames() private static XDocument GetSimplePocoXDocWackyNamesWithIListProperty() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XAttribute("WackyName", "Foo"), new XElement("Age", 50), @@ -408,8 +412,8 @@ private static XDocument GetSimplePocoXDocWackyNamesWithIListProperty() private static XDocument GetSortedPropsXDoc() { - var doc = new XDocument(); - var root = new XElement("OrderedProperties"); + XDocument doc = new XDocument(); + XElement root = new XElement("OrderedProperties"); root.Add(new XElement("StartDate", new DateTime(2010, 1, 1).ToString(CultureInfo.InvariantCulture))); root.Add(new XElement("Name", "Name")); @@ -422,10 +426,10 @@ private static XDocument GetSortedPropsXDoc() private static XDocument GetPeopleXDoc(IFormatProvider culture) { - var doc = new XDocument(); - var root = new XElement("People"); - var element = new XElement("Person"); - var items = new XElement("Items"); + XDocument doc = new XDocument(); + XElement root = new XElement("People"); + XElement element = new XElement("Person"); + XElement items = new XElement("Items"); items.Add(new XElement("Item", new XElement("Name", "One"), new XElement("Value", 1))); items.Add(new XElement("Item", new XElement("Name", "Two"), new XElement("Value", 2))); diff --git a/RestSharp.Tests/UrlBuilderTests.cs b/RestSharp.Tests/UrlBuilderTests.cs index 063bea48f..9be921c28 100644 --- a/RestSharp.Tests/UrlBuilderTests.cs +++ b/RestSharp.Tests/UrlBuilderTests.cs @@ -12,13 +12,13 @@ public class UrlBuilderTests [Test] public void Should_not_duplicate_question_mark() { - var request = new RestRequest(); + RestRequest request = new RestRequest(); request.AddParameter("param2", "value2"); - var client = new RestClient("http://example.com/resource?param1=value1"); - var expected = new Uri("http://example.com/resource?param1=value1¶m2=value2"); - var output = client.BuildUri(request); + RestClient client = new RestClient("http://example.com/resource?param1=value1"); + Uri expected = new Uri("http://example.com/resource?param1=value1¶m2=value2"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -26,10 +26,10 @@ public void Should_not_duplicate_question_mark() [Test] public void GET_with_leading_slash() { - var request = new RestRequest("/resource"); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest("/resource"); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -37,10 +37,10 @@ public void GET_with_leading_slash() [Test] public void POST_with_leading_slash() { - var request = new RestRequest("/resource", Method.POST); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest("/resource", Method.POST); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -48,13 +48,13 @@ public void POST_with_leading_slash() [Test] public void GET_with_leading_slash_and_baseurl_trailing_slash() { - var request = new RestRequest("/resource"); + RestRequest request = new RestRequest("/resource"); request.AddParameter("foo", "bar"); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource?foo=bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource?foo=bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -62,13 +62,13 @@ public void GET_with_leading_slash_and_baseurl_trailing_slash() [Test] public void GET_wth_trailing_slash_and_query_parameters() { - var request = new RestRequest("/resource/"); - var client = new RestClient("http://example.com"); + RestRequest request = new RestRequest("/resource/"); + RestClient client = new RestClient("http://example.com"); request.AddParameter("foo", "bar"); - var expected = new Uri("http://example.com/resource/?foo=bar"); - var output = client.BuildUri(request); + Uri expected = new Uri("http://example.com/resource/?foo=bar"); + Uri output = client.BuildUri(request); client.Execute(request); @@ -78,10 +78,10 @@ public void GET_wth_trailing_slash_and_query_parameters() [Test] public void POST_with_leading_slash_and_baseurl_trailing_slash() { - var request = new RestRequest("/resource", Method.POST); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest("/resource", Method.POST); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -89,10 +89,10 @@ public void POST_with_leading_slash_and_baseurl_trailing_slash() [Test] public void GET_with_resource_containing_slashes() { - var request = new RestRequest("resource/foo"); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource/foo"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest("resource/foo"); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource/foo"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -100,10 +100,10 @@ public void GET_with_resource_containing_slashes() [Test] public void POST_with_resource_containing_slashes() { - var request = new RestRequest("resource/foo", Method.POST); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource/foo"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest("resource/foo", Method.POST); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource/foo"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -111,13 +111,13 @@ public void POST_with_resource_containing_slashes() [Test] public void GET_with_resource_containing_tokens() { - var request = new RestRequest("resource/{foo}"); + RestRequest request = new RestRequest("resource/{foo}"); request.AddUrlSegment("foo", "bar"); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource/bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource/bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -125,12 +125,12 @@ public void GET_with_resource_containing_tokens() [Test] public void GET_with_resource_containing_null_token() { - var request = new RestRequest("/resource/{foo}", Method.GET); + RestRequest request = new RestRequest("/resource/{foo}", Method.GET); request.AddUrlSegment("foo", null); - var client = new RestClient("http://example.com/api/1.0"); - var exception = Assert.Throws(() => client.BuildUri(request)); + RestClient client = new RestClient("http://example.com/api/1.0"); + ArgumentException exception = Assert.Throws(() => client.BuildUri(request)); Assert.IsNotNull(exception); Assert.IsNotNullOrEmpty(exception.Message); @@ -140,13 +140,13 @@ public void GET_with_resource_containing_null_token() [Test] public void POST_with_resource_containing_tokens() { - var request = new RestRequest("resource/{foo}", Method.POST); + RestRequest request = new RestRequest("resource/{foo}", Method.POST); request.AddUrlSegment("foo", "bar"); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/resource/bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/resource/bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -154,10 +154,10 @@ public void POST_with_resource_containing_tokens() [Test] public void GET_with_empty_request() { - var request = new RestRequest(); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest(); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -165,10 +165,10 @@ public void GET_with_empty_request() [Test] public void GET_with_empty_request_and_bare_hostname() { - var request = new RestRequest(); - var client = new RestClient(new Uri("http://example.com")); - var expected = new Uri("http://example.com/"); - var output = client.BuildUri(request); + RestRequest request = new RestRequest(); + RestClient client = new RestClient(new Uri("http://example.com")); + Uri expected = new Uri("http://example.com/"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -176,13 +176,13 @@ public void GET_with_empty_request_and_bare_hostname() [Test] public void POST_with_querystring_containing_tokens() { - var request = new RestRequest("resource", Method.POST); + RestRequest request = new RestRequest("resource", Method.POST); request.AddParameter("foo", "bar", ParameterType.QueryString); - var client = new RestClient("http://example.com"); - var expected = new Uri("http://example.com/resource?foo=bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient("http://example.com"); + Uri expected = new Uri("http://example.com/resource?foo=bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -190,16 +190,16 @@ public void POST_with_querystring_containing_tokens() [Test] public void GET_with_multiple_instances_of_same_key() { - var request = new RestRequest("v1/people/~/network/updates", Method.GET); + RestRequest request = new RestRequest("v1/people/~/network/updates", Method.GET); request.AddParameter("type", "STAT"); request.AddParameter("type", "PICT"); request.AddParameter("count", "50"); request.AddParameter("start", "50"); - var client = new RestClient("http://api.linkedin.com"); - var expected = new Uri("http://api.linkedin.com/v1/people/~/network/updates?type=STAT&type=PICT&count=50&start=50"); - var output = client.BuildUri(request); + RestClient client = new RestClient("http://api.linkedin.com"); + Uri expected = new Uri("http://api.linkedin.com/v1/people/~/network/updates?type=STAT&type=PICT&count=50&start=50"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -207,13 +207,13 @@ public void GET_with_multiple_instances_of_same_key() [Test] public void GET_with_Uri_containing_tokens() { - var request = new RestRequest(); + RestRequest request = new RestRequest(); request.AddUrlSegment("foo", "bar"); - var client = new RestClient(new Uri("http://example.com/{foo}")); - var expected = new Uri("http://example.com/bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient(new Uri("http://example.com/{foo}")); + Uri expected = new Uri("http://example.com/bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -221,13 +221,13 @@ public void GET_with_Uri_containing_tokens() [Test] public void GET_with_Url_string_containing_tokens() { - var request = new RestRequest(); + RestRequest request = new RestRequest(); request.AddUrlSegment("foo", "bar"); - var client = new RestClient("http://example.com/{foo}"); - var expected = new Uri("http://example.com/bar"); - var output = client.BuildUri(request); + RestClient client = new RestClient("http://example.com/{foo}"); + Uri expected = new Uri("http://example.com/bar"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -235,14 +235,14 @@ public void GET_with_Url_string_containing_tokens() [Test] public void GET_with_Uri_and_resource_containing_tokens() { - var request = new RestRequest("resource/{baz}"); + RestRequest request = new RestRequest("resource/{baz}"); request.AddUrlSegment("foo", "bar"); request.AddUrlSegment("baz", "bat"); - var client = new RestClient(new Uri("http://example.com/{foo}")); - var expected = new Uri("http://example.com/bar/resource/bat"); - var output = client.BuildUri(request); + RestClient client = new RestClient(new Uri("http://example.com/{foo}")); + Uri expected = new Uri("http://example.com/bar/resource/bat"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } @@ -250,14 +250,14 @@ public void GET_with_Uri_and_resource_containing_tokens() [Test] public void GET_with_Url_string_and_resource_containing_tokens() { - var request = new RestRequest("resource/{baz}"); + RestRequest request = new RestRequest("resource/{baz}"); request.AddUrlSegment("foo", "bar"); request.AddUrlSegment("baz", "bat"); - var client = new RestClient("http://example.com/{foo}"); - var expected = new Uri("http://example.com/bar/resource/bat"); - var output = client.BuildUri(request); + RestClient client = new RestClient("http://example.com/{foo}"); + Uri expected = new Uri("http://example.com/bar/resource/bat"); + Uri output = client.BuildUri(request); Assert.AreEqual(expected, output); } diff --git a/RestSharp.Tests/XmlAttributeDeserializerTests.cs b/RestSharp.Tests/XmlAttributeDeserializerTests.cs index 90c2dd587..284fc2ce0 100644 --- a/RestSharp.Tests/XmlAttributeDeserializerTests.cs +++ b/RestSharp.Tests/XmlAttributeDeserializerTests.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -23,12 +25,14 @@ using NUnit.Framework; using RestSharp.Deserializers; using RestSharp.Tests.SampleClasses; +using Event = RestSharp.Tests.SampleClasses.Lastfm.Event; namespace RestSharp.Tests { public class XmlAttributeDeserializerTests { private const string GUID_STRING = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5"; + private readonly string sampleDataPath = Path.Combine(Environment.CurrentDirectory, "SampleData"); private string PathFor(string sampleFile) @@ -39,10 +43,11 @@ private string PathFor(string sampleFile) [Test] public void Can_Deserialize_Lists_of_Simple_Types() { - var xmlpath = this.PathFor("xmllists.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("xmllists.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + SimpleTypesListSample output = xml.Deserialize( + new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Names); Assert.IsNotEmpty(output.Numbers); @@ -53,10 +58,10 @@ public void Can_Deserialize_Lists_of_Simple_Types() [Test] public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() { - var xmlpath = this.PathFor("ListWithAttributes.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer { RootElement = "Calls" }; - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("ListWithAttributes.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer { RootElement = "Calls" }; + TwilioCallList output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.AreEqual(3, output.NumPages); Assert.IsNotEmpty(output); @@ -66,10 +71,10 @@ public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() [Test] public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(4, output.Count); @@ -78,10 +83,10 @@ public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() [Test] public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(4, output.Count); @@ -90,10 +95,10 @@ public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() [Test] public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { - var xmlpath = this.PathFor("directlists.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("directlists.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(2, output.Count); @@ -102,10 +107,10 @@ public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Class_Name() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Images); Assert.AreEqual(4, output.Images.Count); @@ -114,10 +119,10 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Cl [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.images); Assert.AreEqual(4, output.images.Count); @@ -126,10 +131,10 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name_With_Additional_Property() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.AreEqual(4, output.Count); } @@ -137,10 +142,10 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class [Test] public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { - var xmlpath = this.PathFor("NestedListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("NestedListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Images); Assert.AreEqual(4, output.Images.Count); @@ -149,10 +154,10 @@ public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() [Test] public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { - var xmlpath = this.PathFor("NestedListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("NestedListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.images); Assert.AreEqual(4, output.images.Count); @@ -161,9 +166,9 @@ public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() [Test] public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { - var doc = CreateXmlWithEmptyNestedList(); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithEmptyNestedList(); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + EmptyListSample output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.images); Assert.NotNull(output.Images); @@ -174,9 +179,9 @@ public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() [Test] public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { - var doc = CreateXmlWithEmptyInlineList(); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithEmptyInlineList(); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + EmptyListSample output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.images); Assert.NotNull(output.Images); @@ -187,9 +192,9 @@ public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() [Test] public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { - var doc = CreateXmlWithNullValues(); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithNullValues(); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -199,10 +204,13 @@ public void Can_Deserialize_Empty_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_Elements_to_Nullable_Values() { - var culture = CultureInfo.InvariantCulture; - var doc = CreateXmlWithoutEmptyValues(culture); - var xml = new XmlAttributeDeserializer { Culture = culture }; - var output = xml.Deserialize(new RestResponse { Content = doc }); + CultureInfo culture = CultureInfo.InvariantCulture; + string doc = CreateXmlWithoutEmptyValues(culture); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer + { + Culture = culture + }; + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); @@ -215,13 +223,13 @@ public void Can_Deserialize_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_TimeSpan() { - var culture = CultureInfo.InvariantCulture; - var doc = new XDocument(culture); + CultureInfo culture = CultureInfo.InvariantCulture; + XDocument doc = new XDocument(culture); TimeSpan? nullTimespan = null; TimeSpan? nullValueTimeSpan = new TimeSpan(21, 30, 7); - var root = new XElement("Person"); + XElement root = new XElement("Person"); root.Add(new XElement("Tick", new TimeSpan(468006))); root.Add(new XElement("Millisecond", new TimeSpan(0, 0, 0, 0, 125))); @@ -233,9 +241,9 @@ public void Can_Deserialize_TimeSpan() doc.Add(root); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer { Culture = culture }; - var payload = d.Deserialize(response); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer { Culture = culture }; + TimeSpanTestStructure payload = d.Deserialize(response); Assert.AreEqual(new TimeSpan(468006), payload.Tick); Assert.AreEqual(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond); @@ -250,44 +258,46 @@ public void Can_Deserialize_TimeSpan() [Test] public void Can_Deserialize_Custom_Formatted_Date() { - var culture = CultureInfo.InvariantCulture; - var format = "dd yyyy MMM, hh:mm ss tt zzz"; - var date = new DateTime(2010, 2, 8, 11, 11, 11); - var doc = new XDocument(); - var root = new XElement("Person"); + CultureInfo culture = CultureInfo.InvariantCulture; + const string format = "dd yyyy MMM, hh:mm ss tt zzz"; + DateTime date = new DateTime(2010, 2, 8, 11, 11, 11); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("StartDate", date.ToString(format, culture))); doc.Add(root); - var xml = new XmlAttributeDeserializer - { - DateFormat = format, - Culture = culture - }; - var response = new RestResponse { Content = doc.ToString() }; - var output = xml.Deserialize(response); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer + { + DateFormat = format, + Culture = culture + }; + RestResponse response = new RestResponse { Content = doc.ToString() }; + PersonForXml output = xml.Deserialize(response); Assert.AreEqual(date, output.StartDate); } + [Test] public void Can_Deserialize_Nested_Class() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.NotNull(p.FavoriteBand); Assert.AreEqual("Goldfinger", p.FavoriteBand.Name); } + [Test] public void Can_Deserialize_Elements_On_Default_Root() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -311,10 +321,10 @@ public void Can_Deserialize_Elements_On_Default_Root() [Test] public void Can_Deserialize_Attributes_On_Default_Root() { - var doc = CreateAttributesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateAttributesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -333,10 +343,10 @@ public void Can_Deserialize_Attributes_On_Default_Root() [Test] public void Ignore_Protected_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.Null(p.IgnoreProxy); } @@ -344,10 +354,10 @@ public void Ignore_Protected_Property_That_Exists_In_Data() [Test] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.Null(p.ReadOnlyProxy); } @@ -355,10 +365,10 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() [Test] public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { - var doc = CreateUnderscoresXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateUnderscoresXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -382,10 +392,10 @@ public void Can_Deserialize_Names_With_Underscores_On_Default_Root() [Test] public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { - var doc = CreateDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -409,10 +419,10 @@ public void Can_Deserialize_Names_With_Dashes_On_Default_Root() [Test] public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Default_Root() { - var doc = CreateLowercaseUnderscoresXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateLowercaseUnderscoresXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -436,10 +446,10 @@ public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Defa [Test] public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { - var doc = CreateDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize(response); + string doc = CreateDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -463,25 +473,24 @@ public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() [Test] public void Can_Deserialize_Root_Elements_Without_Matching_Case_And_Dashes() { - var doc = CreateLowerCasedRootElementWithDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlAttributeDeserializer(); - var p = d.Deserialize>(response); + string doc = CreateLowerCasedRootElementWithDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + List p = d.Deserialize>(response); Assert.NotNull(p); Assert.AreEqual(1, p.Count); Assert.AreEqual(45, p[0].ConceptId); } - [Test] public void Can_Deserialize_Eventful_Xml() { - var xmlpath = this.PathFor("eventful.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("eventful.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + VenueSearch output = d.Deserialize(response); Assert.IsNotEmpty(output.venues); Assert.AreEqual(3, output.venues.Count); @@ -493,11 +502,11 @@ public void Can_Deserialize_Eventful_Xml() [Test] public void Can_Deserialize_Lastfm_Xml() { - var xmlpath = this.PathFor("Lastfm.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("Lastfm.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + Event output = d.Deserialize(response); //Assert.IsNotEmpty(output.artists); Assert.AreEqual("http://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008", output.url); @@ -507,11 +516,11 @@ public void Can_Deserialize_Lastfm_Xml() [Test] public void Can_Deserialize_Google_Weather_Xml() { - var xmlpath = this.PathFor("GoogleWeather.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("GoogleWeather.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + xml_api_reply output = d.Deserialize(response); Assert.IsNotEmpty(output.weather); Assert.AreEqual(4, output.weather.Count); @@ -521,11 +530,11 @@ public void Can_Deserialize_Google_Weather_Xml() [Test] public void Can_Deserialize_Google_Weather_Xml_WithDeserializeAs() { - var xmlpath = this.PathFor("GoogleWeather.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("GoogleWeather.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + GoogleWeatherApi output = d.Deserialize(response); Assert.IsNotEmpty(output.Weather); Assert.AreEqual(4, output.Weather.Count); @@ -535,11 +544,11 @@ public void Can_Deserialize_Google_Weather_Xml_WithDeserializeAs() [Test] public void Can_Deserialize_Boolean_From_Number() { - var xmlpath = this.PathFor("boolean_from_number.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("boolean_from_number.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + BooleanTest output = d.Deserialize(response); Assert.True(output.Value); } @@ -547,11 +556,11 @@ public void Can_Deserialize_Boolean_From_Number() [Test] public void Can_Deserialize_Boolean_From_String() { - var xmlpath = this.PathFor("boolean_from_string.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("boolean_from_string.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer(); + BooleanTest output = d.Deserialize(response); Assert.True(output.Value); } @@ -559,9 +568,9 @@ public void Can_Deserialize_Boolean_From_String() [Test] public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { - var doc = CreateXmlWithAttributesAndNullValues(); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithAttributesAndNullValues(); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -571,9 +580,9 @@ public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() [Test] public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Populated_Elements() { - var doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); - var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); + XmlAttributeDeserializer xml = new XmlAttributeDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -583,13 +592,13 @@ public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Popula [Test] public void Can_Deserialize_DateTimeOffset() { - var culture = CultureInfo.InvariantCulture; - var doc = new XDocument(culture); + CultureInfo culture = CultureInfo.InvariantCulture; + XDocument doc = new XDocument(culture); DateTimeOffset dateTimeOffset = new DateTimeOffset(2013, 02, 08, 9, 18, 22, TimeSpan.FromHours(10)); DateTimeOffset? nullableDateTimeOffsetWithValue = new DateTimeOffset(2013, 02, 08, 9, 18, 23, TimeSpan.FromHours(10)); - var root = new XElement("Dates"); + XElement root = new XElement("Dates"); root.Add(new XElement("DateTimeOffset", dateTimeOffset)); root.Add(new XElement("NullableDateTimeOffsetWithNull", string.Empty)); @@ -598,9 +607,9 @@ public void Can_Deserialize_DateTimeOffset() doc.Add(root); //var xml = new XmlAttributeDeserializer { Culture = culture }; - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlAttributeDeserializer { Culture = culture }; - var payload = d.Deserialize(response); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlAttributeDeserializer d = new XmlAttributeDeserializer { Culture = culture }; + DateTimeTestStructure payload = d.Deserialize(response); Assert.AreEqual(dateTimeOffset, payload.DateTimeOffset); Assert.Null(payload.NullableDateTimeOffsetWithNull); @@ -610,8 +619,8 @@ public void Can_Deserialize_DateTimeOffset() private static string CreateUnderscoresXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -628,7 +637,7 @@ private static string CreateUnderscoresXml() new XElement("Name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -639,7 +648,7 @@ private static string CreateUnderscoresXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -656,8 +665,8 @@ private static string CreateUnderscoresXml() private static string CreateLowercaseUnderscoresXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("start_date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -674,7 +683,7 @@ private static string CreateLowercaseUnderscoresXml() new XElement("name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -685,7 +694,7 @@ private static string CreateLowercaseUnderscoresXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -702,8 +711,8 @@ private static string CreateLowercaseUnderscoresXml() private static string CreateDashesXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -720,7 +729,7 @@ private static string CreateDashesXml() new XElement("Name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -731,7 +740,7 @@ private static string CreateDashesXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -748,8 +757,8 @@ private static string CreateDashesXml() private static string CreateLowerCasedRootElementWithDashesXml() { - var doc = new XDocument(); - var root = new XElement("incoming-invoices", + XDocument doc = new XDocument(); + XElement root = new XElement("incoming-invoices", new XElement("incoming-invoice", new XElement("concept-id", 45))); @@ -760,8 +769,8 @@ private static string CreateLowerCasedRootElementWithDashesXml() private static string CreateElementsXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -781,7 +790,7 @@ private static string CreateElementsXml() new XElement("Name", "The Fonz"), new XElement("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -801,8 +810,8 @@ private static string CreateElementsXml() private static string CreateAttributesXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XAttribute("Name", "John Sheehan")); root.Add(new XAttribute("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -826,8 +835,8 @@ private static string CreateAttributesXml() private static string CreateXmlWithNullValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); root.Add(new XElement("Id", null), new XElement("StartDate", null), @@ -840,8 +849,8 @@ private static string CreateXmlWithNullValues() private static string CreateXmlWithoutEmptyValues(CultureInfo culture) { - var doc = new XDocument(); - var root = new XElement("NullableValues"); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); root.Add(new XElement("Id", 123), new XElement("StartDate", new DateTime(2010, 2, 21, 9, 35, 00).ToString(culture)), @@ -854,8 +863,8 @@ private static string CreateXmlWithoutEmptyValues(CultureInfo culture) private static string CreateXmlWithEmptyNestedList() { - var doc = new XDocument(); - var root = new XElement("EmptyListSample"); + XDocument doc = new XDocument(); + XElement root = new XElement("EmptyListSample"); root.Add(new XElement("Images")); doc.Add(root); @@ -865,8 +874,8 @@ private static string CreateXmlWithEmptyNestedList() private static string CreateXmlWithEmptyInlineList() { - var doc = new XDocument(); - var root = new XElement("EmptyListSample"); + XDocument doc = new XDocument(); + XElement root = new XElement("EmptyListSample"); doc.Add(root); @@ -875,9 +884,9 @@ private static string CreateXmlWithEmptyInlineList() private static string CreateXmlWithAttributesAndNullValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); - var idElement = new XElement("Id", null); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); + XElement idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add(idElement, @@ -891,9 +900,9 @@ private static string CreateXmlWithAttributesAndNullValues() private static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); - var idElement = new XElement("Id", null); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); + XElement idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); root.Add(idElement, @@ -904,6 +913,5 @@ private static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() return doc.ToString(); } - } } diff --git a/RestSharp.Tests/XmlDeserializerTests.cs b/RestSharp.Tests/XmlDeserializerTests.cs index 4df10d80f..99ccda57f 100644 --- a/RestSharp.Tests/XmlDeserializerTests.cs +++ b/RestSharp.Tests/XmlDeserializerTests.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -23,6 +25,7 @@ using NUnit.Framework; using RestSharp.Deserializers; using RestSharp.Tests.SampleClasses; +using Event = RestSharp.Tests.SampleClasses.Lastfm.Event; namespace RestSharp.Tests { @@ -30,6 +33,7 @@ namespace RestSharp.Tests public class XmlDeserializerTests { private const string GUID_STRING = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5"; + private readonly string sampleDataPath = Path.Combine(Environment.CurrentDirectory, "SampleData"); private string PathFor(string sampleFile) @@ -42,8 +46,8 @@ public void Can_Use_DeserializeAs_Attribute() { const string content = "1Jacksonoddball"; - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content }); + XmlDeserializer xml = new XmlDeserializer(); + Oddball output = xml.Deserialize(new RestResponse { Content = content }); Assert.NotNull(output); Assert.AreEqual("1", output.Sid); @@ -54,10 +58,10 @@ public void Can_Use_DeserializeAs_Attribute() [Test] public void Can_Use_DeserializeAs_Attribute_for_List() { - const string content = - "1Jacksonoddball1Jacksonevenball"; - var xml = new XmlDeserializer(); - List output = xml.Deserialize>(new RestResponse { Content = content }); + string xmlpath = this.PathFor("deserialize_as_list.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.NotNull(output); Assert.AreEqual("1", output[0].Sid); @@ -67,8 +71,8 @@ public void Can_Use_DeserializeAs_Attribute_for_List() public void Can_Deserialize_Into_Struct() { const string content = "oneOneOnetwoTwoTwo3"; - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content }); + XmlDeserializer xml = new XmlDeserializer(); + SimpleStruct output = xml.Deserialize(new RestResponse { Content = content }); Assert.NotNull(output); Assert.AreEqual("oneOneOne", output.One); @@ -79,10 +83,11 @@ public void Can_Deserialize_Into_Struct() [Test] public void Can_Deserialize_Lists_of_Simple_Types() { - var xmlpath = this.PathFor("xmllists.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("xmllists.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + SimpleTypesListSample output = xml.Deserialize( + new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Names); Assert.IsNotEmpty(output.Numbers); @@ -93,10 +98,10 @@ public void Can_Deserialize_Lists_of_Simple_Types() [Test] public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() { - var xmlpath = this.PathFor("ListWithAttributes.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer { RootElement = "Calls" }; - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("ListWithAttributes.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer { RootElement = "Calls" }; + TwilioCallList output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.AreEqual(3, output.NumPages); Assert.IsNotEmpty(output); @@ -106,10 +111,10 @@ public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() [Test] public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(4, output.Count); @@ -118,10 +123,10 @@ public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() [Test] public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(4, output.Count); @@ -130,10 +135,10 @@ public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() [Test] public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { - var xmlpath = this.PathFor("directlists.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("directlists.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + List output = xml.Deserialize>(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output); Assert.AreEqual(2, output.Count); @@ -142,10 +147,10 @@ public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Class_Name() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Images); Assert.AreEqual(4, output.Images.Count); @@ -154,10 +159,10 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Cl [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.images); Assert.AreEqual(4, output.images.Count); @@ -166,10 +171,10 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class [Test] public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class_Name_With_Additional_Property() { - var xmlpath = this.PathFor("InlineListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("InlineListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.AreEqual(4, output.Count); } @@ -177,23 +182,22 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class [Test] public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { - var xmlpath = this.PathFor("NestedListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("NestedListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.Images); Assert.AreEqual(4, output.Images.Count); } - [Test] public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { - var xmlpath = this.PathFor("NestedListSample.xml"); - var doc = XDocument.Load(xmlpath); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + string xmlpath = this.PathFor("NestedListSample.xml"); + XDocument doc = XDocument.Load(xmlpath); + XmlDeserializer xml = new XmlDeserializer(); + InlineListSample output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); Assert.IsNotEmpty(output.images); Assert.AreEqual(4, output.images.Count); @@ -202,9 +206,9 @@ public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() [Test] public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { - var doc = CreateXmlWithEmptyNestedList(); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithEmptyNestedList(); + XmlDeserializer xml = new XmlDeserializer(); + EmptyListSample output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.images); Assert.NotNull(output.Images); @@ -215,9 +219,9 @@ public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() [Test] public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { - var doc = CreateXmlWithEmptyInlineList(); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithEmptyInlineList(); + XmlDeserializer xml = new XmlDeserializer(); + EmptyListSample output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.images); Assert.NotNull(output.Images); @@ -228,9 +232,9 @@ public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() [Test] public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { - var doc = CreateXmlWithNullValues(); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithNullValues(); + XmlDeserializer xml = new XmlDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -240,10 +244,13 @@ public void Can_Deserialize_Empty_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_Elements_to_Nullable_Values() { - var culture = CultureInfo.InvariantCulture; - var doc = CreateXmlWithoutEmptyValues(culture); - var xml = new XmlDeserializer { Culture = culture }; - var output = xml.Deserialize(new RestResponse { Content = doc }); + CultureInfo culture = CultureInfo.InvariantCulture; + string doc = CreateXmlWithoutEmptyValues(culture); + XmlDeserializer xml = new XmlDeserializer + { + Culture = culture + }; + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); @@ -256,11 +263,11 @@ public void Can_Deserialize_Elements_to_Nullable_Values() [Test] public void Can_Deserialize_TimeSpan() { - var culture = CultureInfo.InvariantCulture; - var doc = new XDocument(culture); + CultureInfo culture = CultureInfo.InvariantCulture; + XDocument doc = new XDocument(culture); TimeSpan? nullTimespan = null; TimeSpan? nullValueTimeSpan = new TimeSpan(21, 30, 7); - var root = new XElement("Person"); + XElement root = new XElement("Person"); root.Add(new XElement("Tick", new TimeSpan(468006))); root.Add(new XElement("Millisecond", new TimeSpan(0, 0, 0, 0, 125))); @@ -272,9 +279,15 @@ public void Can_Deserialize_TimeSpan() doc.Add(root); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer { Culture = culture, }; - var payload = d.Deserialize(response); + RestResponse response = new RestResponse + { + Content = doc.ToString() + }; + XmlDeserializer d = new XmlDeserializer + { + Culture = culture, + }; + TimeSpanTestStructure payload = d.Deserialize(response); Assert.AreEqual(new TimeSpan(468006), payload.Tick); Assert.AreEqual(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond); @@ -289,22 +302,22 @@ public void Can_Deserialize_TimeSpan() [Test] public void Can_Deserialize_Custom_Formatted_Date() { - var culture = CultureInfo.InvariantCulture; - var format = "dd yyyy MMM, hh:mm ss tt zzz"; - var date = new DateTime(2010, 2, 8, 11, 11, 11); - var doc = new XDocument(); - var root = new XElement("Person"); + CultureInfo culture = CultureInfo.InvariantCulture; + string format = "dd yyyy MMM, hh:mm ss tt zzz"; + DateTime date = new DateTime(2010, 2, 8, 11, 11, 11); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("StartDate", date.ToString(format, culture))); doc.Add(root); - var xml = new XmlDeserializer - { - DateFormat = format, - Culture = culture - }; - var response = new RestResponse { Content = doc.ToString() }; - var output = xml.Deserialize(response); + XmlDeserializer xml = new XmlDeserializer + { + DateFormat = format, + Culture = culture + }; + RestResponse response = new RestResponse { Content = doc.ToString() }; + PersonForXml output = xml.Deserialize(response); Assert.AreEqual(date, output.StartDate); } @@ -312,10 +325,10 @@ public void Can_Deserialize_Custom_Formatted_Date() [Test] public void Can_Deserialize_Elements_On_Default_Root() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -339,10 +352,10 @@ public void Can_Deserialize_Elements_On_Default_Root() [Test] public void Can_Deserialize_Attributes_On_Default_Root() { - var doc = CreateAttributesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateAttributesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -361,10 +374,10 @@ public void Can_Deserialize_Attributes_On_Default_Root() [Test] public void Ignore_Protected_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.Null(p.IgnoreProxy); } @@ -372,10 +385,10 @@ public void Ignore_Protected_Property_That_Exists_In_Data() [Test] public void Ignore_ReadOnly_Property_That_Exists_In_Data() { - var doc = CreateElementsXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateElementsXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.Null(p.ReadOnlyProxy); } @@ -383,10 +396,10 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() [Test] public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { - var doc = CreateUnderscoresXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateUnderscoresXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -410,10 +423,10 @@ public void Can_Deserialize_Names_With_Underscores_On_Default_Root() [Test] public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { - var doc = CreateDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -437,10 +450,10 @@ public void Can_Deserialize_Names_With_Dashes_On_Default_Root() [Test] public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Default_Root() { - var doc = CreateLowercaseUnderscoresXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateLowercaseUnderscoresXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -464,10 +477,10 @@ public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Defa [Test] public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { - var doc = CreateDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize(response); + string doc = CreateDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + PersonForXml p = d.Deserialize(response); Assert.AreEqual("John Sheehan", p.Name); Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); @@ -491,10 +504,10 @@ public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() [Test] public void Can_Deserialize_Root_Elements_Without_Matching_Case_And_Dashes() { - var doc = CreateLowerCasedRootElementWithDashesXml(); - var response = new RestResponse { Content = doc }; - var d = new XmlDeserializer(); - var p = d.Deserialize>(response); + string doc = CreateLowerCasedRootElementWithDashesXml(); + RestResponse response = new RestResponse { Content = doc }; + XmlDeserializer d = new XmlDeserializer(); + List p = d.Deserialize>(response); Assert.NotNull(p); Assert.AreEqual(1, p.Count); @@ -504,11 +517,11 @@ public void Can_Deserialize_Root_Elements_Without_Matching_Case_And_Dashes() [Test] public void Can_Deserialize_Eventful_Xml() { - var xmlpath = this.PathFor("eventful.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("eventful.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + VenueSearch output = d.Deserialize(response); Assert.IsNotEmpty(output.venues); Assert.AreEqual(3, output.venues.Count); @@ -520,11 +533,11 @@ public void Can_Deserialize_Eventful_Xml() [Test] public void Can_Deserialize_Lastfm_Xml() { - var xmlpath = this.PathFor("Lastfm.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("Lastfm.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + Event output = d.Deserialize(response); //Assert.IsNotEmpty(output.artists); Assert.AreEqual("http://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008", output.url); @@ -534,11 +547,11 @@ public void Can_Deserialize_Lastfm_Xml() [Test] public void Can_Deserialize_Google_Weather_Xml() { - var xmlpath = this.PathFor("GoogleWeather.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("GoogleWeather.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + xml_api_reply output = d.Deserialize(response); Assert.IsNotEmpty(output.weather); Assert.AreEqual(4, output.weather.Count); @@ -548,11 +561,11 @@ public void Can_Deserialize_Google_Weather_Xml() [Test] public void Can_Deserialize_Goodreads_Xml() { - var xmlpath = this.PathFor("Goodreads.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("Goodreads.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + GoodReadsReviewCollection output = d.Deserialize(response); Assert.AreEqual(2, output.Reviews.Count); Assert.AreEqual("1208943892", output.Reviews[0].Id); // This fails without fixing the XmlDeserializer @@ -562,11 +575,11 @@ public void Can_Deserialize_Goodreads_Xml() [Test] public void Can_Deserialize_Boolean_From_Number() { - var xmlpath = this.PathFor("boolean_from_number.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("boolean_from_number.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + BooleanTest output = d.Deserialize(response); Assert.True(output.Value); } @@ -574,11 +587,11 @@ public void Can_Deserialize_Boolean_From_Number() [Test] public void Can_Deserialize_Boolean_From_String() { - var xmlpath = this.PathFor("boolean_from_string.xml"); - var doc = XDocument.Load(xmlpath); - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer(); - var output = d.Deserialize(response); + string xmlpath = this.PathFor("boolean_from_string.xml"); + XDocument doc = XDocument.Load(xmlpath); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer(); + BooleanTest output = d.Deserialize(response); Assert.True(output.Value); } @@ -586,9 +599,9 @@ public void Can_Deserialize_Boolean_From_String() [Test] public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { - var doc = CreateXmlWithAttributesAndNullValues(); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithAttributesAndNullValues(); + XmlDeserializer xml = new XmlDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -598,9 +611,9 @@ public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() [Test] public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Populated_Elements() { - var doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); - var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc }); + string doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); + XmlDeserializer xml = new XmlDeserializer(); + NullableValues output = xml.Deserialize(new RestResponse { Content = doc }); Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -610,11 +623,11 @@ public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Popula [Test] public void Can_Deserialize_DateTimeOffset() { - var culture = CultureInfo.InvariantCulture; - var doc = new XDocument(culture); + CultureInfo culture = CultureInfo.InvariantCulture; + XDocument doc = new XDocument(culture); DateTimeOffset dateTimeOffset = new DateTimeOffset(2013, 02, 08, 9, 18, 22, TimeSpan.FromHours(10)); DateTimeOffset? nullableDateTimeOffsetWithValue = new DateTimeOffset(2013, 02, 08, 9, 18, 23, TimeSpan.FromHours(10)); - var root = new XElement("Dates"); + XElement root = new XElement("Dates"); root.Add(new XElement("DateTimeOffset", dateTimeOffset)); root.Add(new XElement("NullableDateTimeOffsetWithNull", string.Empty)); @@ -623,9 +636,9 @@ public void Can_Deserialize_DateTimeOffset() doc.Add(root); //var xml = new XmlDeserializer { Culture = culture, }; - var response = new RestResponse { Content = doc.ToString() }; - var d = new XmlDeserializer { Culture = culture, }; - var payload = d.Deserialize(response); + RestResponse response = new RestResponse { Content = doc.ToString() }; + XmlDeserializer d = new XmlDeserializer { Culture = culture }; + DateTimeTestStructure payload = d.Deserialize(response); Assert.AreEqual(dateTimeOffset, payload.DateTimeOffset); Assert.Null(payload.NullableDateTimeOffsetWithNull); @@ -635,8 +648,8 @@ public void Can_Deserialize_DateTimeOffset() private static string CreateUnderscoresXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -653,7 +666,7 @@ private static string CreateUnderscoresXml() new XElement("Name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -664,7 +677,7 @@ private static string CreateUnderscoresXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -681,8 +694,8 @@ private static string CreateUnderscoresXml() private static string CreateLowercaseUnderscoresXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("start_date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -699,7 +712,7 @@ private static string CreateLowercaseUnderscoresXml() new XElement("name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -710,7 +723,7 @@ private static string CreateLowercaseUnderscoresXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -727,8 +740,8 @@ private static string CreateLowercaseUnderscoresXml() private static string CreateDashesXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -745,7 +758,7 @@ private static string CreateDashesXml() new XElement("Name", "The Fonz"), new XAttribute("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -756,7 +769,7 @@ private static string CreateDashesXml() root.Add(friends); - var foes = new XElement("Foes"); + XElement foes = new XElement("Foes"); foes.Add(new XAttribute("Team", "Yankees")); @@ -773,8 +786,8 @@ private static string CreateDashesXml() private static string CreateLowerCasedRootElementWithDashesXml() { - var doc = new XDocument(); - var root = new XElement("incoming-invoices", + XDocument doc = new XDocument(); + XElement root = new XElement("incoming-invoices", new XElement("incoming-invoice", new XElement("concept-id", 45))); doc.Add(root); @@ -784,8 +797,8 @@ private static string CreateLowerCasedRootElementWithDashesXml() private static string CreateElementsXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XElement("Name", "John Sheehan")); root.Add(new XElement("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -805,7 +818,7 @@ private static string CreateElementsXml() new XElement("Name", "The Fonz"), new XElement("Since", 1952))); - var friends = new XElement("Friends"); + XElement friends = new XElement("Friends"); for (int i = 0; i < 10; i++) { @@ -822,8 +835,8 @@ private static string CreateElementsXml() private static string CreateAttributesXml() { - var doc = new XDocument(); - var root = new XElement("Person"); + XDocument doc = new XDocument(); + XElement root = new XElement("Person"); root.Add(new XAttribute("Name", "John Sheehan")); root.Add(new XAttribute("StartDate", new DateTime(2009, 9, 25, 0, 6, 1))); @@ -847,8 +860,8 @@ private static string CreateAttributesXml() private static string CreateXmlWithNullValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); root.Add(new XElement("Id", null), new XElement("StartDate", null), @@ -861,8 +874,8 @@ private static string CreateXmlWithNullValues() private static string CreateXmlWithoutEmptyValues(CultureInfo culture) { - var doc = new XDocument(); - var root = new XElement("NullableValues"); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); root.Add(new XElement("Id", 123), new XElement("StartDate", new DateTime(2010, 2, 21, 9, 35, 00).ToString(culture)), @@ -875,8 +888,8 @@ private static string CreateXmlWithoutEmptyValues(CultureInfo culture) private static string CreateXmlWithEmptyNestedList() { - var doc = new XDocument(); - var root = new XElement("EmptyListSample"); + XDocument doc = new XDocument(); + XElement root = new XElement("EmptyListSample"); root.Add(new XElement("Images")); doc.Add(root); @@ -886,8 +899,8 @@ private static string CreateXmlWithEmptyNestedList() private static string CreateXmlWithEmptyInlineList() { - var doc = new XDocument(); - var root = new XElement("EmptyListSample"); + XDocument doc = new XDocument(); + XElement root = new XElement("EmptyListSample"); doc.Add(root); @@ -896,9 +909,9 @@ private static string CreateXmlWithEmptyInlineList() private static string CreateXmlWithAttributesAndNullValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); - var idElement = new XElement("Id", null); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); + XElement idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); @@ -913,9 +926,9 @@ private static string CreateXmlWithAttributesAndNullValues() private static string CreateXmlWithAttributesAndNullValuesAndPopulatedValues() { - var doc = new XDocument(); - var root = new XElement("NullableValues"); - var idElement = new XElement("Id", null); + XDocument doc = new XDocument(); + XElement root = new XElement("NullableValues"); + XElement idElement = new XElement("Id", null); idElement.SetAttributeValue("SomeAttribute", "SomeAttribute_Value"); diff --git a/RestSharp.Tests/packages.config b/RestSharp.Tests/packages.config index d904986a8..393f35298 100644 --- a/RestSharp.Tests/packages.config +++ b/RestSharp.Tests/packages.config @@ -1,5 +1,6 @@  + - - + + \ No newline at end of file diff --git a/RestSharp.sln b/RestSharp.sln index 245edcc9d..a40282629 100644 --- a/RestSharp.sln +++ b/RestSharp.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 -VisualStudioVersion = 12.0.30723.0 +VisualStudioVersion = 12.0.40629.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{E709A928-A45C-4622-A35C-CCD8EE44CA80}" ProjectSection(SolutionItems) = preProject @@ -25,8 +25,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Meta", "Meta", "{C5B02FAA-6 releasenotes.markdown = releasenotes.markdown EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp", "RestSharp\RestSharp.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Tests", "RestSharp.Tests\RestSharp.Tests.csproj", "{1464E4AC-18BB-4F23-8A0B-68196F9E1871}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.IntegrationTests", "RestSharp.IntegrationTests\RestSharp.IntegrationTests.csproj", "{47D3EBB9-0300-4AF8-BAC5-740D51454A63}" @@ -45,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net451", "RestSha EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net452", "RestSharp.Net452\RestSharp.Net452.csproj", "{353349A9-4E6C-4706-A1C4-8363EAE0DBF3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RestSharp.Net35", "RestSharp\RestSharp.Net35.csproj", "{2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -61,24 +61,6 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|ARM.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|ARM.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|Any CPU.Build.0 = Debug|Any CPU {1464E4AC-18BB-4F23-8A0B-68196F9E1871}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -244,6 +226,24 @@ Global {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|Mixed Platforms.Build.0 = Release|Any CPU {353349A9-4E6C-4706-A1C4-8363EAE0DBF3}.Release|x86.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Debug|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Any CPU.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|ARM.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|Mixed Platforms.Build.0 = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.DebugAppveyor|x86.ActiveCfg = Debug|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Any CPU.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|ARM.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/RestSharp/Authenticators/HttpBasicAuthenticator.cs b/RestSharp/Authenticators/HttpBasicAuthenticator.cs index 0b254c517..782b04530 100644 --- a/RestSharp/Authenticators/HttpBasicAuthenticator.cs +++ b/RestSharp/Authenticators/HttpBasicAuthenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,22 +13,24 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Linq; using System.Text; -namespace RestSharp +namespace RestSharp.Authenticators { public class HttpBasicAuthenticator : IAuthenticator { - private readonly string _authHeader; + private readonly string authHeader; public HttpBasicAuthenticator(string username, string password) { - var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))); - _authHeader = string.Format("Basic {0}", token); + string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))); + + this.authHeader = string.Format("Basic {0}", token); } public void Authenticate(IRestClient client, IRestRequest request) @@ -42,7 +45,7 @@ public void Authenticate(IRestClient client, IRestRequest request) // only add the Authorization parameter if it hasn't been added by a previous Execute if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) { - request.AddParameter("Authorization", _authHeader, ParameterType.HttpHeader); + request.AddParameter("Authorization", this.authHeader, ParameterType.HttpHeader); } } } diff --git a/RestSharp/Authenticators/IAuthenticator.cs b/RestSharp/Authenticators/IAuthenticator.cs index 2177418d3..bad21cefd 100644 --- a/RestSharp/Authenticators/IAuthenticator.cs +++ b/RestSharp/Authenticators/IAuthenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,9 +13,10 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion -namespace RestSharp +namespace RestSharp.Authenticators { public interface IAuthenticator { diff --git a/RestSharp/Authenticators/JwtAuthenticator.cs b/RestSharp/Authenticators/JwtAuthenticator.cs index 0e704d1a6..49a836c97 100644 --- a/RestSharp/Authenticators/JwtAuthenticator.cs +++ b/RestSharp/Authenticators/JwtAuthenticator.cs @@ -1,4 +1,5 @@ #region License + // Author: Roman Kravchik // Based on HttpBasicAuthenticator class by John Sheehan // @@ -13,40 +14,40 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; -using RestSharp; using System.Linq; -namespace RestSharp +namespace RestSharp.Authenticators { - /// - /// JSON WEB TOKEN (JWT) Authenticator class. - /// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token - /// - public class JwtAuthenticator : IAuthenticator - { - readonly string authHeader; + /// + /// JSON WEB TOKEN (JWT) Authenticator class. + /// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token + /// + public class JwtAuthenticator : IAuthenticator + { + private readonly string authHeader; - public JwtAuthenticator(string accessToken) - { - if (accessToken == null) - { - throw new ArgumentNullException("accessToken"); - } + public JwtAuthenticator(string accessToken) + { + if (accessToken == null) + { + throw new ArgumentNullException("accessToken"); + } - authHeader = string.Format("Bearer {0}", accessToken); - } + this.authHeader = string.Format("Bearer {0}", accessToken); + } - public void Authenticate(IRestClient client, IRestRequest request) - { - // only add the Authorization parameter if it hasn't been added by a previous Execute - if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) && - p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) + public void Authenticate(IRestClient client, IRestRequest request) + { + // only add the Authorization parameter if it hasn't been added by a previous Execute + if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) && + p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) { - request.AddParameter("Authorization", authHeader, ParameterType.HttpHeader); + request.AddParameter("Authorization", this.authHeader, ParameterType.HttpHeader); } - } - } + } + } } diff --git a/RestSharp/Authenticators/NtlmAuthenticator.cs b/RestSharp/Authenticators/NtlmAuthenticator.cs index 22d1676e3..ca1601906 100644 --- a/RestSharp/Authenticators/NtlmAuthenticator.cs +++ b/RestSharp/Authenticators/NtlmAuthenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,14 +13,15 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion +#if FRAMEWORK + using System; using System.Net; -#if FRAMEWORK - -namespace RestSharp +namespace RestSharp.Authenticators { /// /// Tries to Authenticate with the credentials of the currently logged in user, or impersonate a user @@ -49,16 +51,18 @@ public NtlmAuthenticator(string username, string password) public NtlmAuthenticator(ICredentials credentials) { if (credentials == null) + { throw new ArgumentNullException("credentials"); + } this.credentials = credentials; } public void Authenticate(IRestClient client, IRestRequest request) { - request.Credentials = credentials; + request.Credentials = this.credentials; } } } -#endif \ No newline at end of file +#endif diff --git a/RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs b/RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs index 63595328b..b65e18e5d 100644 --- a/RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs +++ b/RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; +using System.Linq; using System.Text; namespace RestSharp.Authenticators.OAuth.Extensions @@ -19,7 +20,7 @@ public static IEnumerable And(this T item, T other) public static IEnumerable And(this IEnumerable items, T item) { - foreach (var i in items) + foreach (T i in items) { yield return i; } @@ -27,33 +28,30 @@ public static IEnumerable And(this IEnumerable items, T item) yield return item; } - public static K TryWithKey(this IDictionary dictionary, T key) + public static TK TryWithKey(this IDictionary dictionary, T key) { - return dictionary.ContainsKey(key) ? dictionary[key] : default(K); + return dictionary.ContainsKey(key) + ? dictionary[key] + : default(TK); } public static IEnumerable ToEnumerable(this object[] items) where T : class { - foreach (var item in items) - { - var record = item as T; - yield return record; - } + return items.Select(item => item as T); } public static void ForEach(this IEnumerable items, Action action) { - foreach (var item in items) + foreach (T item in items) { action(item); } } -#if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC - +#if !WINDOWS_PHONE && !SILVERLIGHT public static void AddRange(this IDictionary collection, NameValueCollection range) { - foreach (var key in range.AllKeys) + foreach (string key in range.AllKeys) { collection.Add(key, range[key]); } @@ -61,14 +59,16 @@ public static void AddRange(this IDictionary collection, NameVal public static string ToQueryString(this NameValueCollection collection) { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + if (collection.Count > 0) { sb.Append("?"); } - var count = 0; - foreach (var key in collection.AllKeys) + int count = 0; + + foreach (string key in collection.AllKeys) { sb.AppendFormat("{0}={1}", key, collection[key].UrlEncode()); count++; @@ -77,27 +77,28 @@ public static string ToQueryString(this NameValueCollection collection) { continue; } + sb.Append("&"); } + return sb.ToString(); } - #endif public static string Concatenate(this WebParameterCollection collection, string separator, string spacer) { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + int total = collection.Count; + int count = 0; - var total = collection.Count; - var count = 0; - - foreach (var item in collection) + foreach (WebPair item in collection) { sb.Append(item.Name); sb.Append(separator); sb.Append(item.Value); count++; + if (count < total) { sb.Append(spacer); diff --git a/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs b/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs index a6c02f6d5..53c44c350 100644 --- a/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs +++ b/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs @@ -8,9 +8,13 @@ internal static class OAuthExtensions { public static string ToRequestValue(this OAuthSignatureMethod signatureMethod) { - var value = signatureMethod.ToString().ToUpper(); - var shaIndex = value.IndexOf("SHA1"); - return shaIndex > -1 ? value.Insert(shaIndex, "-") : value; + string value = signatureMethod.ToString() + .ToUpper(); + int shaIndex = value.IndexOf("SHA1"); + + return shaIndex > -1 + ? value.Insert(shaIndex, "-") + : value; } public static OAuthSignatureMethod FromRequestValue(this string signatureMethod) @@ -19,8 +23,10 @@ public static OAuthSignatureMethod FromRequestValue(this string signatureMethod) { case "HMAC-SHA1": return OAuthSignatureMethod.HmacSha1; + case "RSA-SHA1": return OAuthSignatureMethod.RsaSha1; + default: return OAuthSignatureMethod.PlainText; } @@ -28,8 +34,9 @@ public static OAuthSignatureMethod FromRequestValue(this string signatureMethod) public static string HashWith(this string input, HashAlgorithm algorithm) { - var data = Encoding.UTF8.GetBytes(input); - var hash = algorithm.ComputeHash(data); + byte[] data = Encoding.UTF8.GetBytes(input); + byte[] hash = algorithm.ComputeHash(data); + return Convert.ToBase64String(hash); } } diff --git a/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs b/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs index e280ebe18..b86519c44 100644 --- a/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs +++ b/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs @@ -3,7 +3,6 @@ using System.Globalization; using System.Linq; using System.Text; -using System.Text.RegularExpressions; namespace RestSharp.Authenticators.OAuth.Extensions { @@ -11,13 +10,13 @@ internal static class StringExtensions { public static bool IsNullOrBlank(this string value) { - return String.IsNullOrEmpty(value) || - (!String.IsNullOrEmpty(value) && value.Trim() == String.Empty); + return string.IsNullOrEmpty(value) || + (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty); } public static bool EqualsIgnoreCase(this string left, string right) { - return String.Compare(left, right, StringComparison.OrdinalIgnoreCase) == 0; + return string.Compare(left, right, StringComparison.OrdinalIgnoreCase) == 0; } public static bool EqualsAny(this string input, params string[] args) @@ -27,17 +26,17 @@ public static bool EqualsAny(this string input, params string[] args) public static string FormatWith(this string format, params object[] args) { - return String.Format(format, args); + return string.Format(format, args); } public static string FormatWithInvariantCulture(this string format, params object[] args) { - return String.Format(CultureInfo.InvariantCulture, format, args); + return string.Format(CultureInfo.InvariantCulture, format, args); } public static string Then(this string input, string value) { - return String.Concat(input, value); + return string.Concat(input, value); } public static string UrlEncode(this string value) @@ -68,38 +67,34 @@ public static byte[] GetBytes(this string input) public static string PercentEncode(this string s) { - var bytes = s.GetBytes(); - var sb = new StringBuilder(); - foreach (var b in bytes) + byte[] bytes = s.GetBytes(); + StringBuilder sb = new StringBuilder(); + + foreach (byte b in bytes) { - sb.Append(String.Format("%{0:X2}", b)); + sb.Append(string.Format("%{0:X2}", b)); } + return sb.ToString(); } public static IDictionary ParseQueryString(this string query) { // [DC]: This method does not URL decode, and cannot handle decoded input - if (query.StartsWith("?")) query = query.Substring(1); + if (query.StartsWith("?")) + { + query = query.Substring(1); + } if (query.Equals(string.Empty)) { return new Dictionary(); } - var parts = query.Split(new[] { '&' }); + string[] parts = query.Split('&'); - return parts.Select( - part => part.Split(new[] { '=' })).ToDictionary( - pair => pair[0], pair => pair[1] - ); + return parts.Select(part => part.Split('=')) + .ToDictionary(pair => pair[0], pair => pair[1]); } - - private const RegexOptions Options = -#if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC - RegexOptions.Compiled | RegexOptions.IgnoreCase; -#else - RegexOptions.IgnoreCase; -#endif } } diff --git a/RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs b/RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs index 948b9f024..3adff676d 100644 --- a/RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs +++ b/RestSharp/Authenticators/OAuth/Extensions/TimeExtensions.cs @@ -11,7 +11,8 @@ public static DateTime FromNow(this TimeSpan value) public static DateTime FromUnixTime(this long seconds) { - var time = new DateTime(1970, 1, 1); + DateTime time = new DateTime(1970, 1, 1); + time = time.AddSeconds(seconds); return time.ToLocalTime(); @@ -19,8 +20,8 @@ public static DateTime FromUnixTime(this long seconds) public static long ToUnixTime(this DateTime dateTime) { - var timeSpan = (dateTime - new DateTime(1970, 1, 1)); - var timestamp = (long)timeSpan.TotalSeconds; + TimeSpan timeSpan = (dateTime - new DateTime(1970, 1, 1)); + long timestamp = (long) timeSpan.TotalSeconds; return timestamp; } diff --git a/RestSharp/Authenticators/OAuth/HttpPostParameter.cs b/RestSharp/Authenticators/OAuth/HttpPostParameter.cs index 332aabf0e..d44f51f94 100644 --- a/RestSharp/Authenticators/OAuth/HttpPostParameter.cs +++ b/RestSharp/Authenticators/OAuth/HttpPostParameter.cs @@ -4,7 +4,8 @@ namespace RestSharp.Authenticators.OAuth { internal class HttpPostParameter : WebParameter { - public HttpPostParameter(string name, string value) : base(name, value) { } + public HttpPostParameter(string name, string value) + : base(name, value) { } public virtual HttpPostParameterType Type { get; private set; } @@ -18,25 +19,26 @@ public HttpPostParameter(string name, string value) : base(name, value) { } public static HttpPostParameter CreateFile(string name, string fileName, string filePath, string contentType) { - var parameter = new HttpPostParameter(name, string.Empty) - { - Type = HttpPostParameterType.File, - FileName = fileName, - FilePath = filePath, - ContentType = contentType, - }; + HttpPostParameter parameter = new HttpPostParameter(name, string.Empty) + { + Type = HttpPostParameterType.File, + FileName = fileName, + FilePath = filePath, + ContentType = contentType, + }; + return parameter; } public static HttpPostParameter CreateFile(string name, string fileName, Stream fileStream, string contentType) { - var parameter = new HttpPostParameter(name, string.Empty) - { - Type = HttpPostParameterType.File, - FileName = fileName, - FileStream = fileStream, - ContentType = contentType, - }; + HttpPostParameter parameter = new HttpPostParameter(name, string.Empty) + { + Type = HttpPostParameterType.File, + FileName = fileName, + FileStream = fileStream, + ContentType = contentType, + }; return parameter; } diff --git a/RestSharp/Authenticators/OAuth/HttpPostParameterType.cs b/RestSharp/Authenticators/OAuth/HttpPostParameterType.cs index e345efe4e..0ad1d3f78 100644 --- a/RestSharp/Authenticators/OAuth/HttpPostParameterType.cs +++ b/RestSharp/Authenticators/OAuth/HttpPostParameterType.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif internal enum HttpPostParameterType diff --git a/RestSharp/Authenticators/OAuth/OAuthParameterHandling.cs b/RestSharp/Authenticators/OAuth/OAuthParameterHandling.cs index 35d8f08a8..e9b79a6a5 100644 --- a/RestSharp/Authenticators/OAuth/OAuthParameterHandling.cs +++ b/RestSharp/Authenticators/OAuth/OAuthParameterHandling.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif public enum OAuthParameterHandling diff --git a/RestSharp/Authenticators/OAuth/OAuthSignatureMethod.cs b/RestSharp/Authenticators/OAuth/OAuthSignatureMethod.cs index 534fa7c47..96e16236f 100644 --- a/RestSharp/Authenticators/OAuth/OAuthSignatureMethod.cs +++ b/RestSharp/Authenticators/OAuth/OAuthSignatureMethod.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif public enum OAuthSignatureMethod diff --git a/RestSharp/Authenticators/OAuth/OAuthSignatureTreatment.cs b/RestSharp/Authenticators/OAuth/OAuthSignatureTreatment.cs index 3b767e8ba..cad9e28e1 100644 --- a/RestSharp/Authenticators/OAuth/OAuthSignatureTreatment.cs +++ b/RestSharp/Authenticators/OAuth/OAuthSignatureTreatment.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif public enum OAuthSignatureTreatment diff --git a/RestSharp/Authenticators/OAuth/OAuthTools.cs b/RestSharp/Authenticators/OAuth/OAuthTools.cs index e63fd0688..be6dfe35c 100644 --- a/RestSharp/Authenticators/OAuth/OAuthTools.cs +++ b/RestSharp/Authenticators/OAuth/OAuthTools.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; @@ -6,32 +7,38 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif internal static class OAuthTools { - private const string AlphaNumeric = Upper + Lower + Digit; - private const string Digit = "1234567890"; - private const string Lower = "abcdefghijklmnopqrstuvwxyz"; - private const string Unreserved = AlphaNumeric + "-._~"; - private const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private const string ALPHA_NUMERIC = UPPER + LOWER + DIGIT; - private static readonly Random _random; - private static readonly object _randomLock = new object(); + private const string DIGIT = "1234567890"; -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC - private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); + private const string LOWER = "abcdefghijklmnopqrstuvwxyz"; + + private const string UNRESERVED = ALPHA_NUMERIC + "-._~"; + + private const string UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + private static readonly Random random; + + private static readonly object randomLock = new object(); + +#if !SILVERLIGHT && !WINDOWS_PHONE + private static readonly RandomNumberGenerator rng = RandomNumberGenerator.Create(); #endif static OAuthTools() { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC - var bytes = new byte[4]; - _rng.GetNonZeroBytes(bytes); - _random = new Random(BitConverter.ToInt32(bytes, 0)); +#if !SILVERLIGHT && !WINDOWS_PHONE + byte[] bytes = new byte[4]; + + rng.GetNonZeroBytes(bytes); + random = new Random(BitConverter.ToInt32(bytes, 0)); #else - _random = new Random(); + random = new Random(); #endif } @@ -39,7 +46,7 @@ static OAuthTools() /// All text parameters are UTF-8 encoded (per section 5.1). /// /// - private static readonly Encoding _encoding = Encoding.UTF8; + private static readonly Encoding encoding = Encoding.UTF8; /// /// Generates a random 16-byte lowercase alphanumeric string. @@ -48,14 +55,15 @@ static OAuthTools() /// public static string GetNonce() { - const string chars = (Lower + Digit); - var nonce = new char[16]; + const string chars = (LOWER + DIGIT); - lock (_randomLock) + char[] nonce = new char[16]; + + lock (randomLock) { - for (var i = 0; i < nonce.Length; i++) + for (int i = 0; i < nonce.Length; i++) { - nonce[i] = chars[_random.Next(0, chars.Length)]; + nonce[i] = chars[random.Next(0, chars.Length)]; } } @@ -80,7 +88,8 @@ public static string GetTimestamp() /// public static string GetTimestamp(DateTime dateTime) { - var timestamp = dateTime.ToUnixTime(); + long timestamp = dateTime.ToUnixTime(); + return timestamp.ToString(); } @@ -88,9 +97,9 @@ public static string GetTimestamp(DateTime dateTime) /// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986. /// /// - private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" }; + private static readonly string[] uriRfc3986CharsToEscape = { "!", "*", "'", "(", ")" }; - private static readonly string[] UriRfc3968EscapedHex = new[] { "%21", "%2A", "%27", "%28", "%29" }; + private static readonly string[] uriRfc3968EscapedHex = { "%21", "%2A", "%27", "%28", "%29" }; /// /// URL encodes a string based on section 5.1 of the OAuth spec. @@ -116,10 +125,11 @@ public static string UrlEncodeRelaxed(string value) StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value)); // Upgrade the escaping to RFC 3986, if necessary. - for (int i = 0; i < UriRfc3986CharsToEscape.Length; i++) + for (int i = 0; i < uriRfc3986CharsToEscape.Length; i++) { - string t = UriRfc3986CharsToEscape[i]; - escaped.Replace(t, UriRfc3968EscapedHex[i]); + string t = uriRfc3986CharsToEscape[i]; + + escaped.Replace(t, uriRfc3968EscapedHex[i]); } // Return the fully-RFC3986-escaped string. @@ -141,13 +151,16 @@ public static string UrlEncodeStrict(string value) // Generic Syntax," .) section 2.3) MUST be encoded. // ... // unreserved = ALPHA, DIGIT, '-', '.', '_', '~' - String result = ""; + string result = ""; + value.ForEach(c => - { - result += Unreserved.Contains(c) - ? c.ToString() - : c.ToString().PercentEncode(); - }); + { + result += UNRESERVED.Contains(c) + ? c.ToString() + : c.ToString() + .PercentEncode(); + }); + return result; } @@ -161,8 +174,9 @@ public static string UrlEncodeStrict(string value) /// public static string NormalizeRequestParameters(WebParameterCollection parameters) { - var copy = SortParametersExcludingSignature(parameters); - var concatenated = copy.Concatenate("=", "&"); + WebParameterCollection copy = SortParametersExcludingSignature(parameters); + string concatenated = copy.Concatenate("=", "&"); + return concatenated; } @@ -173,16 +187,19 @@ public static string NormalizeRequestParameters(WebParameterCollection parameter /// A sorted parameter collection public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters) { - var copy = new WebParameterCollection(parameters); - var exclusions = copy.Where(n => n.Name.EqualsIgnoreCase("oauth_signature")); + WebParameterCollection copy = new WebParameterCollection(parameters); + IEnumerable exclusions = copy.Where(n => n.Name.EqualsIgnoreCase("oauth_signature")); copy.RemoveAll(exclusions); - copy.ForEach(p => { p.Name = UrlEncodeStrict(p.Name); p.Value = UrlEncodeStrict(p.Value); }); - copy.Sort( - (x, y) => - string.CompareOrdinal(x.Name, y.Name) != 0 - ? string.CompareOrdinal(x.Name, y.Name) - : string.CompareOrdinal(x.Value, y.Value)); + copy.ForEach(p => + { + p.Name = UrlEncodeStrict(p.Name); + p.Value = UrlEncodeStrict(p.Value); + }); + copy.Sort((x, y) => string.CompareOrdinal(x.Name, y.Name) != 0 + ? string.CompareOrdinal(x.Name, y.Name) + : string.CompareOrdinal(x.Value, y.Value)); + return copy; } @@ -201,15 +218,16 @@ public static string ConstructRequestUrl(Uri url) throw new ArgumentNullException("url"); } - var sb = new StringBuilder(); - - var requestUrl = "{0}://{1}".FormatWith(url.Scheme, url.Host); - var qualified = ":{0}".FormatWith(url.Port); - var basic = url.Scheme == "http" && url.Port == 80; - var secure = url.Scheme == "https" && url.Port == 443; + StringBuilder sb = new StringBuilder(); + string requestUrl = "{0}://{1}".FormatWith(url.Scheme, url.Host); + string qualified = ":{0}".FormatWith(url.Port); + bool basic = url.Scheme == "http" && url.Port == 80; + bool secure = url.Scheme == "https" && url.Port == 443; sb.Append(requestUrl); - sb.Append(!basic && !secure ? qualified : ""); + sb.Append(!basic && !secure + ? qualified + : ""); sb.Append(url.AbsolutePath); return sb.ToString(); //.ToLower(); @@ -227,12 +245,12 @@ public static string ConstructRequestUrl(Uri url) /// A signature base string public static string ConcatenateRequestElements(string method, string url, WebParameterCollection parameters) { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); // Separating &'s are not URL encoded - var requestMethod = method.ToUpper().Then("&"); - var requestUrl = UrlEncodeRelaxed(ConstructRequestUrl(url.AsUri())).Then("&"); - var requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters)); + string requestMethod = method.ToUpper().Then("&"); + string requestUrl = UrlEncodeRelaxed(ConstructRequestUrl(url.AsUri())).Then("&"); + string requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters)); sb.Append(requestMethod); sb.Append(requestUrl); @@ -265,7 +283,8 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, string s /// The signature base /// The consumer key /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret) + public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, + string signatureBase, string consumerSecret) { return GetSignature(signatureMethod, signatureTreatment, signatureBase, consumerSecret, null); } @@ -279,7 +298,8 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSig /// The consumer secret /// The token secret /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret, string tokenSecret) + public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret, + string tokenSecret) { return GetSignature(signatureMethod, OAuthSignatureTreatment.Escaped, consumerSecret, tokenSecret); } @@ -294,15 +314,12 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, string s /// The consumer secret /// The token secret /// - public static string GetSignature(OAuthSignatureMethod signatureMethod, - OAuthSignatureTreatment signatureTreatment, - string signatureBase, - string consumerSecret, - string tokenSecret) + public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, + string signatureBase, string consumerSecret, string tokenSecret) { if (tokenSecret.IsNullOrBlank()) { - tokenSecret = String.Empty; + tokenSecret = string.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); @@ -312,35 +329,29 @@ public static string GetSignature(OAuthSignatureMethod signatureMethod, switch (signatureMethod) { -#if !PocketPC case OAuthSignatureMethod.HmacSha1: - { - var crypto = new HMACSHA1(); - var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); + { + HMACSHA1 crypto = new HMACSHA1(); + string key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); - crypto.Key = _encoding.GetBytes(key); - signature = signatureBase.HashWith(crypto); + crypto.Key = encoding.GetBytes(key); + signature = signatureBase.HashWith(crypto); - break; - } -#endif + break; + } case OAuthSignatureMethod.PlainText: - { - signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); + { + signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); - break; - } + break; + } default: -#if PocketPC - throw new NotImplementedException("Only PlainText is currently supported."); -#else throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); -#endif } - var result = signatureTreatment == OAuthSignatureTreatment.Escaped + string result = signatureTreatment == OAuthSignatureTreatment.Escaped ? UrlEncodeRelaxed(signature) : signature; diff --git a/RestSharp/Authenticators/OAuth/OAuthType.cs b/RestSharp/Authenticators/OAuth/OAuthType.cs index 0355695b6..8c369bb76 100644 --- a/RestSharp/Authenticators/OAuth/OAuthType.cs +++ b/RestSharp/Authenticators/OAuth/OAuthType.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif public enum OAuthType diff --git a/RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs b/RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs index 45057a1bf..b73cfa3e3 100644 --- a/RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs +++ b/RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs @@ -2,7 +2,7 @@ namespace RestSharp.Authenticators.OAuth { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif public class OAuthWebQueryInfo diff --git a/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs b/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs index 405442698..9bf08e329 100644 --- a/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs +++ b/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using RestSharp.Authenticators.OAuth.Extensions; -#if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC -using RestSharp.Contrib; + +#if !SILVERLIGHT && !WINDOWS_PHONE +using System.Collections.Specialized; +using RestSharp.Extensions.MonoHttp; #endif namespace RestSharp.Authenticators.OAuth @@ -58,7 +60,7 @@ internal class OAuthWorkflow /// public OAuthWebQueryInfo BuildRequestTokenInfo(string method) { - return BuildRequestTokenInfo(method, null); + return this.BuildRequestTokenInfo(method, null); } /// @@ -72,36 +74,36 @@ public OAuthWebQueryInfo BuildRequestTokenInfo(string method) /// public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters) { - ValidateTokenRequestState(); + this.ValidateTokenRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } - var timestamp = OAuthTools.GetTimestamp(); - var nonce = OAuthTools.GetNonce(); - - AddAuthParameters(parameters, timestamp, nonce); - - var signatureBase = OAuthTools.ConcatenateRequestElements(method, RequestTokenUrl, parameters); - var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret); - - var info = new OAuthWebQueryInfo - { - WebMethod = method, - ParameterHandling = ParameterHandling, - ConsumerKey = ConsumerKey, - SignatureMethod = SignatureMethod.ToRequestValue(), - SignatureTreatment = SignatureTreatment, - Signature = signature, - Timestamp = timestamp, - Nonce = nonce, - Version = Version ?? "1.0", - Callback = OAuthTools.UrlEncodeRelaxed(CallbackUrl ?? ""), - TokenSecret = TokenSecret, - ConsumerSecret = ConsumerSecret - }; + string timestamp = OAuthTools.GetTimestamp(); + string nonce = OAuthTools.GetNonce(); + + this.AddAuthParameters(parameters, timestamp, nonce); + + string signatureBase = OAuthTools.ConcatenateRequestElements(method, this.RequestTokenUrl, parameters); + string signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, this.ConsumerSecret); + + OAuthWebQueryInfo info = new OAuthWebQueryInfo + { + WebMethod = method, + ParameterHandling = this.ParameterHandling, + ConsumerKey = this.ConsumerKey, + SignatureMethod = this.SignatureMethod.ToRequestValue(), + SignatureTreatment = this.SignatureTreatment, + Signature = signature, + Timestamp = timestamp, + Nonce = nonce, + Version = this.Version ?? "1.0", + Callback = OAuthTools.UrlEncodeRelaxed(this.CallbackUrl ?? ""), + TokenSecret = this.TokenSecret, + ConsumerSecret = this.ConsumerSecret + }; return info; } @@ -115,7 +117,7 @@ public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParamet /// public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method) { - return BuildAccessTokenInfo(method, null); + return this.BuildAccessTokenInfo(method, null); } /// @@ -128,39 +130,40 @@ public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method) /// Any existing, non-OAuth query parameters desired in the request public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParameterCollection parameters) { - ValidateAccessRequestState(); + this.ValidateAccessRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } - var uri = new Uri(AccessTokenUrl); - var timestamp = OAuthTools.GetTimestamp(); - var nonce = OAuthTools.GetNonce(); - - AddAuthParameters(parameters, timestamp, nonce); - - var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); - var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret); - - var info = new OAuthWebQueryInfo - { - WebMethod = method, - ParameterHandling = ParameterHandling, - ConsumerKey = ConsumerKey, - Token = Token, - SignatureMethod = SignatureMethod.ToRequestValue(), - SignatureTreatment = SignatureTreatment, - Signature = signature, - Timestamp = timestamp, - Nonce = nonce, - Version = Version ?? "1.0", - Verifier = Verifier, - Callback = CallbackUrl, - TokenSecret = TokenSecret, - ConsumerSecret = ConsumerSecret, - }; + Uri uri = new Uri(this.AccessTokenUrl); + string timestamp = OAuthTools.GetTimestamp(); + string nonce = OAuthTools.GetNonce(); + + this.AddAuthParameters(parameters, timestamp, nonce); + + string signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); + string signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, + this.ConsumerSecret, this.TokenSecret); + + OAuthWebQueryInfo info = new OAuthWebQueryInfo + { + WebMethod = method, + ParameterHandling = this.ParameterHandling, + ConsumerKey = this.ConsumerKey, + Token = this.Token, + SignatureMethod = this.SignatureMethod.ToRequestValue(), + SignatureTreatment = this.SignatureTreatment, + Signature = signature, + Timestamp = timestamp, + Nonce = nonce, + Version = this.Version ?? "1.0", + Verifier = this.Verifier, + Callback = this.CallbackUrl, + TokenSecret = this.TokenSecret, + ConsumerSecret = this.ConsumerSecret, + }; return info; } @@ -175,46 +178,48 @@ public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParamete /// Any existing, non-OAuth query parameters desired in the request public virtual OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters) { - ValidateClientAuthAccessRequestState(); + this.ValidateClientAuthAccessRequestState(); if (parameters == null) { parameters = new WebParameterCollection(); } - var uri = new Uri(AccessTokenUrl); - var timestamp = OAuthTools.GetTimestamp(); - var nonce = OAuthTools.GetNonce(); - - AddXAuthParameters(parameters, timestamp, nonce); - - var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); - var signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret); - - var info = new OAuthWebQueryInfo - { - WebMethod = method, - ParameterHandling = ParameterHandling, - ClientMode = "client_auth", - ClientUsername = ClientUsername, - ClientPassword = ClientPassword, - ConsumerKey = ConsumerKey, - SignatureMethod = SignatureMethod.ToRequestValue(), - SignatureTreatment = SignatureTreatment, - Signature = signature, - Timestamp = timestamp, - Nonce = nonce, - Version = Version ?? "1.0", - TokenSecret = TokenSecret, - ConsumerSecret = ConsumerSecret - }; + Uri uri = new Uri(this.AccessTokenUrl); + string timestamp = OAuthTools.GetTimestamp(); + string nonce = OAuthTools.GetNonce(); + + this.AddXAuthParameters(parameters, timestamp, nonce); + + string signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters); + string signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, + this.ConsumerSecret); + + OAuthWebQueryInfo info = new OAuthWebQueryInfo + { + WebMethod = method, + ParameterHandling = this.ParameterHandling, + ClientMode = "client_auth", + ClientUsername = this.ClientUsername, + ClientPassword = this.ClientPassword, + ConsumerKey = this.ConsumerKey, + SignatureMethod = this.SignatureMethod.ToRequestValue(), + SignatureTreatment = this.SignatureTreatment, + Signature = signature, + Timestamp = timestamp, + Nonce = nonce, + Version = this.Version ?? "1.0", + TokenSecret = this.TokenSecret, + ConsumerSecret = this.ConsumerSecret + }; return info; } - public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url) + public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, + string url) { - ValidateProtectedResourceState(); + this.ValidateProtectedResourceState(); if (parameters == null) { @@ -222,24 +227,20 @@ public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebPa } // Include url parameters in query pool - var uri = new Uri(url); -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC - var urlParameters = HttpUtility.ParseQueryString(uri.Query); + Uri uri = new Uri(url); +#if !SILVERLIGHT && !WINDOWS_PHONE + NameValueCollection urlParameters = HttpUtility.ParseQueryString(uri.Query); #else - var urlParameters = uri.Query.ParseQueryString(); + IDictionary urlParameters = uri.Query.ParseQueryString(); #endif -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC - foreach (var parameter in urlParameters.AllKeys) +#if !SILVERLIGHT && !WINDOWS_PHONE + foreach (string parameter in urlParameters.AllKeys) #else - foreach (var parameter in urlParameters.Keys) + foreach (string parameter in urlParameters.Keys) #endif { -#if PocketPC - switch (method.ToUpper()) -#else switch (method.ToUpperInvariant()) -#endif { case "POST": parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter])); @@ -251,48 +252,48 @@ public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebPa } } - var timestamp = OAuthTools.GetTimestamp(); - var nonce = OAuthTools.GetNonce(); - - AddAuthParameters(parameters, timestamp, nonce); - - var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters); - var signature = OAuthTools.GetSignature( - SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret); - - var info = new OAuthWebQueryInfo - { - WebMethod = method, - ParameterHandling = ParameterHandling, - ConsumerKey = ConsumerKey, - Token = Token, - SignatureMethod = SignatureMethod.ToRequestValue(), - SignatureTreatment = SignatureTreatment, - Signature = signature, - Timestamp = timestamp, - Nonce = nonce, - Version = Version ?? "1.0", - Callback = CallbackUrl, - ConsumerSecret = ConsumerSecret, - TokenSecret = TokenSecret - }; + string timestamp = OAuthTools.GetTimestamp(); + string nonce = OAuthTools.GetNonce(); + + this.AddAuthParameters(parameters, timestamp, nonce); + + string signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters); + string signature = OAuthTools.GetSignature(this.SignatureMethod, this.SignatureTreatment, signatureBase, + this.ConsumerSecret, this.TokenSecret); + + OAuthWebQueryInfo info = new OAuthWebQueryInfo + { + WebMethod = method, + ParameterHandling = this.ParameterHandling, + ConsumerKey = this.ConsumerKey, + Token = this.Token, + SignatureMethod = this.SignatureMethod.ToRequestValue(), + SignatureTreatment = this.SignatureTreatment, + Signature = signature, + Timestamp = timestamp, + Nonce = nonce, + Version = this.Version ?? "1.0", + Callback = this.CallbackUrl, + ConsumerSecret = this.ConsumerSecret, + TokenSecret = this.TokenSecret + }; return info; } private void ValidateTokenRequestState() { - if (RequestTokenUrl.IsNullOrBlank()) + if (this.RequestTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify a request token URL"); } - if (ConsumerKey.IsNullOrBlank()) + if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } - if (ConsumerSecret.IsNullOrBlank()) + if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } @@ -300,22 +301,22 @@ private void ValidateTokenRequestState() private void ValidateAccessRequestState() { - if (AccessTokenUrl.IsNullOrBlank()) + if (this.AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } - if (ConsumerKey.IsNullOrBlank()) + if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } - if (ConsumerSecret.IsNullOrBlank()) + if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } - if (Token.IsNullOrBlank()) + if (this.Token.IsNullOrBlank()) { throw new ArgumentException("You must specify a token"); } @@ -323,22 +324,22 @@ private void ValidateAccessRequestState() private void ValidateClientAuthAccessRequestState() { - if (AccessTokenUrl.IsNullOrBlank()) + if (this.AccessTokenUrl.IsNullOrBlank()) { throw new ArgumentException("You must specify an access token URL"); } - if (ConsumerKey.IsNullOrBlank()) + if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } - if (ConsumerSecret.IsNullOrBlank()) + if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } - if (ClientUsername.IsNullOrBlank() || ClientPassword.IsNullOrBlank()) + if (this.ClientUsername.IsNullOrBlank() || this.ClientPassword.IsNullOrBlank()) { throw new ArgumentException("You must specify user credentials"); } @@ -346,12 +347,12 @@ private void ValidateClientAuthAccessRequestState() private void ValidateProtectedResourceState() { - if (ConsumerKey.IsNullOrBlank()) + if (this.ConsumerKey.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer key"); } - if (ConsumerSecret.IsNullOrBlank()) + if (this.ConsumerSecret.IsNullOrBlank()) { throw new ArgumentException("You must specify a consumer secret"); } @@ -359,36 +360,36 @@ private void ValidateProtectedResourceState() private void AddAuthParameters(ICollection parameters, string timestamp, string nonce) { - var authParameters = new WebParameterCollection + WebParameterCollection authParameters = new WebParameterCollection + { + new WebPair("oauth_consumer_key", this.ConsumerKey), + new WebPair("oauth_nonce", nonce), + new WebPair("oauth_signature_method", this.SignatureMethod.ToRequestValue()), + new WebPair("oauth_timestamp", timestamp), + new WebPair("oauth_version", this.Version ?? "1.0") + }; + + if (!this.Token.IsNullOrBlank()) { - new WebPair("oauth_consumer_key", ConsumerKey), - new WebPair("oauth_nonce", nonce), - new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()), - new WebPair("oauth_timestamp", timestamp), - new WebPair("oauth_version", Version ?? "1.0") - }; - - if (!Token.IsNullOrBlank()) - { - authParameters.Add(new WebPair("oauth_token", Token)); + authParameters.Add(new WebPair("oauth_token", this.Token)); } - if (!CallbackUrl.IsNullOrBlank()) + if (!this.CallbackUrl.IsNullOrBlank()) { - authParameters.Add(new WebPair("oauth_callback", CallbackUrl)); + authParameters.Add(new WebPair("oauth_callback", this.CallbackUrl)); } - if (!Verifier.IsNullOrBlank()) + if (!this.Verifier.IsNullOrBlank()) { - authParameters.Add(new WebPair("oauth_verifier", Verifier)); + authParameters.Add(new WebPair("oauth_verifier", this.Verifier)); } - if (!SessionHandle.IsNullOrBlank()) + if (!this.SessionHandle.IsNullOrBlank()) { - authParameters.Add(new WebPair("oauth_session_handle", SessionHandle)); + authParameters.Add(new WebPair("oauth_session_handle", this.SessionHandle)); } - foreach (var authParameter in authParameters) + foreach (WebPair authParameter in authParameters) { parameters.Add(authParameter); } @@ -396,19 +397,19 @@ private void AddAuthParameters(ICollection parameters, string timestamp private void AddXAuthParameters(ICollection parameters, string timestamp, string nonce) { - var authParameters = new WebParameterCollection - { - new WebPair("x_auth_username", ClientUsername), - new WebPair("x_auth_password", ClientPassword), - new WebPair("x_auth_mode", "client_auth"), - new WebPair("oauth_consumer_key", ConsumerKey), - new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()), - new WebPair("oauth_timestamp", timestamp), - new WebPair("oauth_nonce", nonce), - new WebPair("oauth_version", Version ?? "1.0") - }; - - foreach (var authParameter in authParameters) + WebParameterCollection authParameters = new WebParameterCollection + { + new WebPair("x_auth_username", this.ClientUsername), + new WebPair("x_auth_password", this.ClientPassword), + new WebPair("x_auth_mode", "client_auth"), + new WebPair("oauth_consumer_key", this.ConsumerKey), + new WebPair("oauth_signature_method", this.SignatureMethod.ToRequestValue()), + new WebPair("oauth_timestamp", timestamp), + new WebPair("oauth_nonce", nonce), + new WebPair("oauth_version", this.Version ?? "1.0") + }; + + foreach (WebPair authParameter in authParameters) { parameters.Add(authParameter); } diff --git a/RestSharp/Authenticators/OAuth/WebPair.cs b/RestSharp/Authenticators/OAuth/WebPair.cs index 3ba6480d5..8a943c27d 100644 --- a/RestSharp/Authenticators/OAuth/WebPair.cs +++ b/RestSharp/Authenticators/OAuth/WebPair.cs @@ -1,11 +1,12 @@ -namespace RestSharp.Authenticators.OAuth + +namespace RestSharp.Authenticators.OAuth { internal class WebPair { public WebPair(string name, string value) { - Name = name; - Value = value; + this.Name = name; + this.Value = value; } public string Value { get; set; } diff --git a/RestSharp/Authenticators/OAuth/WebPairCollection.cs b/RestSharp/Authenticators/OAuth/WebPairCollection.cs index f53ccc31e..18466819b 100644 --- a/RestSharp/Authenticators/OAuth/WebPairCollection.cs +++ b/RestSharp/Authenticators/OAuth/WebPairCollection.cs @@ -8,7 +8,7 @@ namespace RestSharp.Authenticators.OAuth { internal class WebPairCollection : IList { - private IList _parameters; + private List parameters; public virtual WebPair this[string name] { @@ -17,178 +17,163 @@ public virtual WebPair this[string name] public virtual IEnumerable Names { - get { return _parameters.Select(p => p.Name); } + get { return this.parameters.Select(p => p.Name); } } public virtual IEnumerable Values { - get { return _parameters.Select(p => p.Value); } + get { return this.parameters.Select(p => p.Value); } } public WebPairCollection(IEnumerable parameters) { - _parameters = new List(parameters); + this.parameters = new List(parameters); } -#if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC +#if !WINDOWS_PHONE && !SILVERLIGHT public WebPairCollection(NameValueCollection collection) : this() { - AddCollection(collection); + this.AddCollection(collection); } public virtual void AddRange(NameValueCollection collection) { - AddCollection(collection); + this.AddCollection(collection); } private void AddCollection(NameValueCollection collection) { - var parameters = collection.AllKeys.Select(key => new WebPair(key, collection[key])); - foreach (var parameter in parameters) - { - _parameters.Add(parameter); - } + this.parameters.AddRange(collection.AllKeys.Select(key => new WebPair(key, collection[key]))); } #endif public WebPairCollection(IDictionary collection) : this() { - AddCollection(collection); + this.AddCollection(collection); } public void AddCollection(IDictionary collection) { - foreach (var key in collection.Keys) - { - var parameter = new WebPair(key, collection[key]); - _parameters.Add(parameter); - } + this.parameters.AddRange(collection.Keys.Select(key => new WebPair(key, collection[key]))); } public WebPairCollection() { - _parameters = new List(0); + this.parameters = new List(0); } public WebPairCollection(int capacity) { - _parameters = new List(capacity); + this.parameters = new List(capacity); } private void AddCollection(IEnumerable collection) { - foreach (var parameter in collection) - { - var pair = new WebPair(parameter.Name, parameter.Value); - _parameters.Add(pair); - } + this.parameters.AddRange(collection.Select(parameter => new WebPair(parameter.Name, parameter.Value))); } public virtual void AddRange(WebPairCollection collection) { - AddCollection(collection); + this.AddCollection(collection); } public virtual void AddRange(IEnumerable collection) { - AddCollection(collection); + this.AddCollection(collection); } public virtual void Sort(Comparison comparison) { - var sorted = new List(_parameters); + List sorted = new List(this.parameters); + sorted.Sort(comparison); - _parameters = sorted; + + this.parameters = sorted; } - public virtual bool RemoveAll(IEnumerable parameters) + public virtual bool RemoveAll(IEnumerable parametersToRemove) { - var success = true; - var array = parameters.ToArray(); - - for (var p = 0; p < array.Length; p++) - { - var parameter = array[p]; - success &= _parameters.Remove(parameter); - } + WebPair[] array = parametersToRemove.ToArray(); + bool success = array.Aggregate(true, (current, parameter) => current & this.parameters.Remove(parameter)); return success && array.Length > 0; } public virtual void Add(string name, string value) { - var pair = new WebPair(name, value); - _parameters.Add(pair); + WebPair pair = new WebPair(name, value); + + this.parameters.Add(pair); } #region IList Members public virtual IEnumerator GetEnumerator() { - return _parameters.GetEnumerator(); + return this.parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } public virtual void Add(WebPair parameter) { - _parameters.Add(parameter); + this.parameters.Add(parameter); } public virtual void Clear() { - _parameters.Clear(); + this.parameters.Clear(); } public virtual bool Contains(WebPair parameter) { - return _parameters.Contains(parameter); + return this.parameters.Contains(parameter); } - public virtual void CopyTo(WebPair[] parameters, int arrayIndex) + public virtual void CopyTo(WebPair[] parametersArray, int arrayIndex) { - _parameters.CopyTo(parameters, arrayIndex); + this.parameters.CopyTo(parametersArray, arrayIndex); } public virtual bool Remove(WebPair parameter) { - return _parameters.Remove(parameter); + return this.parameters.Remove(parameter); } public virtual int Count { - get { return _parameters.Count; } + get { return this.parameters.Count; } } public virtual bool IsReadOnly { - get { return _parameters.IsReadOnly; } + get { return false; } } public virtual int IndexOf(WebPair parameter) { - return _parameters.IndexOf(parameter); + return this.parameters.IndexOf(parameter); } public virtual void Insert(int index, WebPair parameter) { - _parameters.Insert(index, parameter); + this.parameters.Insert(index, parameter); } public virtual void RemoveAt(int index) { - _parameters.RemoveAt(index); + this.parameters.RemoveAt(index); } public virtual WebPair this[int index] { - get { return _parameters[index]; } - set { _parameters[index] = value; } + get { return this.parameters[index]; } + set { this.parameters[index] = value; } } #endregion diff --git a/RestSharp/Authenticators/OAuth/WebParameter.cs b/RestSharp/Authenticators/OAuth/WebParameter.cs index 253a6ab01..a56c2ecb6 100644 --- a/RestSharp/Authenticators/OAuth/WebParameter.cs +++ b/RestSharp/Authenticators/OAuth/WebParameter.cs @@ -1,14 +1,8 @@ -#if !Smartphone using System; -using System.Diagnostics; -#endif namespace RestSharp.Authenticators.OAuth { -#if !Smartphone && !PocketPC - [DebuggerDisplay("{Name}:{Value}")] -#endif -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC +#if !SILVERLIGHT && !WINDOWS_PHONE [Serializable] #endif internal class WebParameter : WebPair diff --git a/RestSharp/Authenticators/OAuth/WebParameterCollection.cs b/RestSharp/Authenticators/OAuth/WebParameterCollection.cs index 504bc2886..373a991e7 100644 --- a/RestSharp/Authenticators/OAuth/WebParameterCollection.cs +++ b/RestSharp/Authenticators/OAuth/WebParameterCollection.cs @@ -8,22 +8,22 @@ internal class WebParameterCollection : WebPairCollection public WebParameterCollection(IEnumerable parameters) : base(parameters) { } -#if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC +#if !WINDOWS_PHONE && !SILVERLIGHT public WebParameterCollection(NameValueCollection collection) : base(collection) { } #endif public WebParameterCollection() { } - public WebParameterCollection(int capacity) - : base(capacity) { } + public WebParameterCollection(int capacity) : base(capacity) { } public WebParameterCollection(IDictionary collection) : base(collection) { } public override void Add(string name, string value) { - var parameter = new WebParameter(name, value); + WebParameter parameter = new WebParameter(name, value); + base.Add(parameter); } } diff --git a/RestSharp/Authenticators/OAuth1Authenticator.cs b/RestSharp/Authenticators/OAuth1Authenticator.cs index 0b31af8cd..c5ef563a4 100644 --- a/RestSharp/Authenticators/OAuth1Authenticator.cs +++ b/RestSharp/Authenticators/OAuth1Authenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,20 +13,28 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; +using System.Collections.Generic; using System.Linq; using System.Text; using RestSharp.Authenticators.OAuth; using RestSharp.Authenticators.OAuth.Extensions; +#if !SILVERLIGHT && !WINDOWS_PHONE +using RestSharp.Extensions.MonoHttp; + +#endif #if WINDOWS_PHONE using System.Net; -#elif SILVERLIGHT +#endif + +#if SILVERLIGHT using System.Windows.Browser; #else -using RestSharp.Contrib; + #endif namespace RestSharp.Authenticators @@ -65,139 +74,150 @@ public class OAuth1Authenticator : IAuthenticator public static OAuth1Authenticator ForRequestToken(string consumerKey, string consumerSecret) { - var authenticator = new OAuth1Authenticator - { - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - SignatureTreatment = OAuthSignatureTreatment.Escaped, - ConsumerKey = consumerKey, - ConsumerSecret = consumerSecret, - Type = OAuthType.RequestToken - }; + OAuth1Authenticator authenticator = new OAuth1Authenticator + { + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + SignatureTreatment = OAuthSignatureTreatment.Escaped, + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + Type = OAuthType.RequestToken + }; + return authenticator; } public static OAuth1Authenticator ForRequestToken(string consumerKey, string consumerSecret, string callbackUrl) { - var authenticator = ForRequestToken(consumerKey, consumerSecret); + OAuth1Authenticator authenticator = ForRequestToken(consumerKey, consumerSecret); + authenticator.CallbackUrl = callbackUrl; + return authenticator; } public static OAuth1Authenticator ForAccessToken(string consumerKey, string consumerSecret, string token, string tokenSecret) { - var authenticator = new OAuth1Authenticator - { - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - SignatureTreatment = OAuthSignatureTreatment.Escaped, - ConsumerKey = consumerKey, - ConsumerSecret = consumerSecret, - Token = token, - TokenSecret = tokenSecret, - Type = OAuthType.AccessToken - }; + OAuth1Authenticator authenticator = new OAuth1Authenticator + { + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + SignatureTreatment = OAuthSignatureTreatment.Escaped, + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + Token = token, + TokenSecret = tokenSecret, + Type = OAuthType.AccessToken + }; + return authenticator; } public static OAuth1Authenticator ForAccessToken(string consumerKey, string consumerSecret, string token, string tokenSecret, string verifier) { - var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + OAuth1Authenticator authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + authenticator.Verifier = verifier; + return authenticator; } public static OAuth1Authenticator ForAccessTokenRefresh(string consumerKey, string consumerSecret, string token, string tokenSecret, string sessionHandle) { - var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + OAuth1Authenticator authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + authenticator.SessionHandle = sessionHandle; + return authenticator; } public static OAuth1Authenticator ForAccessTokenRefresh(string consumerKey, string consumerSecret, string token, string tokenSecret, string verifier, string sessionHandle) { - var authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + OAuth1Authenticator authenticator = ForAccessToken(consumerKey, consumerSecret, token, tokenSecret); + authenticator.SessionHandle = sessionHandle; authenticator.Verifier = verifier; + return authenticator; } public static OAuth1Authenticator ForClientAuthentication(string consumerKey, string consumerSecret, string username, string password) { - var authenticator = new OAuth1Authenticator - { - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - SignatureTreatment = OAuthSignatureTreatment.Escaped, - ConsumerKey = consumerKey, - ConsumerSecret = consumerSecret, - ClientUsername = username, - ClientPassword = password, - Type = OAuthType.ClientAuthentication - }; + OAuth1Authenticator authenticator = new OAuth1Authenticator + { + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + SignatureTreatment = OAuthSignatureTreatment.Escaped, + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + ClientUsername = username, + ClientPassword = password, + Type = OAuthType.ClientAuthentication + }; + return authenticator; } public static OAuth1Authenticator ForProtectedResource(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret) { - var authenticator = new OAuth1Authenticator - { - Type = OAuthType.ProtectedResource, - ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, - SignatureMethod = OAuthSignatureMethod.HmacSha1, - SignatureTreatment = OAuthSignatureTreatment.Escaped, - ConsumerKey = consumerKey, - ConsumerSecret = consumerSecret, - Token = accessToken, - TokenSecret = accessTokenSecret - }; + OAuth1Authenticator authenticator = new OAuth1Authenticator + { + Type = OAuthType.ProtectedResource, + ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, + SignatureMethod = OAuthSignatureMethod.HmacSha1, + SignatureTreatment = OAuthSignatureTreatment.Escaped, + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + Token = accessToken, + TokenSecret = accessTokenSecret + }; + return authenticator; } public void Authenticate(IRestClient client, IRestRequest request) { - var workflow = new OAuthWorkflow - { - ConsumerKey = ConsumerKey, - ConsumerSecret = ConsumerSecret, - ParameterHandling = ParameterHandling, - SignatureMethod = SignatureMethod, - SignatureTreatment = SignatureTreatment, - Verifier = Verifier, - Version = Version, - CallbackUrl = CallbackUrl, - SessionHandle = SessionHandle, - Token = Token, - TokenSecret = TokenSecret, - ClientUsername = ClientUsername, - ClientPassword = ClientPassword - }; - - AddOAuthData(client, request, workflow); + OAuthWorkflow workflow = new OAuthWorkflow + { + ConsumerKey = this.ConsumerKey, + ConsumerSecret = this.ConsumerSecret, + ParameterHandling = this.ParameterHandling, + SignatureMethod = this.SignatureMethod, + SignatureTreatment = this.SignatureTreatment, + Verifier = this.Verifier, + Version = this.Version, + CallbackUrl = this.CallbackUrl, + SessionHandle = this.SessionHandle, + Token = this.Token, + TokenSecret = this.TokenSecret, + ClientUsername = this.ClientUsername, + ClientPassword = this.ClientPassword + }; + + this.AddOAuthData(client, request, workflow); } private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow) { - var url = client.BuildUri(request).ToString(); - var queryStringStart = url.IndexOf('?'); + string url = client.BuildUri(request) + .ToString(); + int queryStringStart = url.IndexOf('?'); if (queryStringStart != -1) + { url = url.Substring(0, queryStringStart); + } OAuthWebQueryInfo oauth; -#if PocketPC - var method = request.Method.ToString().ToUpper(); -#else - var method = request.Method.ToString().ToUpperInvariant(); -#endif - - var parameters = new WebParameterCollection(); + string method = request.Method.ToString() + .ToUpperInvariant(); + WebParameterCollection parameters = new WebParameterCollection(); // include all GET and POST parameters before generating the signature // according to the RFC 5849 - The OAuth 1.0 Protocol @@ -206,33 +226,34 @@ private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflo // or implement a seperate class for each OAuth version if (!request.AlwaysMultipartFormData && !request.Files.Any()) { - foreach (var p in client.DefaultParameters.Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)) - { - parameters.Add(new WebPair(p.Name, p.Value.ToString())); - } - - foreach (var p in request.Parameters.Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString)) - { - parameters.Add(new WebPair(p.Name, p.Value.ToString())); - } + parameters.AddRange( + client.DefaultParameters + .Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) + .Select(p => new WebPair(p.Name, p.Value.ToString()))); + + parameters.AddRange( + request.Parameters + .Where(p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) + .Select(p => new WebPair(p.Name, p.Value.ToString()))); } else { // if we are sending a multipart request, only the "oauth_" parameters should be included in the signature - foreach (var p in client.DefaultParameters.Where( - p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) && p.Name.StartsWith("oauth_"))) - { - parameters.Add(new WebPair(p.Name, p.Value.ToString())); - } - - foreach (var p in request.Parameters.Where( - p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) && p.Name.StartsWith("oauth_"))) - { - parameters.Add(new WebPair(p.Name, p.Value.ToString())); - } + + parameters.AddRange( + client.DefaultParameters + .Where(p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) + && p.Name.StartsWith("oauth_")) + .Select(p => new WebPair(p.Name, p.Value.ToString()))); + + parameters.AddRange( + request.Parameters + .Where(p => (p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString) + && p.Name.StartsWith("oauth_")) + .Select(p => new WebPair(p.Name, p.Value.ToString()))); } - switch (Type) + switch (this.Type) { case OAuthType.RequestToken: workflow.RequestTokenUrl = url; @@ -257,22 +278,23 @@ private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflo throw new ArgumentOutOfRangeException(); } - switch (ParameterHandling) + switch (this.ParameterHandling) { case OAuthParameterHandling.HttpAuthorizationHeader: parameters.Add("oauth_signature", oauth.Signature); - request.AddHeader("Authorization", GetAuthorizationHeader(parameters)); + request.AddHeader("Authorization", this.GetAuthorizationHeader(parameters)); break; case OAuthParameterHandling.UrlOrPostParameters: parameters.Add("oauth_signature", oauth.Signature); - - foreach (var parameter in parameters.Where(parameter => - !parameter.Name.IsNullOrBlank() && - (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_")))) - { - request.AddParameter(parameter.Name, HttpUtility.UrlDecode(parameter.Value)); - } + request.Parameters.AddRange( + parameters.Where(p => !p.Name.IsNullOrBlank() && + (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_"))) + .Select(p => new Parameter + { + Name = p.Name, + Value = HttpUtility.UrlDecode(p.Value) + })); break; default: @@ -282,30 +304,35 @@ private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflo private string GetAuthorizationHeader(WebPairCollection parameters) { - var sb = new StringBuilder("OAuth "); + StringBuilder sb = new StringBuilder("OAuth "); - if (!Realm.IsNullOrBlank()) + if (!this.Realm.IsNullOrBlank()) { - sb.Append("realm=\"{0}\",".FormatWith(OAuthTools.UrlEncodeRelaxed(Realm))); + sb.Append("realm=\"{0}\",".FormatWith(OAuthTools.UrlEncodeRelaxed(this.Realm))); } parameters.Sort((l, r) => l.Name.CompareTo(r.Name)); - var parameterCount = 0; - var oathParameters = parameters.Where(parameter => - !parameter.Name.IsNullOrBlank() && - !parameter.Value.IsNullOrBlank() && - (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_")) - ).ToList(); + int parameterCount = 0; + List oathParameters = + parameters.Where(p => !p.Name.IsNullOrBlank() && + !p.Value.IsNullOrBlank() && + (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_"))) + .ToList(); - foreach (var parameter in oathParameters) + foreach (WebPair parameter in oathParameters) { parameterCount++; - var format = parameterCount < oathParameters.Count ? "{0}=\"{1}\"," : "{0}=\"{1}\""; + + string format = parameterCount < oathParameters.Count + ? "{0}=\"{1}\"," + : "{0}=\"{1}\""; + sb.Append(format.FormatWith(parameter.Name, parameter.Value)); } - var authorization = sb.ToString(); + string authorization = sb.ToString(); + return authorization; } } diff --git a/RestSharp/Authenticators/OAuth2Authenticator.cs b/RestSharp/Authenticators/OAuth2Authenticator.cs index d0658cd90..980679d4c 100644 --- a/RestSharp/Authenticators/OAuth2Authenticator.cs +++ b/RestSharp/Authenticators/OAuth2Authenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,12 +13,13 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Linq; -namespace RestSharp +namespace RestSharp.Authenticators { /// /// Base class for OAuth 2 Authenticators. @@ -35,7 +37,7 @@ public abstract class OAuth2Authenticator : IAuthenticator /// /// Access token to be used when authenticating. /// - private readonly string _accessToken; + private readonly string accessToken; /// /// Initializes a new instance of the class. @@ -45,7 +47,7 @@ public abstract class OAuth2Authenticator : IAuthenticator /// protected OAuth2Authenticator(string accessToken) { - _accessToken = accessToken; + this.accessToken = accessToken; } /// @@ -53,7 +55,7 @@ protected OAuth2Authenticator(string accessToken) /// public string AccessToken { - get { return _accessToken; } + get { return this.accessToken; } } public abstract void Authenticate(IRestClient client, IRestRequest request); @@ -93,7 +95,7 @@ public class OAuth2AuthorizationRequestHeaderAuthenticator : OAuth2Authenticator /// /// Stores the Authorization header value as "[tokenType] accessToken". used for performance. /// - private readonly string _authorizationValue; + private readonly string authorizationValue; /// /// Initializes a new instance of the class. @@ -117,7 +119,7 @@ public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken, string : base(accessToken) { // Conatenate during constructor so that it is only done once. can improve performance. - _authorizationValue = tokenType + " " + accessToken; + this.authorizationValue = tokenType + " " + accessToken; } public override void Authenticate(IRestClient client, IRestRequest request) @@ -125,7 +127,7 @@ public override void Authenticate(IRestClient client, IRestRequest request) // only add the Authorization parameter if it hasn't been added. if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase))) { - request.AddParameter("Authorization", _authorizationValue, ParameterType.HttpHeader); + request.AddParameter("Authorization", this.authorizationValue, ParameterType.HttpHeader); } } } diff --git a/RestSharp/Authenticators/SimpleAuthenticator.cs b/RestSharp/Authenticators/SimpleAuthenticator.cs index 72050fb59..a257fa4ff 100644 --- a/RestSharp/Authenticators/SimpleAuthenticator.cs +++ b/RestSharp/Authenticators/SimpleAuthenticator.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,29 +13,33 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion -namespace RestSharp +namespace RestSharp.Authenticators { public class SimpleAuthenticator : IAuthenticator { - private readonly string _usernameKey; - private readonly string _username; - private readonly string _passwordKey; - private readonly string _password; + private readonly string usernameKey; + + private readonly string username; + + private readonly string passwordKey; + + private readonly string password; public SimpleAuthenticator(string usernameKey, string username, string passwordKey, string password) { - _usernameKey = usernameKey; - _username = username; - _passwordKey = passwordKey; - _password = password; + this.usernameKey = usernameKey; + this.username = username; + this.passwordKey = passwordKey; + this.password = password; } public void Authenticate(IRestClient client, IRestRequest request) { - request.AddParameter(_usernameKey, _username); - request.AddParameter(_passwordKey, _password); + request.AddParameter(this.usernameKey, this.username); + request.AddParameter(this.passwordKey, this.password); } } } diff --git a/RestSharp/Compression/ZLib/Crc32.cs b/RestSharp/Compression/ZLib/Crc32.cs index 459885078..9cd676ffc 100644 --- a/RestSharp/Compression/ZLib/Crc32.cs +++ b/RestSharp/Compression/ZLib/Crc32.cs @@ -32,10 +32,11 @@ // // ------------------------------------------------------------------ + #if WINDOWS_PHONE using System; -using Interop = System.Runtime.InteropServices; +using System.IO; namespace RestSharp.Compression.ZLib { @@ -45,29 +46,60 @@ namespace RestSharp.Compression.ZLib /// directly by applications wishing to create, read, or manipulate zip archive /// files. /// - internal class CRC32 + internal class Crc32 { - /// - /// indicates the total number of bytes read on the CRC stream. - /// This is used when writing the ZipDirEntry when compressing files. - /// - public Int64 TotalBytesRead + // private member vars + private static readonly uint[] crc32Table; + private const int BUFFER_SIZE = 8192; + private uint runningCrc32Result = 0xFFFFFFFF; + + // pre-initialize the crc table for speed of lookup. + static Crc32() { - get + unchecked { - return _TotalBytesRead; + // This is the official polynomial used by CRC32 in PKZip. + // Often the polynomial is shown reversed as 0x04C11DB7. + const uint dwPolynomial = 0xEDB88320; + + crc32Table = new uint[256]; + + for (uint i = 0; i < 256; i++) + { + uint dwCrc = i; + + for (uint j = 8; j > 0; j--) + { + if ((dwCrc & 1) == 1) + { + dwCrc = (dwCrc >> 1) ^ dwPolynomial; + } + else + { + dwCrc >>= 1; + } + } + + crc32Table[i] = dwCrc; + } } } + /// + /// indicates the total number of bytes read on the CRC stream. + /// This is used when writing the ZipDirEntry when compressing files. + /// + public long TotalBytesRead { get; private set; } + /// /// Indicates the current CRC for all blocks slurped in. /// - public Int32 Crc32Result + public int Crc32Result { get { // return one's complement of the running result - return unchecked((Int32)(~_RunningCrc32Result)); + return unchecked((int) (~this.runningCrc32Result)); } } @@ -76,9 +108,9 @@ public Int32 Crc32Result /// /// The stream over which to calculate the CRC32 /// the CRC32 calculation - public Int32 GetCrc32(System.IO.Stream input) + public int GetCrc32(Stream input) { - return GetCrc32AndCopy(input, null); + return this.GetCrc32AndCopy(input, null); } /// @@ -88,7 +120,7 @@ public Int32 GetCrc32(System.IO.Stream input) /// The stream over which to calculate the CRC32 /// The stream into which to deflate the input /// the CRC32 calculation - public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) + public int GetCrc32AndCopy(Stream input, Stream output) { if (input == null) throw new ZlibException("The input stream must not be null."); @@ -98,21 +130,28 @@ public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) //UInt32 crc32Result; //crc32Result = 0xFFFFFFFF; byte[] buffer = new byte[BUFFER_SIZE]; - int readSize = BUFFER_SIZE; + const int readSize = BUFFER_SIZE; - _TotalBytesRead = 0; + this.TotalBytesRead = 0; int count = input.Read(buffer, 0, readSize); - if (output != null) output.Write(buffer, 0, count); - _TotalBytesRead += count; + + if (output != null) + output.Write(buffer, 0, count); + + this.TotalBytesRead += count; + while (count > 0) { - SlurpBlock(buffer, 0, count); + this.SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); - if (output != null) output.Write(buffer, 0, count); - _TotalBytesRead += count; + + if (output != null) + output.Write(buffer, 0, count); + + this.TotalBytesRead += count; } - return (Int32)(~_RunningCrc32Result); + return (int) (~this.runningCrc32Result); } } @@ -120,17 +159,17 @@ public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) /// Get the CRC32 for the given (word,byte) combo. This is a computation /// defined by PKzip. /// - /// The word to start with. - /// The byte to combine it with. + /// The word to start with. + /// The byte to combine it with. /// The CRC-ized result. - public Int32 ComputeCrc32(Int32 W, byte B) + public int ComputeCrc32(int w, byte b) { - return _InternalComputeCrc32((UInt32)W, B); + return this.InternalComputeCrc32((uint) w, b); } - internal Int32 _InternalComputeCrc32(UInt32 W, byte B) + internal int InternalComputeCrc32(uint w, byte b) { - return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); + return (int) (crc32Table[(w ^ b) & 0xFF] ^ (w >> 8)); } /// @@ -148,53 +187,12 @@ public void SlurpBlock(byte[] block, int offset, int count) for (int i = 0; i < count; i++) { int x = offset + i; - _RunningCrc32Result = ((_RunningCrc32Result) >> 8) ^ crc32Table[(block[x]) ^ ((_RunningCrc32Result) & 0x000000FF)]; - } - - _TotalBytesRead += count; - } - - - // pre-initialize the crc table for speed of lookup. - static CRC32() - { - unchecked - { - // This is the official polynomial used by CRC32 in PKZip. - // Often the polynomial is shown reversed as 0x04C11DB7. - UInt32 dwPolynomial = 0xEDB88320; - UInt32 i, j; - crc32Table = new UInt32[256]; - - UInt32 dwCrc; - - for (i = 0; i < 256; i++) - { - dwCrc = i; - - for (j = 8; j > 0; j--) - { - if ((dwCrc & 1) == 1) - { - dwCrc = (dwCrc >> 1) ^ dwPolynomial; - } - else - { - dwCrc >>= 1; - } - } - - crc32Table[i] = dwCrc; - } + this.runningCrc32Result = ((this.runningCrc32Result) >> 8) ^ crc32Table[(block[x]) ^ ((this.runningCrc32Result) & 0x000000FF)]; } - } - // private member vars - private Int64 _TotalBytesRead; - private static UInt32[] crc32Table; - private const int BUFFER_SIZE = 8192; - private UInt32 _RunningCrc32Result = 0xFFFFFFFF; + this.TotalBytesRead += count; + } } /// @@ -216,27 +214,13 @@ static CRC32() /// DotNetZip library. /// /// - internal class CrcCalculatorStream : System.IO.Stream, System.IDisposable + internal class CrcCalculatorStream : Stream, IDisposable { - private static readonly Int64 UnsetLengthLimit = -99; + private const long UNSET_LENGTH_LIMIT = -99; - private System.IO.Stream _innerStream; - private CRC32 _Crc32; - private Int64 _lengthLimit = -99; - private bool _leaveOpen; - - /// - /// Gets the total number of bytes run through the CRC32 calculator. - /// - /// - /// - /// This is either the total number of bytes read, or the total number of bytes - /// written, depending on the direction of this stream. - /// - public Int64 TotalBytesSlurped - { - get { return _Crc32.TotalBytesRead; } - } + private readonly Stream innerStream; + private readonly Crc32 crc32; + private readonly long lengthLimit; /// /// The default constructor. @@ -246,8 +230,8 @@ public Int64 TotalBytesSlurped /// open upon Close(). /// /// The underlying stream - public CrcCalculatorStream(System.IO.Stream stream) - : this(true, CrcCalculatorStream.UnsetLengthLimit, stream) { } + public CrcCalculatorStream(Stream stream) + : this(true, UNSET_LENGTH_LIMIT, stream) { } /// /// The constructor allows the caller to specify how to handle the underlying @@ -256,8 +240,8 @@ public CrcCalculatorStream(System.IO.Stream stream) /// The underlying stream /// true to leave the underlying stream /// open upon close of the CrcCalculatorStream.; false otherwise. - public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen) - : this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream) { } + public CrcCalculatorStream(Stream stream, bool leaveOpen) + : this(leaveOpen, UNSET_LENGTH_LIMIT, stream) { } /// /// A constructor allowing the specification of the length of the stream to read. @@ -268,7 +252,7 @@ public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen) /// /// The underlying stream /// The length of the stream to slurp - public CrcCalculatorStream(System.IO.Stream stream, Int64 length) + public CrcCalculatorStream(Stream stream, long length) : this(true, length, stream) { if (length < 0) @@ -283,7 +267,7 @@ public CrcCalculatorStream(System.IO.Stream stream, Int64 length) /// The length of the stream to slurp /// true to leave the underlying stream /// open upon close of the CrcCalculatorStream.; false otherwise. - public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen) + public CrcCalculatorStream(Stream stream, long length, bool leaveOpen) : this(leaveOpen, length, stream) { if (length < 0) @@ -296,32 +280,34 @@ public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen // is no length set. So we validate the length limit in those ctors that use an // explicit param, otherwise we don't validate, because it could be our special // value. - private CrcCalculatorStream(bool leaveOpen, Int64 length, System.IO.Stream stream) - : base() + private CrcCalculatorStream(bool leaveOpen, long length, Stream stream) { - _innerStream = stream; - _Crc32 = new CRC32(); - _lengthLimit = length; - _leaveOpen = leaveOpen; + this.innerStream = stream; + this.crc32 = new Crc32(); + this.lengthLimit = length; + this.LeaveOpen = leaveOpen; } + /// + /// Gets the total number of bytes run through the CRC32 calculator. + /// + /// + /// + /// This is either the total number of bytes read, or the total number of bytes + /// written, depending on the direction of this stream. + /// + public long TotalBytesSlurped { get { return this.crc32.TotalBytesRead; } } + /// /// Provides the current CRC for all blocks slurped in. /// - public Int32 Crc - { - get { return _Crc32.Crc32Result; } - } + public int Crc { get { return this.crc32.Crc32Result; } } /// /// Indicates whether the underlying stream will be left open when the /// CrcCalculatorStream is Closed. /// - public bool LeaveOpen - { - get { return _leaveOpen; } - set { _leaveOpen = value; } - } + public bool LeaveOpen { get; set; } /// /// Read from the stream @@ -342,17 +328,21 @@ public override int Read(byte[] buffer, int offset, int count) // calling ReadToEnd() on it, We can "over-read" the zip data and get a // corrupt string. The length limits that, prevents that problem. - if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit) + if (this.lengthLimit != UNSET_LENGTH_LIMIT) { - if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF - Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead; - if (bytesRemaining < count) bytesToRead = (int)bytesRemaining; + if (this.crc32.TotalBytesRead >= this.lengthLimit) + return 0; // EOF + + long bytesRemaining = this.lengthLimit - this.crc32.TotalBytesRead; + + if (bytesRemaining < count) + bytesToRead = (int) bytesRemaining; } - int n = _innerStream.Read(buffer, offset, bytesToRead); + int n = this.innerStream.Read(buffer, offset, bytesToRead); if (n > 0) - _Crc32.SlurpBlock(buffer, offset, n); + this.crc32.SlurpBlock(buffer, offset, n); return n; } @@ -366,9 +356,9 @@ public override int Read(byte[] buffer, int offset, int count) public override void Write(byte[] buffer, int offset, int count) { if (count > 0) - _Crc32.SlurpBlock(buffer, offset, count); + this.crc32.SlurpBlock(buffer, offset, count); - _innerStream.Write(buffer, offset, count); + this.innerStream.Write(buffer, offset, count); } /// @@ -376,7 +366,7 @@ public override void Write(byte[] buffer, int offset, int count) /// public override bool CanRead { - get { return _innerStream.CanRead; } + get { return this.innerStream.CanRead; } } /// @@ -384,7 +374,7 @@ public override bool CanRead /// public override bool CanSeek { - get { return _innerStream.CanSeek; } + get { return this.innerStream.CanSeek; } } /// @@ -392,7 +382,7 @@ public override bool CanSeek /// public override bool CanWrite { - get { return _innerStream.CanWrite; } + get { return this.innerStream.CanWrite; } } /// @@ -400,7 +390,7 @@ public override bool CanWrite /// public override void Flush() { - _innerStream.Flush(); + this.innerStream.Flush(); } /// @@ -408,13 +398,7 @@ public override void Flush() /// public override long Length { - get - { - if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit) - return _innerStream.Length; - else - return _lengthLimit; - } + get { return this.lengthLimit == UNSET_LENGTH_LIMIT ? this.innerStream.Length : this.lengthLimit; } } /// @@ -422,7 +406,7 @@ public override long Length /// public override long Position { - get { return _Crc32.TotalBytesRead; } + get { return this.crc32.TotalBytesRead; } set { throw new NotImplementedException(); } } @@ -432,7 +416,7 @@ public override long Position /// N/A /// N/A /// N/A - public override long Seek(long offset, System.IO.SeekOrigin origin) + public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } @@ -446,10 +430,9 @@ public override void SetLength(long value) throw new NotImplementedException(); } - void IDisposable.Dispose() { - Close(); + this.Close(); } /// @@ -459,8 +442,8 @@ public override void Close() { base.Close(); - if (!_leaveOpen) - _innerStream.Close(); + if (!this.LeaveOpen) + this.innerStream.Close(); } } } diff --git a/RestSharp/Compression/ZLib/FlushType.cs b/RestSharp/Compression/ZLib/FlushType.cs index 2a1c9d944..82da56b2d 100644 --- a/RestSharp/Compression/ZLib/FlushType.cs +++ b/RestSharp/Compression/ZLib/FlushType.cs @@ -1,4 +1,5 @@ -#if WINDOWS_PHONE + +#if WINDOWS_PHONE using System; using System.Net; diff --git a/RestSharp/Compression/ZLib/GZipStream.cs b/RestSharp/Compression/ZLib/GZipStream.cs index 491762656..aaaef52c4 100644 --- a/RestSharp/Compression/ZLib/GZipStream.cs +++ b/RestSharp/Compression/ZLib/GZipStream.cs @@ -26,10 +26,12 @@ // // ------------------------------------------------------------------ + #if WINDOWS_PHONE using System; using System.IO; +using System.Text; namespace RestSharp.Compression.ZLib { @@ -73,7 +75,7 @@ namespace RestSharp.Compression.ZLib /// /// /// - internal class GZipStream : System.IO.Stream + internal class GZipStream : Stream { // GZip format // source: http://tools.ietf.org/html/rfc1952 @@ -128,15 +130,15 @@ internal class GZipStream : System.IO.Stream /// property will return null (Nothing in VB). /// /// - public String Comment + public string Comment { - get { return _Comment; } + get { return this.comment; } set { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - _Comment = value; + this.comment = value; } } @@ -157,44 +159,44 @@ public String Comment /// bytestream, the property will return null (Nothing in VB). /// /// - public String FileName + public string FileName { - get { return _FileName; } + get { return this.fileName; } set { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - _FileName = value; + this.fileName = value; - if (_FileName == null) + if (this.fileName == null) return; - if (_FileName.IndexOf("/") != -1) + if (this.fileName.IndexOf("/") != -1) { - _FileName = _FileName.Replace("/", "\\"); + this.fileName = this.fileName.Replace("/", "\\"); } - if (_FileName.EndsWith("\\")) + if (this.fileName.EndsWith("\\")) throw new Exception("Illegal filename"); - if (_FileName.IndexOf("\\") != -1) + if (this.fileName.IndexOf("\\") != -1) { // trim any leading path - _FileName = Path.GetFileName(_FileName); + this.fileName = Path.GetFileName(this.fileName); } } } - /// - /// The last modified time for the GZIP stream. - /// - /// - /// GZIP allows the storage of a last modified time with each GZIP entry. - /// When compressing data, you can set this before the first call to Write(). When - /// decompressing, you can retrieve this value any time after the first call to - /// Read(). - public DateTime? LastModified; + // / + // / The last modified time for the GZIP stream. + // / + // / + // / GZIP allows the storage of a last modified time with each GZIP entry. + // / When compressing data, you can set this before the first call to Write(). When + // / decompressing, you can retrieve this value any time after the first call to + // / Read(). + //public DateTime? LastModified; /// /// The CRC on the GZIP stream. @@ -202,14 +204,13 @@ public String FileName /// /// This is used for internal error checking. You probably don't need to look at this property. /// - public int Crc32 { get { return _Crc32; } } + public int Crc32 { get; private set; } - internal ZlibBaseStream _baseStream; - bool _disposed; - bool _firstReadDone; - string _FileName; - string _Comment; - int _Crc32; + internal ZlibBaseStream BaseStream; + bool disposed; + bool firstReadDone; + string fileName; + string comment; /// /// Create a GZipStream using the specified CompressionMode and the specified CompressionLevel, @@ -273,7 +274,7 @@ public String FileName /// A tuning knob to trade speed for effectiveness. public GZipStream(Stream stream) { - _baseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.GZIP, false); + this.BaseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.Gzip, false); } #region Zlib properties @@ -283,11 +284,13 @@ public GZipStream(Stream stream) /// virtual public FlushType FlushMode { - get { return (this._baseStream._flushMode); } + get { return (this.BaseStream.FlushMode); } set { - if (_disposed) throw new ObjectDisposedException("GZipStream"); - this._baseStream._flushMode = value; + if (this.disposed) + throw new ObjectDisposedException("GZipStream"); + + this.BaseStream.FlushMode = value; } } @@ -309,32 +312,32 @@ virtual public FlushType FlushMode /// public int BufferSize { - get { return this._baseStream._bufferSize; } + get { return this.BaseStream.BufferSize; } set { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - if (this._baseStream._workingBuffer != null) + if (this.BaseStream.workingBuffer != null) throw new ZlibException("The working buffer is already set."); - if (value < ZlibConstants.WorkingBufferSizeMin) - throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", value)); + if (value < ZlibConstants.WORKING_BUFFER_SIZE_MIN) + throw new ZlibException(string.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", value)); - this._baseStream._bufferSize = value; + this.BaseStream.BufferSize = value; } } /// Returns the total number of bytes input so far. virtual public long TotalIn { - get { return this._baseStream._z.TotalBytesIn; } + get { return this.BaseStream.z.TotalBytesIn; } } /// Returns the total number of bytes output so far. virtual public long TotalOut { - get { return this._baseStream._z.TotalBytesOut; } + get { return this.BaseStream.z.TotalBytesOut; } } #endregion @@ -352,15 +355,15 @@ protected override void Dispose(bool disposing) { try { - if (!_disposed) + if (!this.disposed) { - if (disposing && (this._baseStream != null)) + if (disposing && (this.BaseStream != null)) { - this._baseStream.Close(); - this._Crc32 = _baseStream.Crc32; + this.BaseStream.Close(); + this.Crc32 = this.BaseStream.Crc32; } - _disposed = true; + this.disposed = true; } } finally @@ -379,10 +382,10 @@ public override bool CanRead { get { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - return _baseStream._stream.CanRead; + return this.BaseStream.Stream.CanRead; } } @@ -407,10 +410,10 @@ public override bool CanWrite { get { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - return _baseStream._stream.CanWrite; + return this.BaseStream.Stream.CanWrite; } } @@ -419,10 +422,10 @@ public override bool CanWrite /// public override void Flush() { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - _baseStream.Flush(); + this.BaseStream.Flush(); } /// @@ -446,8 +449,8 @@ public override long Position { get { - if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) - return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount; + if (this.BaseStream.streamMode == ZlibBaseStream.StreamMode.Reader) + return this.BaseStream.z.TotalBytesIn + this.BaseStream.GzipHeaderByteCount; return 0; } @@ -485,19 +488,19 @@ public override long Position /// the number of bytes actually read public override int Read(byte[] buffer, int offset, int count) { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("GZipStream"); - int n = _baseStream.Read(buffer, offset, count); + int n = this.BaseStream.Read(buffer, offset, count); // Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n); // Console.WriteLine( Util.FormatByteArray(buffer, offset, n) ); - if (!_firstReadDone) + if (!this.firstReadDone) { - _firstReadDone = true; - FileName = _baseStream._GzipFileName; - Comment = _baseStream._GzipComment; + this.firstReadDone = true; + this.FileName = this.BaseStream.GzipFileName; + this.Comment = this.BaseStream.GzipComment; } return n; @@ -525,75 +528,80 @@ public override void SetLength(long value) #endregion - internal static System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - internal static System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1"); + internal static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + internal static Encoding Iso8859Dash1 = Encoding.GetEncoding("iso-8859-1"); - private int EmitHeader() - { - byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment); - byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName); + //private int EmitHeader() + //{ + // byte[] commentBytes = (Comment == null) ? null : Iso8859Dash1.GetBytes(Comment); + // byte[] filenameBytes = (FileName == null) ? null : Iso8859Dash1.GetBytes(FileName); - int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; - int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; + // int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; + // int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; - int bufferLength = 10 + cbLength + fnLength; - byte[] header = new byte[bufferLength]; - int i = 0; - // ID - header[i++] = 0x1F; - header[i++] = 0x8B; + // int bufferLength = 10 + cbLength + fnLength; + // byte[] header = new byte[bufferLength]; + // int i = 0; - // compression method - header[i++] = 8; - byte flag = 0; + // // ID + // header[i++] = 0x1F; + // header[i++] = 0x8B; - if (Comment != null) - flag ^= 0x10; + // // compression method + // header[i++] = 8; - if (FileName != null) - flag ^= 0x8; + // byte flag = 0; - // flag - header[i++] = flag; + // if (Comment != null) + // flag ^= 0x10; - // mtime - if (!LastModified.HasValue) - LastModified = DateTime.Now; + // if (FileName != null) + // flag ^= 0x8; - System.TimeSpan delta = LastModified.Value - _unixEpoch; - Int32 timet = (Int32)delta.TotalSeconds; - Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); - i += 4; + // // flag + // header[i++] = flag; - // xflg - header[i++] = 0; // this field is totally useless - // OS - header[i++] = 0xFF; // 0xFF == unspecified + // // mtime + // if (!LastModified.HasValue) + // LastModified = DateTime.Now; - // extra field length - only if FEXTRA is set, which it is not. - //header[i++]= 0; - //header[i++]= 0; + // TimeSpan delta = LastModified.Value - UnixEpoch; + // int timet = (int) delta.TotalSeconds; + // Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); - // filename - if (fnLength != 0) - { - Array.Copy(filenameBytes, 0, header, i, fnLength - 1); - i += fnLength - 1; - header[i++] = 0; // terminate - } + // i += 4; - // comment - if (cbLength != 0) - { - Array.Copy(commentBytes, 0, header, i, cbLength - 1); - i += cbLength - 1; - header[i++] = 0; // terminate - } + // // xflg + // header[i++] = 0; // this field is totally useless + // // OS + // header[i++] = 0xFF; // 0xFF == unspecified - _baseStream._stream.Write(header, 0, header.Length); + // // extra field length - only if FEXTRA is set, which it is not. + // //header[i++]= 0; + // //header[i++]= 0; - return header.Length; // bytes written - } + // // filename + // if (fnLength != 0) + // { + // Array.Copy(filenameBytes, 0, header, i, fnLength - 1); + + // i += fnLength - 1; + // header[i++] = 0; // terminate + // } + + // // comment + // if (cbLength != 0) + // { + // Array.Copy(commentBytes, 0, header, i, cbLength - 1); + + // i += cbLength - 1; + // header[i++] = 0; // terminate + // } + + // BaseStream.stream.Write(header, 0, header.Length); + + // return header.Length; // bytes written + //} public override void Write(byte[] buffer, int offset, int count) { diff --git a/RestSharp/Compression/ZLib/InfTree.cs b/RestSharp/Compression/ZLib/InfTree.cs index e7dbb4502..30c9aed5e 100644 --- a/RestSharp/Compression/ZLib/InfTree.cs +++ b/RestSharp/Compression/ZLib/InfTree.cs @@ -59,6 +59,7 @@ // // ----------------------------------------------------------------------- + #if WINDOWS_PHONE using System; @@ -70,49 +71,125 @@ sealed internal class InfTree { private const int MANY = 1440; private const int Z_OK = 0; - private const int Z_STREAM_END = 1; - private const int Z_NEED_DICT = 2; - private const int Z_ERRNO = -1; - private const int Z_STREAM_ERROR = -2; + //private const int Z_STREAM_END = 1; + //private const int Z_NEED_DICT = 2; + //private const int Z_ERRNO = -1; + //private const int Z_STREAM_ERROR = -2; private const int Z_DATA_ERROR = -3; private const int Z_MEM_ERROR = -4; private const int Z_BUF_ERROR = -5; - private const int Z_VERSION_ERROR = -6; - - internal const int fixed_bl = 9; - internal const int fixed_bd = 5; + //private const int Z_VERSION_ERROR = -6; - //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_tl'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] fixed_tl = new int[]{96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, - 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, - 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255}; + internal const int FIXED_BL = 9; + internal const int FIXED_BD = 5; - //UPGRADE_NOTE: Final was removed from the declaration of 'fixed_td'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] fixed_td = new int[] { 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 }; + // UPGRADE_NOTE: Final was removed from the declaration of 'fixed_tl'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] FixedTl = + { + 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, + 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, + 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, + 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, + 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, + 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, + 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, + 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, + 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, + 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, + 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, + 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, + 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, + 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, + 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, + 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, + 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, + 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, + 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, + 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, + 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, + 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, + 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, + 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, + 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, + 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, + 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, + 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, + 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, + 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, + 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, + 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, + 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, + 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, + 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, + 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, + 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, + 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, + 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, + 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, + 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, + 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, + 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, + 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, + 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, + 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, + 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, + 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, + 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, + 0, 8, 143, 0, 8, 79, 0, 9, 255 + }; + + // UPGRADE_NOTE: Final was removed from the declaration of 'fixed_td'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] FixedTd = + { + 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, + 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, + 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, + 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 + }; // Tables for deflate from PKZIP's appnote.txt. - //UPGRADE_NOTE: Final was removed from the declaration of 'cplens'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] cplens = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + // UPGRADE_NOTE: Final was removed from the declaration of 'cplens'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] Cplens = + { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, + 258, 0, 0 + }; // see note #13 above about 258 - //UPGRADE_NOTE: Final was removed from the declaration of 'cplext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] cplext = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 }; + // UPGRADE_NOTE: Final was removed from the declaration of 'cplext'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] Cplext = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 + }; - //UPGRADE_NOTE: Final was removed from the declaration of 'cpdist'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] cpdist = new int[] { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; + // UPGRADE_NOTE: Final was removed from the declaration of 'cpdist'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] Cpdist = + { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577 + }; - //UPGRADE_NOTE: Final was removed from the declaration of 'cpdext'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] cpdext = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + // UPGRADE_NOTE: Final was removed from the declaration of 'cpdext'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + internal static readonly int[] Cpdext = + { + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 + }; // If BMAX needs to be larger than 16, then h and x[] should be uLong. internal const int BMAX = 15; // maximum bit length of any code - internal int[] hn = null; // hufts used in space - internal int[] v = null; // work area for huft_build - internal int[] c = null; // bit length count table - internal int[] r = null; // table entry for structure assignment - internal int[] u = null; // table stack - internal int[] x = null; // bit offsets, then code stack + internal int[] Hn; // hufts used in space + internal int[] V; // work area for huft_build + internal int[] C; // bit length count table + internal int[] R; // table entry for structure assignment + internal int[] U; // table stack + internal int[] X; // bit offsets, then code stack private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) { @@ -122,15 +199,12 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of // lengths), or Z_MEM_ERROR if not enough memory. - int a; // counter for codes of length k - int f; // i repeats in table every f entries int g; // maximum code length int h; // table level int i; // counter, current code int j; // counter int k; // number of bits in current code int l; // bits per table (returned in m) - int mask; // (1 << w) - 1, to avoid cc -O bug on HP int p; // pointer into c[], b[], or v[] int q; // points to current table int w; // bits before this table == (l * h) @@ -145,15 +219,16 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ do { - c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX + this.C[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX } while (i != 0); - if (c[0] == n) + if (this.C[0] == n) { // null input--all zero length codes t[0] = -1; m[0] = 0; + return Z_OK; } @@ -161,8 +236,10 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ l = m[0]; for (j = 1; j <= BMAX; j++) - if (c[j] != 0) + { + if (this.C[j] != 0) break; + } k = j; // minimum code length @@ -173,7 +250,7 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ for (i = BMAX; i != 0; i--) { - if (c[i] != 0) + if (this.C[i] != 0) break; } @@ -189,28 +266,28 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) { - if ((y -= c[j]) < 0) + if ((y -= this.C[j]) < 0) { return Z_DATA_ERROR; } } - if ((y -= c[i]) < 0) + if ((y -= this.C[i]) < 0) { return Z_DATA_ERROR; } - c[i] += y; + this.C[i] += y; // Generate starting offsets into the value table for each length - x[1] = j = 0; + this.X[1] = j = 0; p = 1; xp = 2; while (--i != 0) { // note that i == g from above - x[xp] = (j += c[p]); + this.X[xp] = (j += this.C[p]); xp++; p++; } @@ -223,32 +300,34 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ { if ((j = b[bindex + p]) != 0) { - v[x[j]++] = i; + v[this.X[j]++] = i; } p++; } while (++i < n); - n = x[g]; // set n to length of v + n = this.X[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries - x[0] = i = 0; // first Huffman code is zero + this.X[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = -1; // no tables yet--level -1 w = -l; // bits decoded == (l * h) - u[0] = 0; // just to keep compilers happy + this.U[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { - a = c[k]; + int a = this.C[k]; // counter for codes of length k while (a-- != 0) { // here i is the Huffman code of length k bits for value *p // make tables up to required level + int f; // i repeats in table every f entries + while (k > w + l) { h++; @@ -269,10 +348,10 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ while (++j < z) { // try smaller tables up to z bits - if ((f <<= 1) <= c[++xp]) + if ((f <<= 1) <= this.C[++xp]) break; // enough codes to use up j bits - f -= c[xp]; // else deduct codes from patterns + f -= this.C[xp]; // else deduct codes from patterns } } } @@ -286,18 +365,18 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ return Z_DATA_ERROR; // overflow of MANY } - u[h] = q = hn[0]; // DEBUG + this.U[h] = q = hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if (h != 0) { - x[h] = i; // save pattern for backing up - r[0] = (sbyte)j; // bits in this table - r[1] = (sbyte)l; // bits to dump before this table - j = SharedUtils.URShift(i, (w - l)); - r[2] = (int)(q - u[h - 1] - j); // offset to this table - Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table + this.X[h] = i; // save pattern for backing up + this.R[0] = (sbyte)j; // bits in this table + this.R[1] = (sbyte)l; // bits to dump before this table + j = SharedUtils.UrShift(i, (w - l)); + this.R[2] = q - this.U[h - 1] - j; // offset to this table + Array.Copy(this.R, 0, hp, (this.U[h - 1] + j) * 3, 3); // connect to last table } else { @@ -306,32 +385,33 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ } // set up table entry in r - r[1] = (sbyte)(k - w); + this.R[1] = (sbyte)(k - w); if (p >= n) { - r[0] = 128 + 64; // out of values--invalid code + this.R[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { - r[0] = (sbyte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block - r[2] = v[p++]; // simple code is just the value + this.R[0] = (sbyte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block + this.R[2] = v[p++]; // simple code is just the value } else { - r[0] = (sbyte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists - r[2] = d[v[p++] - s]; + this.R[0] = (sbyte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists + this.R[2] = d[v[p++] - s]; } // fill code-like entries with r f = 1 << (k - w); - for (j = SharedUtils.URShift(i, w); j < z; j += f) + + for (j = SharedUtils.UrShift(i, w); j < z; j += f) { - Array.Copy(r, 0, hp, (q + j) * 3, 3); + Array.Copy(this.R, 0, hp, (q + j) * 3, 3); } // backwards increment the k-bit code i - for (j = 1 << (k - 1); (i & j) != 0; j = SharedUtils.URShift(j, 1)) + for (j = 1 << (k - 1); (i & j) != 0; j = SharedUtils.UrShift(j, 1)) { i ^= j; } @@ -339,9 +419,9 @@ private int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[ i ^= j; // backup over finished tables - mask = (1 << w) - 1; // needed on HP, cc -O bug + int mask = (1 << w) - 1; // (1 << w) - 1, to avoid cc -O bug on HP - while ((i & mask) != x[h]) + while ((i & mask) != this.X[h]) { h--; // don't need to update q w -= l; @@ -358,9 +438,9 @@ internal int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZlibCodec { int result; - initWorkArea(19); - hn[0] = 0; - result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); + this.InitWorkArea(19); + this.Hn[0] = 0; + result = this.huft_build(c, 0, 19, 19, null, null, tb, bb, hp, this.Hn, this.V); if (result == Z_DATA_ERROR) { @@ -380,9 +460,9 @@ internal int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int result; // build literal/length tree - initWorkArea(288); - hn[0] = 0; - result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); + this.InitWorkArea(288); + this.Hn[0] = 0; + result = this.huft_build(c, 0, nl, 257, Cplens, Cplext, tl, bl, hp, this.Hn, this.V); if (result != Z_OK || bl[0] == 0) { @@ -400,8 +480,8 @@ internal int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, } // build distance tree - initWorkArea(288); - result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); + this.InitWorkArea(288); + result = this.huft_build(c, nl, nd, 0, Cpdist, Cpdext, td, bd, hp, this.Hn, this.V); if (result != Z_OK || (bd[0] == 0 && nl > 257)) { @@ -428,49 +508,50 @@ internal int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZlibCodec z) { - bl[0] = fixed_bl; - bd[0] = fixed_bd; - tl[0] = fixed_tl; - td[0] = fixed_td; + bl[0] = FIXED_BL; + bd[0] = FIXED_BD; + tl[0] = FixedTl; + td[0] = FixedTd; return Z_OK; } - private void initWorkArea(int vsize) + private void InitWorkArea(int vsize) { - if (hn == null) + if (this.Hn == null) { - hn = new int[1]; - v = new int[vsize]; - c = new int[BMAX + 1]; - r = new int[3]; - u = new int[BMAX]; - x = new int[BMAX + 1]; + this.Hn = new int[1]; + this.V = new int[vsize]; + this.C = new int[BMAX + 1]; + this.R = new int[3]; + this.U = new int[BMAX]; + this.X = new int[BMAX + 1]; } - if (v.Length < vsize) + if (this.V.Length < vsize) { - v = new int[vsize]; + this.V = new int[vsize]; } for (int i = 0; i < vsize; i++) { - v[i] = 0; + this.V[i] = 0; } for (int i = 0; i < BMAX + 1; i++) { - c[i] = 0; + this.C[i] = 0; } for (int i = 0; i < 3; i++) { - r[i] = 0; + this.R[i] = 0; } // for(int i=0; i n) t = n; @@ -323,14 +360,16 @@ internal int Process(int r) if (t > m) t = m; - Array.Copy(_codec.InputBuffer, p, window, q, t); - p += t; n -= t; - q += t; m -= t; + Array.Copy(this.Codec.InputBuffer, p, this.Window, q, t); + p += t; + n -= t; + q += t; + m -= t; - if ((left -= t) != 0) + if ((this.Left -= t) != 0) break; - mode = last != 0 ? DRY : TYPE; + this.Mode = this.Last != 0 ? DRY : TYPE; break; case TABLE: @@ -342,59 +381,63 @@ internal int Process(int r) } else { - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - ; n--; - b |= (_codec.InputBuffer[p++] & 0xff) << k; + b |= (this.Codec.InputBuffer[p++] & 0xff) << k; k += 8; } - table = t = (b & 0x3fff); + this.Table = t = (b & 0x3fff); if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { - mode = BAD; - _codec.Message = "too many length or distance symbols"; + this.Mode = BAD; + this.Codec.Message = "too many length or distance symbols"; r = ZlibConstants.Z_DATA_ERROR; - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); - if (blens == null || blens.Length < t) + if (this.Blens == null || this.Blens.Length < t) { - blens = new int[t]; + this.Blens = new int[t]; } else { for (int i = 0; i < t; i++) { - blens[i] = 0; + this.Blens[i] = 0; } } - { - b = SharedUtils.URShift(b, (14)); k -= (14); + b = SharedUtils.UrShift(b, (14)); + k -= (14); } - index = 0; - mode = BTREE; + this.Index = 0; + this.Mode = BTREE; + goto case BTREE; case BTREE: - while (index < 4 + (SharedUtils.URShift(table, 10))) + while (this.Index < 4 + (SharedUtils.UrShift(this.Table, 10))) { while (k < (3)) { @@ -404,34 +447,36 @@ internal int Process(int r) } else { - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - ; n--; - b |= (_codec.InputBuffer[p++] & 0xff) << k; + b |= (this.Codec.InputBuffer[p++] & 0xff) << k; k += 8; } - blens[border[index++]] = b & 7; + this.Blens[Border[this.Index++]] = b & 7; { - b = SharedUtils.URShift(b, (3)); k -= (3); + b = SharedUtils.UrShift(b, (3)); + k -= (3); } } - while (index < 19) + while (this.Index < 19) { - blens[border[index++]] = 0; + this.Blens[Border[this.Index++]] = 0; } - bb[0] = 7; - t = inftree.inflate_trees_bits(blens, bb, tb, hufts, _codec); + this.Bb[0] = 7; + t = this.Inftree.inflate_trees_bits(this.Blens, this.Bb, this.Tb, this.Hufts, this.Codec); if (t != ZlibConstants.Z_OK) { @@ -439,35 +484,37 @@ internal int Process(int r) if (r == ZlibConstants.Z_DATA_ERROR) { - blens = null; - mode = BAD; + this.Blens = null; + this.Mode = BAD; } - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + return this.Flush(r); } - index = 0; - mode = DTREE; + this.Index = 0; + this.Mode = DTREE; + goto case DTREE; case DTREE: while (true) { - t = table; + t = this.Table; - if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) + if (!(this.Index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) { break; } - int i, j, c; + int c; - t = bb[0]; + t = this.Bb[0]; while (k < (t)) { @@ -477,39 +524,40 @@ internal int Process(int r) } else { - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - ; n--; - b |= (_codec.InputBuffer[p++] & 0xff) << k; + b |= (this.Codec.InputBuffer[p++] & 0xff) << k; k += 8; } - if (tb[0] == -1) + if (this.Tb[0] == -1) { //System.err.println("null..."); } - t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1]; - c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2]; + t = this.Hufts[(this.Tb[0] + (b & inflateMask[t])) * 3 + 1]; + c = this.Hufts[(this.Tb[0] + (b & inflateMask[t])) * 3 + 2]; if (c < 16) { - b = SharedUtils.URShift(b, (t)); k -= (t); - blens[index++] = c; + b = SharedUtils.UrShift(b, (t)); + k -= (t); + this.Blens[this.Index++] = c; } else { // c == 16..18 - i = c == 18 ? 7 : c - 14; - j = c == 18 ? 11 : 3; + int i = c == 18 ? 7 : c - 14; + int j = c == 18 ? 11 : 3; while (k < (t + i)) { @@ -519,182 +567,200 @@ internal int Process(int r) } else { - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - ; n--; - b |= (_codec.InputBuffer[p++] & 0xff) << k; + b |= (this.Codec.InputBuffer[p++] & 0xff) << k; k += 8; } - b = SharedUtils.URShift(b, (t)); k -= (t); - j += (b & inflate_mask[i]); - b = SharedUtils.URShift(b, (i)); k -= (i); + b = SharedUtils.UrShift(b, (t)); + k -= (t); + j += (b & inflateMask[i]); + b = SharedUtils.UrShift(b, (i)); + k -= (i); - i = index; - t = table; + i = this.Index; + t = this.Table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { - blens = null; - mode = BAD; - _codec.Message = "invalid bit length repeat"; + this.Blens = null; + this.Mode = BAD; + this.Codec.Message = "invalid bit length repeat"; r = ZlibConstants.Z_DATA_ERROR; - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - c = c == 16 ? blens[i - 1] : 0; + c = c == 16 ? this.Blens[i - 1] : 0; do { - blens[i++] = c; + this.Blens[i++] = c; } while (--j != 0); - index = i; + this.Index = i; } } - tb[0] = -1; + this.Tb[0] = -1; { - int[] bl = new int[] { 9 }; // must be <= 9 for lookahead assumptions - int[] bd = new int[] { 6 }; // must be <= 9 for lookahead assumptions + int[] bl = { 9 }; // must be <= 9 for lookahead assumptions + int[] bd = { 6 }; // must be <= 9 for lookahead assumptions int[] tl = new int[1]; int[] td = new int[1]; - t = table; - t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, _codec); + t = this.Table; + t = this.Inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), this.Blens, bl, bd, tl, td, this.Hufts, this.Codec); if (t != ZlibConstants.Z_OK) { if (t == ZlibConstants.Z_DATA_ERROR) { - blens = null; - mode = BAD; + this.Blens = null; + this.Mode = BAD; } r = t; - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); + this.Codes.Init(bl[0], bd[0], this.Hufts, tl[0], this.Hufts, td[0]); } - mode = CODES; + this.Mode = CODES; + goto case CODES; case CODES: - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; - if ((r = codes.Process(this, r)) != ZlibConstants.Z_STREAM_END) - return Flush(r); + if ((r = this.Codes.Process(this, r)) != ZlibConstants.Z_STREAM_END) + return this.Flush(r); r = ZlibConstants.Z_OK; - p = _codec.NextIn; - n = _codec.AvailableBytesIn; - b = bitb; - k = bitk; - q = write; - m = (int)(q < read ? read - q - 1 : end - q); - - if (last == 0) + p = this.Codec.NextIn; + n = this.Codec.AvailableBytesIn; + b = this.Bitb; + k = this.Bitk; + q = this.Write; + m = q < this.Read ? this.Read - q - 1 : this.End - q; + + if (this.Last == 0) { - mode = TYPE; + this.Mode = TYPE; break; } - mode = DRY; + this.Mode = DRY; goto case DRY; case DRY: - write = q; - r = Flush(r); - q = write; m = (int)(q < read ? read - q - 1 : end - q); + this.Write = q; + r = this.Flush(r); + q = this.Write; - if (read != write) - { - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; + //m = q < this.Read ? this.Read - q - 1 : this.End - q; - return Flush(r); + if (this.Read != this.Write) + { + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } - mode = DONE; + this.Mode = DONE; + goto case DONE; case DONE: r = ZlibConstants.Z_STREAM_END; - bitb = b; - bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); case BAD: r = ZlibConstants.Z_DATA_ERROR; - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); default: r = ZlibConstants.Z_STREAM_ERROR; - bitb = b; bitk = k; - _codec.AvailableBytesIn = n; - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - write = q; - return Flush(r); + this.Bitb = b; + this.Bitk = k; + this.Codec.AvailableBytesIn = n; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Write = q; + + return this.Flush(r); } } } internal void Free() { - Reset(null); - window = null; - hufts = null; + this.Reset(null); + this.Window = null; + this.Hufts = null; //ZFREE(z, s); } internal void SetDictionary(byte[] d, int start, int n) { - Array.Copy(d, start, window, 0, n); - read = write = n; + Array.Copy(d, start, this.Window, 0, n); + this.Read = this.Write = n; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. internal int SyncPoint() { - return mode == LENS ? 1 : 0; + return this.Mode == LENS ? 1 : 0; } // copy as much as possible from the sliding window to the output area @@ -705,66 +771,66 @@ internal int Flush(int r) int q; // local copies of source and destination pointers - p = _codec.NextOut; - q = read; + p = this.Codec.NextOut; + q = this.Read; // compute number of bytes to copy as far as end of window - n = (int)((q <= write ? write : end) - q); + n = (q <= this.Write ? this.Write : this.End) - q; - if (n > _codec.AvailableBytesOut) - n = _codec.AvailableBytesOut; + if (n > this.Codec.AvailableBytesOut) + n = this.Codec.AvailableBytesOut; if (n != 0 && r == ZlibConstants.Z_BUF_ERROR) r = ZlibConstants.Z_OK; // update counters - _codec.AvailableBytesOut -= n; - _codec.TotalBytesOut += n; + this.Codec.AvailableBytesOut -= n; + this.Codec.TotalBytesOut += n; // update check information - if (checkfn != null) - _codec._Adler32 = check = Adler.Adler32(check, window, q, n); + if (this.Checkfn != null) + this.Codec.Adler32 = this.Check = Adler.Adler32(this.Check, this.Window, q, n); // copy as far as end of window - Array.Copy(window, q, _codec.OutputBuffer, p, n); + Array.Copy(this.Window, q, this.Codec.OutputBuffer, p, n); p += n; q += n; // see if more to copy at beginning of window - if (q == end) + if (q == this.End) { // wrap pointers q = 0; - if (write == end) - write = 0; + if (this.Write == this.End) + this.Write = 0; // compute bytes to copy - n = write - q; + n = this.Write - q; - if (n > _codec.AvailableBytesOut) - n = _codec.AvailableBytesOut; + if (n > this.Codec.AvailableBytesOut) + n = this.Codec.AvailableBytesOut; if (n != 0 && r == ZlibConstants.Z_BUF_ERROR) r = ZlibConstants.Z_OK; // update counters - _codec.AvailableBytesOut -= n; - _codec.TotalBytesOut += n; + this.Codec.AvailableBytesOut -= n; + this.Codec.TotalBytesOut += n; // update check information - if (checkfn != null) - _codec._Adler32 = check = Adler.Adler32(check, window, q, n); + if (this.Checkfn != null) + this.Codec.Adler32 = this.Check = Adler.Adler32(this.Check, this.Window, q, n); // copy - Array.Copy(window, q, _codec.OutputBuffer, p, n); + Array.Copy(this.Window, q, this.Codec.OutputBuffer, p, n); p += n; q += n; } // update pointers - _codec.NextOut = p; - read = q; + this.Codec.NextOut = p; + this.Read = q; // done return r; @@ -773,8 +839,28 @@ internal int Flush(int r) sealed internal class InflateCodes { - //UPGRADE_NOTE: Final was removed from the declaration of 'inflate_mask'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] inflate_mask = new int[] { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff }; + // UPGRADE_NOTE: Final was removed from the declaration of 'inflate_mask'. + // "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" + private static readonly int[] inflateMask = + { + 0x00000000, + 0x00000001, + 0x00000003, + 0x00000007, + 0x0000000f, + 0x0000001f, + 0x0000003f, + 0x0000007f, + 0x000000ff, + 0x000001ff, + 0x000003ff, + 0x000007ff, + 0x00000fff, + 0x00001fff, + 0x00003fff, + 0x00007fff, + 0x0000ffff + }; // waiting for "i:"=input, // "o:"=output, @@ -790,99 +876,104 @@ sealed internal class InflateCodes private const int END = 8; // x: got eob and all data flushed private const int BADCODE = 9; // x: got error - internal int mode; // current inflate_codes mode + internal int Mode; // current inflate_codes mode // mode dependent information - internal int len; + internal int Len; - internal int[] tree; // pointer into tree - internal int tree_index = 0; - internal int need; // bits needed - internal int lit; + internal int[] Tree; // pointer into tree + internal int TreeIndex; + internal int Need; // bits needed + internal int Lit; // if EXT or COPY, where and how much - internal int get_Renamed; // bits to get for extra - internal int dist; // distance back to copy from + internal int GetRenamed; // bits to get for extra + internal int Dist; // distance back to copy from - internal byte lbits; // ltree bits decoded per branch - internal byte dbits; // dtree bits decoder per branch - internal int[] ltree; // literal/length/eob tree - internal int ltree_index; // literal/length/eob tree - internal int[] dtree; // distance tree - internal int dtree_index; // distance tree + internal byte Lbits; // ltree bits decoded per branch + internal byte Dbits; // dtree bits decoder per branch + internal int[] Ltree; // literal/length/eob tree + internal int LtreeIndex; // literal/length/eob tree + internal int[] Dtree; // distance tree + internal int DtreeIndex; // distance tree - internal InflateCodes() { } + //internal InflateCodes() { } - internal void Init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index) + internal void Init(int bl, int bd, int[] tl, int tlIndex, int[] td, int tdIndex) { - mode = START; - lbits = (byte)bl; - dbits = (byte)bd; - ltree = tl; - ltree_index = tl_index; - dtree = td; - dtree_index = td_index; - tree = null; + this.Mode = START; + this.Lbits = (byte) bl; + this.Dbits = (byte) bd; + this.Ltree = tl; + this.LtreeIndex = tlIndex; + this.Dtree = td; + this.DtreeIndex = tdIndex; + this.Tree = null; } internal int Process(InflateBlocks blocks, int r) { - int j; // temporary storage - int tindex; // temporary pointer - int e; // extra bits or operation - int b = 0; // bit buffer - int k = 0; // bits in bit buffer - int p = 0; // input data pointer + int b; // bit buffer + int k; // bits in bit buffer + int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer - int f; // pointer to copy strings from - ZlibCodec z = blocks._codec; + ZlibCodec z = blocks.Codec; // copy input/output information to locals (UPDATE macro restores) p = z.NextIn; n = z.AvailableBytesIn; - b = blocks.bitb; - k = blocks.bitk; - q = blocks.write; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + b = blocks.Bitb; + k = blocks.Bitk; + q = blocks.Write; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; // process input and output based on current state while (true) { - switch (mode) + int j; // temporary storage + int tindex; // temporary pointer + int e; // extra bits or operation + + switch (this.Mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { - blocks.bitb = b; blocks.bitk = k; + blocks.Bitb = b; + blocks.Bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; - r = InflateFast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, blocks, z); + blocks.Write = q; + r = this.InflateFast(this.Lbits, this.Dbits, this.Ltree, this.LtreeIndex, this.Dtree, this.DtreeIndex, blocks, z); p = z.NextIn; n = z.AvailableBytesIn; - b = blocks.bitb; - k = blocks.bitk; - q = blocks.write; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + b = blocks.Bitb; + k = blocks.Bitk; + q = blocks.Write; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; if (r != ZlibConstants.Z_OK) { - mode = (r == ZlibConstants.Z_STREAM_END) ? WASH : BADCODE; + this.Mode = (r == ZlibConstants.Z_STREAM_END) ? WASH : BADCODE; + break; } } - need = lbits; - tree = ltree; - tree_index = ltree_index; - mode = LEN; + this.Need = this.Lbits; + this.Tree = this.Ltree; + this.TreeIndex = this.LtreeIndex; + this.Mode = LEN; + goto case LEN; case LEN: // i: get length/literal/eob next - j = need; + j = this.Need; while (k < (j)) { @@ -890,11 +981,13 @@ internal int Process(InflateBlocks blocks, int r) r = ZlibConstants.Z_OK; else { - blocks.bitb = b; blocks.bitk = k; + blocks.Bitb = b; + blocks.Bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Write = q; + return blocks.Flush(r); } @@ -903,56 +996,62 @@ internal int Process(InflateBlocks blocks, int r) k += 8; } - tindex = (tree_index + (b & inflate_mask[j])) * 3; + tindex = (this.TreeIndex + (b & inflateMask[j])) * 3; - b = SharedUtils.URShift(b, (tree[tindex + 1])); - k -= (tree[tindex + 1]); - e = tree[tindex]; + b = SharedUtils.UrShift(b, (this.Tree[tindex + 1])); + k -= (this.Tree[tindex + 1]); + e = this.Tree[tindex]; if (e == 0) { // literal - lit = tree[tindex + 2]; - mode = LIT; + this.Lit = this.Tree[tindex + 2]; + this.Mode = LIT; + break; } if ((e & 16) != 0) { // length - get_Renamed = e & 15; - len = tree[tindex + 2]; - mode = LENEXT; + this.GetRenamed = e & 15; + this.Len = this.Tree[tindex + 2]; + this.Mode = LENEXT; + break; } if ((e & 64) == 0) { // next table - need = e; - tree_index = tindex / 3 + tree[tindex + 2]; + this.Need = e; + this.TreeIndex = tindex / 3 + this.Tree[tindex + 2]; + break; } if ((e & 32) != 0) { // end of block - mode = WASH; + this.Mode = WASH; + break; } - mode = BADCODE; // invalid code + this.Mode = BADCODE; // invalid code z.Message = "invalid literal/length code"; r = ZlibConstants.Z_DATA_ERROR; - blocks.bitb = b; blocks.bitk = k; + blocks.Bitb = b; + blocks.Bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Write = q; + return blocks.Flush(r); case LENEXT: // i: getting length extra (have base) - j = get_Renamed; + j = this.GetRenamed; while (k < (j)) { @@ -961,29 +1060,35 @@ internal int Process(InflateBlocks blocks, int r) else { - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } - n--; b |= (z.InputBuffer[p++] & 0xff) << k; + n--; + b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } - len += (b & inflate_mask[j]); + this.Len += (b & inflateMask[j]); b >>= j; k -= j; - need = dbits; - tree = dtree; - tree_index = dtree_index; - mode = DIST; + this.Need = this.Dbits; + this.Tree = this.Dtree; + this.TreeIndex = this.DtreeIndex; + this.Mode = DIST; + goto case DIST; case DIST: // i: get distance next - j = need; + j = this.Need; while (k < (j)) { @@ -991,49 +1096,60 @@ internal int Process(InflateBlocks blocks, int r) r = ZlibConstants.Z_OK; else { - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } - n--; b |= (z.InputBuffer[p++] & 0xff) << k; + n--; + b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } - tindex = (tree_index + (b & inflate_mask[j])) * 3; + tindex = (this.TreeIndex + (b & inflateMask[j])) * 3; - b >>= tree[tindex + 1]; - k -= tree[tindex + 1]; - e = (tree[tindex]); + b >>= this.Tree[tindex + 1]; + k -= this.Tree[tindex + 1]; + e = (this.Tree[tindex]); if ((e & 16) != 0) { // distance - get_Renamed = e & 15; - dist = tree[tindex + 2]; - mode = DISTEXT; + this.GetRenamed = e & 15; + this.Dist = this.Tree[tindex + 2]; + this.Mode = DISTEXT; + break; } if ((e & 64) == 0) { // next table - need = e; - tree_index = tindex / 3 + tree[tindex + 2]; + this.Need = e; + this.TreeIndex = tindex / 3 + this.Tree[tindex + 2]; + break; } - mode = BADCODE; // invalid code + this.Mode = BADCODE; // invalid code z.Message = "invalid distance code"; r = ZlibConstants.Z_DATA_ERROR; - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); case DISTEXT: // i: getting distance extra - j = get_Renamed; + j = this.GetRenamed; while (k < (j)) { @@ -1041,106 +1157,129 @@ internal int Process(InflateBlocks blocks, int r) r = ZlibConstants.Z_OK; else { - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } - n--; b |= (z.InputBuffer[p++] & 0xff) << k; + n--; + b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } - dist += (b & inflate_mask[j]); + this.Dist += (b & inflateMask[j]); b >>= j; k -= j; - mode = COPY; + this.Mode = COPY; + goto case COPY; case COPY: // o: copying bytes in window, waiting for space - f = q - dist; + int f = q - this.Dist; // pointer to copy strings from while (f < 0) { // modulo window size-"while" instead - f += blocks.end; // of "if" handles invalid distances + f += blocks.End; // of "if" handles invalid distances } - while (len != 0) + while (this.Len != 0) { if (m == 0) { - if (q == blocks.end && blocks.read != 0) + if (q == blocks.End && blocks.Read != 0) { - q = 0; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + q = 0; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; } if (m == 0) { - blocks.write = q; r = blocks.Flush(r); - q = blocks.write; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + blocks.Write = q; + r = blocks.Flush(r); + q = blocks.Write; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; - if (q == blocks.end && blocks.read != 0) + if (q == blocks.End && blocks.Read != 0) { - q = 0; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + q = 0; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; } if (m == 0) { - blocks.bitb = b; blocks.bitk = k; + blocks.Bitb = b; + blocks.Bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Write = q; + return blocks.Flush(r); } } } - blocks.window[q++] = blocks.window[f++]; m--; + blocks.Window[q++] = blocks.Window[f++]; + m--; - if (f == blocks.end) + if (f == blocks.End) f = 0; - len--; + this.Len--; } - mode = START; + this.Mode = START; break; case LIT: // o: got literal, waiting for output space if (m == 0) { - if (q == blocks.end && blocks.read != 0) + if (q == blocks.End && blocks.Read != 0) { - q = 0; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + q = 0; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; } if (m == 0) { - blocks.write = q; r = blocks.Flush(r); - q = blocks.write; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + blocks.Write = q; + r = blocks.Flush(r); + q = blocks.Write; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; - if (q == blocks.end && blocks.read != 0) + if (q == blocks.End && blocks.Read != 0) { - q = 0; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + q = 0; + m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; } if (m == 0) { - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } } } r = ZlibConstants.Z_OK; - blocks.window[q++] = (byte)lit; m--; - mode = START; + blocks.Window[q++] = (byte) this.Lit; + m--; + this.Mode = START; + break; case WASH: // o: got eob, possibly more output @@ -1152,39 +1291,58 @@ internal int Process(InflateBlocks blocks, int r) p--; // can always return one } - blocks.write = q; r = blocks.Flush(r); - q = blocks.write; m = q < blocks.read ? blocks.read - q - 1 : blocks.end - q; + blocks.Write = q; + r = blocks.Flush(r); + q = blocks.Write; + //m = q < blocks.Read ? blocks.Read - q - 1 : blocks.End - q; - if (blocks.read != blocks.write) + if (blocks.Read != blocks.Write) { - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } - mode = END; + this.Mode = END; + goto case END; case END: r = ZlibConstants.Z_STREAM_END; - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); case BADCODE: // x: got error r = ZlibConstants.Z_DATA_ERROR; - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); default: r = ZlibConstants.Z_STREAM_ERROR; - blocks.bitb = b; blocks.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - blocks.write = q; + blocks.Bitb = b; + blocks.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + blocks.Write = q; + return blocks.Flush(r); } } @@ -1195,12 +1353,8 @@ internal int Process(InflateBlocks blocks, int r) // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. - internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InflateBlocks s, ZlibCodec z) + internal int InflateFast(int bl, int bd, int[] tl, int tlIndex, int[] td, int tdIndex, InflateBlocks s, ZlibCodec z) { - int t; // temporary pointer - int[] tp; // temporary pointer - int tp_index; // temporary pointer - int e; // extra bits or operation int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer @@ -1210,18 +1364,18 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t int ml; // mask for literal/length tree int md; // mask for distance tree int c; // bytes to copy - int d; // distance back to copy from - int r; // copy source pointer - - int tp_index_t_3; // (tp_index+t)*3 // load input, output, bit values - p = z.NextIn; n = z.AvailableBytesIn; b = s.bitb; k = s.bitk; - q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q; + p = z.NextIn; + n = z.AvailableBytesIn; + b = s.Bitb; + k = s.Bitk; + q = s.Write; + m = q < s.Read ? s.Read - q - 1 : s.End - q; // initialize masks - ml = inflate_mask[bl]; - md = inflate_mask[bd]; + ml = inflateMask[bl]; + md = inflateMask[bd]; // do until not enough input or output space for fast loop do @@ -1232,51 +1386,59 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t { // max bits for literal/length code n--; - b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; + b |= (z.InputBuffer[p++] & 0xff) << k; + k += 8; } - t = b & ml; - tp = tl; - tp_index = tl_index; - tp_index_t_3 = (tp_index + t) * 3; + int t = b & ml; // temporary pointer + int[] tp = tl; // temporary pointer + int tpIndex = tlIndex; // temporary pointer + int tpIndexT3 = (tpIndex + t) * 3; // (tp_index+t)*3 + int e; // extra bits or operation - if ((e = tp[tp_index_t_3]) == 0) + if ((e = tp[tpIndexT3]) == 0) { - b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); + b >>= (tp[tpIndexT3 + 1]); + k -= (tp[tpIndexT3 + 1]); - s.window[q++] = (byte)tp[tp_index_t_3 + 2]; + s.Window[q++] = (byte) tp[tpIndexT3 + 2]; m--; + continue; } do { - b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); + b >>= (tp[tpIndexT3 + 1]); + k -= (tp[tpIndexT3 + 1]); if ((e & 16) != 0) { e &= 15; - c = tp[tp_index_t_3 + 2] + ((int)b & inflate_mask[e]); + c = tp[tpIndexT3 + 2] + (b & inflateMask[e]); - b >>= e; k -= e; + b >>= e; + k -= e; // decode distance base of block to copy while (k < (15)) { // max bits for distance code n--; - b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; + b |= (z.InputBuffer[p++] & 0xff) << k; + k += 8; } t = b & md; tp = td; - tp_index = td_index; - tp_index_t_3 = (tp_index + t) * 3; - e = tp[tp_index_t_3]; + tpIndex = tdIndex; + tpIndexT3 = (tpIndex + t) * 3; + e = tp[tpIndexT3]; do { - b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); + b >>= (tp[tpIndexT3 + 1]); + k -= (tp[tpIndexT3 + 1]); if ((e & 16) != 0) { @@ -1287,15 +1449,20 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t { // get extra bits (up to 13) n--; - b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; + b |= (z.InputBuffer[p++] & 0xff) << k; + k += 8; } - d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]); - b >>= (e); k -= (e); + int d = tp[tpIndexT3 + 2] + (b & inflateMask[e]); // distance back to copy from + + b >>= (e); + k -= (e); // do the copy m -= c; + int r; // copy source pointer + if (q >= d) { // offset before dest @@ -1304,27 +1471,30 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t if (q - r > 0 && 2 > (q - r)) { - s.window[q++] = s.window[r++]; // minimum count is three, - s.window[q++] = s.window[r++]; // so unroll loop a little + s.Window[q++] = s.Window[r++]; // minimum count is three, + s.Window[q++] = s.Window[r++]; // so unroll loop a little c -= 2; } else { - Array.Copy(s.window, r, s.window, q, 2); - q += 2; r += 2; c -= 2; + Array.Copy(s.Window, r, s.Window, q, 2); + q += 2; + r += 2; + c -= 2; } } else { // else offset after destination r = q - d; + do { - r += s.end; // force pointer in window + r += s.End; // force pointer in window } while (r < 0); // covers invalid distances - e = s.end - r; + e = s.End - r; if (c > e) { @@ -1335,14 +1505,16 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t { do { - s.window[q++] = s.window[r++]; + s.Window[q++] = s.Window[r++]; } while (--e != 0); } else { - Array.Copy(s.window, r, s.window, q, e); - q += e; r += e; e = 0; + Array.Copy(s.Window, r, s.Window, q, e); + q += e; + //r += e; + //e = 0; } r = 0; // copy rest from start of window @@ -1354,68 +1526,98 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t { do { - s.window[q++] = s.window[r++]; + s.Window[q++] = s.Window[r++]; } while (--c != 0); } else { - Array.Copy(s.window, r, s.window, q, c); - q += c; r += c; c = 0; + Array.Copy(s.Window, r, s.Window, q, c); + q += c; + //r += c; + //c = 0; } break; } - else if ((e & 64) == 0) + + if ((e & 64) == 0) { - t += tp[tp_index_t_3 + 2]; - t += (b & inflate_mask[e]); - tp_index_t_3 = (tp_index + t) * 3; - e = tp[tp_index_t_3]; + t += tp[tpIndexT3 + 2]; + t += (b & inflateMask[e]); + tpIndexT3 = (tpIndex + t) * 3; + e = tp[tpIndexT3]; } else { z.Message = "invalid distance code"; - c = z.AvailableBytesIn - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3); - s.bitb = b; s.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - s.write = q; + c = z.AvailableBytesIn - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= (c << 3); + s.Bitb = b; + s.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + s.Write = q; + return ZlibConstants.Z_DATA_ERROR; } } while (true); + break; } if ((e & 64) == 0) { - t += tp[tp_index_t_3 + 2]; - t += (b & inflate_mask[e]); - tp_index_t_3 = (tp_index + t) * 3; + t += tp[tpIndexT3 + 2]; + t += (b & inflateMask[e]); + tpIndexT3 = (tpIndex + t) * 3; - if ((e = tp[tp_index_t_3]) == 0) + if ((e = tp[tpIndexT3]) == 0) { - b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]); - s.window[q++] = (byte)tp[tp_index_t_3 + 2]; + b >>= (tp[tpIndexT3 + 1]); + k -= (tp[tpIndexT3 + 1]); + s.Window[q++] = (byte) tp[tpIndexT3 + 2]; m--; + break; } } else if ((e & 32) != 0) { - c = z.AvailableBytesIn - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3); - s.bitb = b; s.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - s.write = q; + c = z.AvailableBytesIn - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= (c << 3); + s.Bitb = b; + s.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + s.Write = q; + return ZlibConstants.Z_STREAM_END; } else { z.Message = "invalid literal/length code"; - c = z.AvailableBytesIn - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3); - s.bitb = b; s.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - s.write = q; + c = z.AvailableBytesIn - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= (c << 3); + s.Bitb = b; + s.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + s.Write = q; + return ZlibConstants.Z_DATA_ERROR; } } @@ -1424,11 +1626,19 @@ internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int t while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return - c = z.AvailableBytesIn - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3); + c = z.AvailableBytesIn - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= (c << 3); + + s.Bitb = b; + s.Bitk = k; + z.AvailableBytesIn = n; + z.TotalBytesIn += p - z.NextIn; + z.NextIn = p; + s.Write = q; - s.bitb = b; s.bitk = k; - z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; - s.write = q; return ZlibConstants.Z_OK; } } @@ -1453,61 +1663,64 @@ internal sealed class InflateManager private const int DONE = 12; // finished check, done private const int BAD = 13; // got an error--stay here - internal int mode; // current inflate mode - internal ZlibCodec _codec; // pointer back to this zlib stream + internal int Mode; // current inflate mode + internal ZlibCodec Codec; // pointer back to this zlib stream // mode dependent information - internal int method; // if FLAGS, method byte + internal int Method; // if FLAGS, method byte // if CHECK, check values to compare - internal long[] was = new long[1]; // computed check value - internal long need; // stream check value + internal long[] Was = new long[1]; // computed check value + internal long Need; // stream check value // if BAD, inflateSync's marker bytes count - internal int marker; + internal int Marker; // mode independent information //internal int nowrap; // flag for no wrapper - private bool _handleRfc1950HeaderBytes = true; + private bool handleRfc1950HeaderBytes = true; + internal bool HandleRfc1950HeaderBytes { - get { return _handleRfc1950HeaderBytes; } - set { _handleRfc1950HeaderBytes = value; } + get { return this.handleRfc1950HeaderBytes; } + set { this.handleRfc1950HeaderBytes = value; } } - internal int wbits; // log2(window size) (8..15, defaults to 15) - internal InflateBlocks blocks; // current inflate_blocks state + internal int Wbits; // log2(window size) (8..15, defaults to 15) + internal InflateBlocks Blocks; // current inflate_blocks state public InflateManager() { } public InflateManager(bool expectRfc1950HeaderBytes) { - _handleRfc1950HeaderBytes = expectRfc1950HeaderBytes; + this.handleRfc1950HeaderBytes = expectRfc1950HeaderBytes; } internal int Reset() { - _codec.TotalBytesIn = _codec.TotalBytesOut = 0; - _codec.Message = null; - mode = HandleRfc1950HeaderBytes ? METHOD : BLOCKS; - blocks.Reset(null); + this.Codec.TotalBytesIn = this.Codec.TotalBytesOut = 0; + this.Codec.Message = null; + this.Mode = this.HandleRfc1950HeaderBytes ? METHOD : BLOCKS; + this.Blocks.Reset(null); + return ZlibConstants.Z_OK; } internal int End() { - if (blocks != null) - blocks.Free(); + if (this.Blocks != null) + this.Blocks.Free(); + + this.Blocks = null; - blocks = null; return ZlibConstants.Z_OK; } internal int Initialize(ZlibCodec codec, int w) { - _codec = codec; - _codec.Message = null; - blocks = null; + this.Codec = codec; + codec.Message = null; + this.Blocks = null; // handle undocumented nowrap option (no zlib header or check) //nowrap = 0; @@ -1520,147 +1733,163 @@ internal int Initialize(ZlibCodec codec, int w) // set window size if (w < 8 || w > 15) { - End(); + this.End(); throw new ZlibException("Bad window size."); //return ZlibConstants.Z_STREAM_ERROR; } - wbits = w; + this.Wbits = w; - blocks = new InflateBlocks(codec, - HandleRfc1950HeaderBytes ? this : null, - 1 << w); + this.Blocks = new InflateBlocks(codec, this.HandleRfc1950HeaderBytes ? this : null, 1 << w); // reset state - Reset(); + this.Reset(); + return ZlibConstants.Z_OK; } internal int Inflate(FlushType flush) { int r; - int b; - int f = (int)flush; + int f = (int) flush; - if (_codec.InputBuffer == null) + if (this.Codec.InputBuffer == null) throw new ZlibException("InputBuffer is null. "); - f = (f == (int)FlushType.Finish) + f = (f == (int) FlushType.Finish) ? ZlibConstants.Z_BUF_ERROR : ZlibConstants.Z_OK; r = ZlibConstants.Z_BUF_ERROR; while (true) { - switch (mode) + switch (this.Mode) { case METHOD: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; - if (((method = _codec.InputBuffer[_codec.NextIn++]) & 0xf) != Z_DEFLATED) + if (((this.Method = this.Codec.InputBuffer[this.Codec.NextIn++]) & 0xf) != Z_DEFLATED) { - mode = BAD; - _codec.Message = String.Format("unknown compression method (0x{0:X2})", method); - marker = 5; // can't try inflateSync + this.Mode = BAD; + this.Codec.Message = string.Format("unknown compression method (0x{0:X2})", this.Method); + this.Marker = 5; // can't try inflateSync + break; } - if ((method >> 4) + 8 > wbits) + if ((this.Method >> 4) + 8 > this.Wbits) { - mode = BAD; - _codec.Message = String.Format("invalid window size ({0})", (method >> 4) + 8); - marker = 5; // can't try inflateSync + this.Mode = BAD; + this.Codec.Message = string.Format("invalid window size ({0})", (this.Method >> 4) + 8); + this.Marker = 5; // can't try inflateSync + break; } - mode = FLAG; + this.Mode = FLAG; goto case FLAG; case FLAG: - if (_codec.AvailableBytesIn == 0) return r; + if (this.Codec.AvailableBytesIn == 0) + return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - b = (_codec.InputBuffer[_codec.NextIn++]) & 0xff; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + int b = (this.Codec.InputBuffer[this.Codec.NextIn++]) & 0xff; - if ((((method << 8) + b) % 31) != 0) + if ((((this.Method << 8) + b) % 31) != 0) { - mode = BAD; - _codec.Message = "incorrect header check"; - marker = 5; // can't try inflateSync + this.Mode = BAD; + this.Codec.Message = "incorrect header check"; + this.Marker = 5; // can't try inflateSync + break; } if ((b & PRESET_DICT) == 0) { - mode = BLOCKS; + this.Mode = BLOCKS; + break; } - mode = DICT4; + this.Mode = DICT4; + goto case DICT4; case DICT4: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need = ((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 24) & unchecked((int)0xff000000L); - mode = DICT3; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need = ((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 24) & unchecked((int) 0xff000000L); + this.Mode = DICT3; + goto case DICT3; case DICT3: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need += (((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 16) & 0xff0000L); - mode = DICT2; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 16) & 0xff0000L); + this.Mode = DICT2; + goto case DICT2; case DICT2: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need += (((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 8) & 0xff00L); - mode = DICT1; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 8) & 0xff00L); + this.Mode = DICT1; + goto case DICT1; case DICT1: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; - r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need += (_codec.InputBuffer[_codec.NextIn++] & 0xffL); - _codec._Adler32 = need; - mode = DICT0; + //r = f; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (this.Codec.InputBuffer[this.Codec.NextIn++] & 0xffL); + this.Codec.Adler32 = this.Need; + this.Mode = DICT0; + return ZlibConstants.Z_NEED_DICT; case DICT0: - mode = BAD; - _codec.Message = "need dictionary"; - marker = 0; // can try inflateSync + this.Mode = BAD; + this.Codec.Message = "need dictionary"; + this.Marker = 0; // can try inflateSync + return ZlibConstants.Z_STREAM_ERROR; case BLOCKS: - r = blocks.Process(r); + r = this.Blocks.Process(r); if (r == ZlibConstants.Z_DATA_ERROR) { - mode = BAD; - marker = 0; // can try inflateSync + this.Mode = BAD; + this.Marker = 0; // can try inflateSync + break; } @@ -1671,75 +1900,84 @@ internal int Inflate(FlushType flush) return r; r = f; - blocks.Reset(was); + this.Blocks.Reset(this.Was); - if (!HandleRfc1950HeaderBytes) + if (!this.HandleRfc1950HeaderBytes) { - mode = DONE; + this.Mode = DONE; + break; } - mode = CHECK4; + this.Mode = CHECK4; + goto case CHECK4; case CHECK4: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need = ((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 24) & unchecked((int)0xff000000L); - mode = CHECK3; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need = ((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 24) & unchecked((int) 0xff000000L); + this.Mode = CHECK3; + goto case CHECK3; case CHECK3: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need += (((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 16) & 0xff0000L); - mode = CHECK2; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 16) & 0xff0000L); + this.Mode = CHECK2; + goto case CHECK2; case CHECK2: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; - _codec.TotalBytesIn++; - need += (((_codec.InputBuffer[_codec.NextIn++] & 0xff) << 8) & 0xff00L); - mode = CHECK1; + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (((this.Codec.InputBuffer[this.Codec.NextIn++] & 0xff) << 8) & 0xff00L); + this.Mode = CHECK1; + goto case CHECK1; case CHECK1: - if (_codec.AvailableBytesIn == 0) + if (this.Codec.AvailableBytesIn == 0) return r; r = f; - _codec.AvailableBytesIn--; _codec.TotalBytesIn++; - need += (_codec.InputBuffer[_codec.NextIn++] & 0xffL); + this.Codec.AvailableBytesIn--; + this.Codec.TotalBytesIn++; + this.Need += (this.Codec.InputBuffer[this.Codec.NextIn++] & 0xffL); unchecked { - if (((int)(was[0])) != ((int)(need))) + if (((int) (this.Was[0])) != ((int) (this.Need))) { - mode = BAD; - _codec.Message = "incorrect data check"; - marker = 5; // can't try inflateSync + this.Mode = BAD; + this.Codec.Message = "incorrect data check"; + this.Marker = 5; // can't try inflateSync + break; } } - mode = DONE; + this.Mode = DONE; goto case DONE; case DONE: return ZlibConstants.Z_STREAM_END; case BAD: - throw new ZlibException(String.Format("Bad state ({0})", _codec.Message)); + throw new ZlibException(string.Format("Bad state ({0})", this.Codec.Message)); //return ZlibConstants.Z_DATA_ERROR; default: @@ -1754,28 +1992,29 @@ internal int SetDictionary(byte[] dictionary) int index = 0; int length = dictionary.Length; - if (mode != DICT0) + if (this.Mode != DICT0) throw new ZlibException("Stream error."); - if (Adler.Adler32(1L, dictionary, 0, dictionary.Length) != _codec._Adler32) + if (Adler.Adler32(1L, dictionary, 0, dictionary.Length) != this.Codec.Adler32) { return ZlibConstants.Z_DATA_ERROR; } - _codec._Adler32 = Adler.Adler32(0, null, 0, 0); + this.Codec.Adler32 = Adler.Adler32(0, null, 0, 0); - if (length >= (1 << wbits)) + if (length >= (1 << this.Wbits)) { - length = (1 << wbits) - 1; + length = (1 << this.Wbits) - 1; index = dictionary.Length - length; } - blocks.SetDictionary(dictionary, index, length); - mode = BLOCKS; + this.Blocks.SetDictionary(dictionary, index, length); + this.Mode = BLOCKS; + return ZlibConstants.Z_OK; } - private static byte[] mark = new byte[] { 0, 0, 0xff, 0xff }; + private static readonly byte[] mark = { 0, 0, 0xff, 0xff }; internal int Sync() { @@ -1785,26 +2024,26 @@ internal int Sync() long r, w; // temporaries to save total_in and total_out // set up - if (mode != BAD) + if (this.Mode != BAD) { - mode = BAD; - marker = 0; + this.Mode = BAD; + this.Marker = 0; } - if ((n = _codec.AvailableBytesIn) == 0) + if ((n = this.Codec.AvailableBytesIn) == 0) return ZlibConstants.Z_BUF_ERROR; - p = _codec.NextIn; - m = marker; + p = this.Codec.NextIn; + m = this.Marker; // search while (n != 0 && m < 4) { - if (_codec.InputBuffer[p] == mark[m]) + if (this.Codec.InputBuffer[p] == mark[m]) { m++; } - else if (_codec.InputBuffer[p] != 0) + else if (this.Codec.InputBuffer[p] != 0) { m = 0; } @@ -1813,14 +2052,15 @@ internal int Sync() m = 4 - m; } - p++; n--; + p++; + n--; } // restore - _codec.TotalBytesIn += p - _codec.NextIn; - _codec.NextIn = p; - _codec.AvailableBytesIn = n; - marker = m; + this.Codec.TotalBytesIn += p - this.Codec.NextIn; + this.Codec.NextIn = p; + this.Codec.AvailableBytesIn = n; + this.Marker = m; // return no joy or set up to restart on a new block if (m != 4) @@ -1828,12 +2068,13 @@ internal int Sync() return ZlibConstants.Z_DATA_ERROR; } - r = _codec.TotalBytesIn; - w = _codec.TotalBytesOut; - Reset(); - _codec.TotalBytesIn = r; - _codec.TotalBytesOut = w; - mode = BLOCKS; + r = this.Codec.TotalBytesIn; + w = this.Codec.TotalBytesOut; + this.Reset(); + this.Codec.TotalBytesIn = r; + this.Codec.TotalBytesOut = w; + this.Mode = BLOCKS; + return ZlibConstants.Z_OK; } @@ -1845,7 +2086,7 @@ internal int Sync() // waiting for these length bytes. internal int SyncPoint(ZlibCodec z) { - return blocks.SyncPoint(); + return this.Blocks.SyncPoint(); } } } diff --git a/RestSharp/Compression/ZLib/ZLib.cs b/RestSharp/Compression/ZLib/ZLib.cs index c5241e8f4..3f4c50477 100644 --- a/RestSharp/Compression/ZLib/ZLib.cs +++ b/RestSharp/Compression/ZLib/ZLib.cs @@ -62,29 +62,31 @@ // // ----------------------------------------------------------------------- + #if WINDOWS_PHONE using System; -using Interop = System.Runtime.InteropServices; +using System.IO; +using System.Text; namespace RestSharp.Compression.ZLib { /// /// A general purpose exception class for exceptions in the Zlib library. /// - internal class ZlibException : System.Exception + internal class ZlibException : Exception { /// /// The ZlibException class captures exception information generated /// by the Zlib library. /// - public ZlibException() : base() { } + public ZlibException() { } /// /// This ctor collects a message attached to the exception. /// /// - public ZlibException(System.String s) : base(s) { } + public ZlibException(string s) : base(s) { } } internal class SharedUtils @@ -95,7 +97,7 @@ internal class SharedUtils /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation - public static int URShift(int number, int bits) + public static int UrShift(int number, int bits) { return (int)((uint)number >> bits); } @@ -106,9 +108,9 @@ public static int URShift(int number, int bits) /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation - public static long URShift(long number, int bits) + public static long UrShift(long number, int bits) { - return (long)((UInt64)number >> bits); + return (long)((ulong)number >> bits); } #if NOTUSED @@ -172,7 +174,7 @@ public static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] targe /// The starting index of the target array. /// The maximum number of characters to read from the source TextReader. /// The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached. - public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) + public static int ReadInput(TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) @@ -191,14 +193,14 @@ public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte return bytesRead; } - internal static byte[] ToByteArray(System.String sourceString) + internal static byte[] ToByteArray(string sourceString) { - return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); + return Encoding.UTF8.GetBytes(sourceString); } internal static char[] ToCharArray(byte[] byteArray) { - return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); + return Encoding.UTF8.GetChars(byteArray); } } @@ -215,8 +217,9 @@ internal sealed class Adler { // largest prime smaller than 65536 private static int BASE = 65521; + // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 - private static int NMAX = 5552; + private static int nmax = 5552; static internal long Adler32(long adler, byte[] buf, int index, int len) { @@ -227,11 +230,11 @@ static internal long Adler32(long adler, byte[] buf, int index, int len) long s1 = adler & 0xffff; long s2 = (adler >> 16) & 0xffff; - int k; while (len > 0) { - k = len < NMAX ? len : NMAX; + int k = len < nmax ? len : nmax; + len -= k; while (k >= 16) @@ -270,16 +273,6 @@ static internal long Adler32(long adler, byte[] buf, int index, int len) return (s2 << 16) | s1; } - - /* - private java.util.zip.Adler32 adler=new java.util.zip.Adler32(); - long adler32(long value, byte[] buf, int index, int len){ - if(value==1) {adler.reset();} - if(buf==null) {adler.reset();} - else{adler.update(buf, index, len);} - return adler.getValue(); - } - */ } } diff --git a/RestSharp/Compression/ZLib/ZLibCodec.cs b/RestSharp/Compression/ZLib/ZLibCodec.cs index 86930349c..361921102 100644 --- a/RestSharp/Compression/ZLib/ZLibCodec.cs +++ b/RestSharp/Compression/ZLib/ZLibCodec.cs @@ -63,10 +63,8 @@ // // ----------------------------------------------------------------------- -#if WINDOWS_PHONE -using System; -using Interop = System.Runtime.InteropServices; +#if WINDOWS_PHONE namespace RestSharp.Compression.ZLib { @@ -133,11 +131,9 @@ sealed internal class ZlibCodec /// /// used for diagnostics, when something goes wrong! /// - public System.String Message; - - internal InflateManager istate; + public string Message; - internal long _Adler32; + internal InflateManager Istate; /// /// The number of Window Bits to use. @@ -148,20 +144,22 @@ sealed internal class ZlibCodec /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// - public int WindowBits = ZlibConstants.WindowBitsDefault; + public int WindowBits = ZlibConstants.WINDOW_BITS_DEFAULT; /// /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// - public long Adler32 { get { return _Adler32; } } + public long Adler32 { get; internal set; } /// /// Create a ZlibCodec that decompresses. /// public ZlibCodec() { - int rc = InitializeInflate(); - if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); + int rc = this.InitializeInflate(); + + if (rc != ZlibConstants.Z_OK) + throw new ZlibException("Cannot initialize for inflate."); } /// @@ -174,7 +172,7 @@ public ZlibCodec() /// Z_OK if everything goes well. public int InitializeInflate() { - return InitializeInflate(this.WindowBits); + return this.InitializeInflate(this.WindowBits); } /// @@ -197,7 +195,7 @@ public int InitializeInflate() /// Z_OK if everything goes well. public int InitializeInflate(bool expectRfc1950Header) { - return InitializeInflate(this.WindowBits, expectRfc1950Header); + return this.InitializeInflate(this.WindowBits, expectRfc1950Header); } /// @@ -209,7 +207,8 @@ public int InitializeInflate(bool expectRfc1950Header) public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; - return InitializeInflate(windowBits, true); + + return this.InitializeInflate(windowBits, true); } /// @@ -238,8 +237,9 @@ public int InitializeInflate(int windowBits, bool expectRfc1950Header) //if (dstate != null) // throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); - istate = new InflateManager(expectRfc1950Header); - return istate.Initialize(this, windowBits); + this.Istate = new InflateManager(expectRfc1950Header); + + return this.Istate.Initialize(this, windowBits); } /// @@ -307,10 +307,10 @@ public int InitializeInflate(int windowBits, bool expectRfc1950Header) /// Z_OK if everything goes well. public int Inflate(FlushType flush) { - if (istate == null) + if (this.Istate == null) throw new ZlibException("No Inflate State!"); - return istate.Inflate(flush); + return this.Istate.Inflate(flush); } /// @@ -324,12 +324,12 @@ public int Inflate(FlushType flush) /// Z_OK if everything goes well. public int EndInflate() { - if (istate == null) + if (this.Istate == null) throw new ZlibException("No Inflate State!"); - int ret = istate.End(); + int ret = this.Istate.End(); - istate = null; + this.Istate = null; return ret; } @@ -340,10 +340,10 @@ public int EndInflate() /// Z_OK if everything goes well. public int SyncInflate() { - if (istate == null) + if (this.Istate == null) throw new ZlibException("No Inflate State!"); - return istate.Sync(); + return this.Istate.Sync(); } /// @@ -353,8 +353,8 @@ public int SyncInflate() /// Z_OK if all goes well. public int SetDictionary(byte[] dictionary) { - if (istate != null) - return istate.SetDictionary(dictionary); + if (this.Istate != null) + return this.Istate.SetDictionary(dictionary); throw new ZlibException("No Inflate state!"); } diff --git a/RestSharp/Compression/ZLib/ZLibConstants.cs b/RestSharp/Compression/ZLib/ZLibConstants.cs index 18b878b2c..2c50393bf 100644 --- a/RestSharp/Compression/ZLib/ZLibConstants.cs +++ b/RestSharp/Compression/ZLib/ZLibConstants.cs @@ -60,9 +60,8 @@ // // ----------------------------------------------------------------------- -#if WINDOWS_PHONE -using System; +#if WINDOWS_PHONE namespace RestSharp.Compression.ZLib { @@ -74,12 +73,12 @@ internal static class ZlibConstants /// /// The maximum number of window bits for the Deflate algorithm. /// - public const int WindowBitsMax = 15; // 32K LZ77 window + public const int WINDOW_BITS_MAX = 15; // 32K LZ77 window /// /// The default number of window bits for the Deflate algorithm. /// - public const int WindowBitsDefault = WindowBitsMax; + public const int WINDOW_BITS_DEFAULT = WINDOW_BITS_MAX; /// /// indicates everything is A-OK @@ -114,12 +113,12 @@ internal static class ZlibConstants /// /// The size of the working buffer used in the ZlibCodec class. Defaults to 8192 bytes. /// - public const int WorkingBufferSizeDefault = 8192; // 8192; // 0x8000; // 16384; // 1024; + public const int WORKING_BUFFER_SIZE_DEFAULT = 8192; // 8192; // 0x8000; // 16384; // 1024; /// /// The minimum size of the working buffer used in the ZlibCodec class. Currently it is 128 bytes. /// - public const int WorkingBufferSizeMin = 128; + public const int WORKING_BUFFER_SIZE_MIN = 128; } } diff --git a/RestSharp/Compression/ZLib/ZLibStream.cs b/RestSharp/Compression/ZLib/ZLibStream.cs index 170adea94..02157c093 100644 --- a/RestSharp/Compression/ZLib/ZLibStream.cs +++ b/RestSharp/Compression/ZLib/ZLibStream.cs @@ -25,10 +25,13 @@ // // ------------------------------------------------------------------ + #if WINDOWS_PHONE using System; +using System.Collections.Generic; using System.IO; +using System.Text; namespace RestSharp.Compression.ZLib { @@ -69,14 +72,14 @@ namespace RestSharp.Compression.ZLib /// /// /// - internal class ZlibStream : System.IO.Stream + internal class ZlibStream : Stream { - internal ZlibBaseStream _baseStream; - bool _disposed; + internal ZlibBaseStream BaseStream; + bool disposed; - public ZlibStream(System.IO.Stream stream) + public ZlibStream(Stream stream) { - _baseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.ZLIB, false); + this.BaseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.Zlib, false); } #region Zlib properties @@ -87,13 +90,13 @@ public ZlibStream(System.IO.Stream stream) /// virtual public FlushType FlushMode { - get { return (this._baseStream._flushMode); } + get { return (this.BaseStream.FlushMode); } set { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - this._baseStream._flushMode = value; + this.BaseStream.FlushMode = value; } } @@ -115,32 +118,32 @@ virtual public FlushType FlushMode /// public int BufferSize { - get { return this._baseStream._bufferSize; } + get { return this.BaseStream.BufferSize; } set { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - if (this._baseStream._workingBuffer != null) + if (this.BaseStream.workingBuffer != null) throw new ZlibException("The working buffer is already set."); - if (value < ZlibConstants.WorkingBufferSizeMin) - throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", value)); + if (value < ZlibConstants.WORKING_BUFFER_SIZE_MIN) + throw new ZlibException(string.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", value)); - this._baseStream._bufferSize = value; + this.BaseStream.BufferSize = value; } } /// Returns the total number of bytes input so far. virtual public long TotalIn { - get { return this._baseStream._z.TotalBytesIn; } + get { return this.BaseStream.z.TotalBytesIn; } } /// Returns the total number of bytes output so far. virtual public long TotalOut { - get { return this._baseStream._z.TotalBytesOut; } + get { return this.BaseStream.z.TotalBytesOut; } } #endregion @@ -158,12 +161,12 @@ protected override void Dispose(bool disposing) { try { - if (!_disposed) + if (!this.disposed) { - if (disposing && (this._baseStream != null)) - this._baseStream.Close(); + if (disposing && (this.BaseStream != null)) + this.BaseStream.Close(); - _disposed = true; + this.disposed = true; } } finally @@ -182,10 +185,10 @@ public override bool CanRead { get { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - return _baseStream._stream.CanRead; + return this.BaseStream.Stream.CanRead; } } @@ -210,10 +213,10 @@ public override bool CanWrite { get { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - return _baseStream._stream.CanWrite; + return this.BaseStream.Stream.CanWrite; } } @@ -222,10 +225,10 @@ public override bool CanWrite /// public override void Flush() { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - _baseStream.Flush(); + this.BaseStream.Flush(); } /// @@ -249,11 +252,14 @@ public override long Position { get { - if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Writer) - return this._baseStream._z.TotalBytesOut; + switch (this.BaseStream.streamMode) + { + case ZlibBaseStream.StreamMode.Writer: + return this.BaseStream.z.TotalBytesOut; - if (this._baseStream._streamMode == ZlibBaseStream.StreamMode.Reader) - return this._baseStream._z.TotalBytesIn; + case ZlibBaseStream.StreamMode.Reader: + return this.BaseStream.z.TotalBytesIn; + } return 0; } @@ -284,16 +290,16 @@ public override long Position /// the number of bytes to read. public override int Read(byte[] buffer, int offset, int count) { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - return _baseStream.Read(buffer, offset, count); + return this.BaseStream.Read(buffer, offset, count); } /// /// Calling this method always throws a NotImplementedException. /// - public override long Seek(long offset, System.IO.SeekOrigin origin) + public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } @@ -332,10 +338,10 @@ public override void SetLength(long value) /// the number of bytes to write. public override void Write(byte[] buffer, int offset, int count) { - if (_disposed) + if (this.disposed) throw new ObjectDisposedException("ZlibStream"); - _baseStream.Write(buffer, offset, count); + this.BaseStream.Write(buffer, offset, count); } #endregion @@ -347,15 +353,15 @@ public override void Write(byte[] buffer, int offset, int count) /// /// A buffer containing ZLIB-compressed data. /// - public static String UncompressString(byte[] compressed) + public static string UncompressString(byte[] compressed) { // workitem 8460 byte[] working = new byte[1024]; - var encoding = System.Text.Encoding.UTF8; + Encoding encoding = Encoding.UTF8; - using (var output = new MemoryStream()) + using (MemoryStream output = new MemoryStream()) { - using (var input = new MemoryStream(compressed)) + using (MemoryStream input = new MemoryStream(compressed)) { using (Stream decompressor = new ZlibStream(input)) { @@ -369,7 +375,9 @@ public static String UncompressString(byte[] compressed) // reset to allow read from start output.Seek(0, SeekOrigin.Begin); - var sr = new StreamReader(output, encoding); + + StreamReader sr = new StreamReader(output, encoding); + return sr.ReadToEnd(); } } @@ -388,9 +396,9 @@ public static byte[] UncompressBuffer(byte[] compressed) // workitem 8460 byte[] working = new byte[1024]; - using (var output = new MemoryStream()) + using (MemoryStream output = new MemoryStream()) { - using (var input = new MemoryStream(compressed)) + using (MemoryStream input = new MemoryStream(compressed)) { using (Stream decompressor = new ZlibStream(input)) { @@ -407,70 +415,69 @@ public static byte[] UncompressBuffer(byte[] compressed) } } - internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } + internal enum ZlibStreamFlavor + { + Zlib = 1950, + Deflate = 1951, + Gzip = 1952 + } - internal class ZlibBaseStream : System.IO.Stream + internal class ZlibBaseStream : Stream { - protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); + protected internal ZlibCodec z; // deferred init... new ZlibCodec(); - protected internal StreamMode _streamMode = StreamMode.Undefined; - protected internal FlushType _flushMode; - protected internal ZlibStreamFlavor _flavor; - protected internal bool _leaveOpen; - protected internal byte[] _workingBuffer; - protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; - protected internal byte[] _buf1 = new byte[1]; - protected internal System.IO.Stream _stream; + protected internal StreamMode streamMode = StreamMode.Undefined; + protected internal FlushType FlushMode; + protected internal ZlibStreamFlavor Flavor; + protected internal bool LeaveOpen; + protected internal byte[] workingBuffer; + protected internal int BufferSize = ZlibConstants.WORKING_BUFFER_SIZE_DEFAULT; + protected internal byte[] Buf1 = new byte[1]; + protected internal Stream Stream; // workitem 7159 - CRC32 crc; - protected internal string _GzipFileName; - protected internal string _GzipComment; - protected internal DateTime _GzipMtime; - protected internal int _gzipHeaderByteCount; - - internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } - - public ZlibBaseStream(System.IO.Stream stream, ZlibStreamFlavor flavor, bool leaveOpen) - : base() - { - this._flushMode = FlushType.None; - //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; - this._stream = stream; - this._leaveOpen = leaveOpen; - this._flavor = flavor; + Crc32 crc; + protected internal string GzipFileName; + protected internal string GzipComment; + protected internal DateTime GzipMtime; + protected internal int GzipHeaderByteCount; + + internal int Crc32 { get { return this.crc == null ? 0 : this.crc.Crc32Result; } } + + public ZlibBaseStream(Stream stream, ZlibStreamFlavor flavor, bool leaveOpen) + { + this.FlushMode = FlushType.None; + //_workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; + this.Stream = stream; + this.LeaveOpen = leaveOpen; + this.Flavor = flavor; // workitem 7159 - if (flavor == ZlibStreamFlavor.GZIP) + if (flavor == ZlibStreamFlavor.Gzip) { - crc = new CRC32(); + this.crc = new Crc32(); } } - private ZlibCodec z + private ZlibCodec Z { get { - if (_z == null) + if (this.z == null) { - bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); - _z = new ZlibCodec(); - _z.InitializeInflate(wantRfc1950Header); + bool wantRfc1950Header = (this.Flavor == ZlibStreamFlavor.Zlib); + + this.z = new ZlibCodec(); + this.z.InitializeInflate(wantRfc1950Header); } - return _z; + return this.z; } } - private byte[] workingBuffer + private byte[] WorkingBuffer { - get - { - if (_workingBuffer == null) - _workingBuffer = new byte[_bufferSize]; - - return _workingBuffer; - } + get { return this.workingBuffer ?? (this.workingBuffer = new byte[this.BufferSize]); } } // workitem 7813 - totally unnecessary @@ -483,137 +490,139 @@ private byte[] workingBuffer // Write(_buf1, 0, 1); // } - public override void Write(System.Byte[] buffer, int offset, int count) + public override void Write(byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) - if (crc != null) - crc.SlurpBlock(buffer, offset, count); + if (this.crc != null) + this.crc.SlurpBlock(buffer, offset, count); - if (_streamMode == StreamMode.Undefined) - _streamMode = StreamMode.Writer; - else if (_streamMode != StreamMode.Writer) + if (this.streamMode == StreamMode.Undefined) + this.streamMode = StreamMode.Writer; + else if (this.streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z - z.InputBuffer = buffer; - _z.NextIn = offset; - _z.AvailableBytesIn = count; + this.z.InputBuffer = buffer; + this.z.NextIn = offset; + this.z.AvailableBytesIn = count; - bool done = false; + bool done; do { - _z.OutputBuffer = workingBuffer; - _z.NextOut = 0; - _z.AvailableBytesOut = _workingBuffer.Length; + this.z.OutputBuffer = this.WorkingBuffer; + this.z.NextOut = 0; + this.z.AvailableBytesOut = this.workingBuffer.Length; //int rc = (_wantCompress) // ? _z.Deflate(_flushMode) // : _z.Inflate(_flushMode); - int rc = _z.Inflate(_flushMode); + int rc = this.z.Inflate(this.FlushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) - throw new ZlibException("inflating: " + _z.Message); + throw new ZlibException("inflating: " + this.z.Message); - _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); + this.Stream.Write(this.workingBuffer, 0, this.workingBuffer.Length - this.z.AvailableBytesOut); - done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; + done = this.z.AvailableBytesIn == 0 && this.z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. - if (_flavor == ZlibStreamFlavor.GZIP) - done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); + if (this.Flavor == ZlibStreamFlavor.Gzip) + done = (this.z.AvailableBytesIn == 8 && this.z.AvailableBytesOut != 0); } while (!done); } - private void finish() + private void Finish() { - if (_z == null) + if (this.z == null) return; - if (_streamMode == StreamMode.Writer) + switch (this.streamMode) { - bool done = false; + case StreamMode.Writer: + bool done; - do - { - _z.OutputBuffer = workingBuffer; - _z.NextOut = 0; - _z.AvailableBytesOut = _workingBuffer.Length; + do + { + this.z.OutputBuffer = this.WorkingBuffer; + this.z.NextOut = 0; + this.z.AvailableBytesOut = this.workingBuffer.Length; - //int rc = (_wantCompress) - // ? _z.Deflate(FlushType.Finish) - // : _z.Inflate(FlushType.Finish); + //int rc = (_wantCompress) + // ? _z.Deflate(FlushType.Finish) + // : _z.Inflate(FlushType.Finish); - int rc = _z.Inflate(FlushType.Finish); + int rc = this.z.Inflate(FlushType.Finish); - if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) - throw new ZlibException("inflating: " + _z.Message); + if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) + throw new ZlibException("inflating: " + this.z.Message); - if (_workingBuffer.Length - _z.AvailableBytesOut > 0) - { - _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); - } + if (this.workingBuffer.Length - this.z.AvailableBytesOut > 0) + { + this.Stream.Write(this.workingBuffer, 0, this.workingBuffer.Length - this.z.AvailableBytesOut); + } - done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; + done = this.z.AvailableBytesIn == 0 && this.z.AvailableBytesOut != 0; - // If GZIP and de-compress, we're done when 8 bytes remain. - if (_flavor == ZlibStreamFlavor.GZIP) - done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); - } - while (!done); + // If GZIP and de-compress, we're done when 8 bytes remain. + if (this.Flavor == ZlibStreamFlavor.Gzip) + done = (this.z.AvailableBytesIn == 8 && this.z.AvailableBytesOut != 0); + } + while (!done); - Flush(); + this.Flush(); - // workitem 7159 - if (_flavor == ZlibStreamFlavor.GZIP) - { - //Console.WriteLine("GZipStream: Last write"); - throw new ZlibException("Writing with decompression is not supported."); - } - } - // workitem 7159 - else if (_streamMode == StreamMode.Reader) - { - if (_flavor == ZlibStreamFlavor.GZIP) - { - // workitem 8501: handle edge case (decompress empty stream) - if (_z.TotalBytesOut == 0L) - return; + // workitem 7159 + if (this.Flavor == ZlibStreamFlavor.Gzip) + { + //Console.WriteLine("GZipStream: Last write"); + throw new ZlibException("Writing with decompression is not supported."); + } + break; - // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 - byte[] trailer = new byte[8]; + case StreamMode.Reader: + if (this.Flavor == ZlibStreamFlavor.Gzip) + { + // workitem 8501: handle edge case (decompress empty stream) + if (this.z.TotalBytesOut == 0L) + return; - if (_z.AvailableBytesIn != 8) - throw new ZlibException(String.Format("Protocol error. AvailableBytesIn={0}, expected 8", - _z.AvailableBytesIn)); + // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 + byte[] trailer = new byte[8]; - Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); + if (this.z.AvailableBytesIn != 8) + { + throw new ZlibException(string.Format("Protocol error. AvailableBytesIn={0}, expected 8", this.z.AvailableBytesIn)); + } - Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); - int crc32_actual = crc.Crc32Result; - Int32 isize_expected = BitConverter.ToInt32(trailer, 4); - Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); + Array.Copy(this.z.InputBuffer, this.z.NextIn, trailer, 0, trailer.Length); - // Console.WriteLine("GZipStream: slurped trailer crc(0x{0:X8}) isize({1})", crc32_expected, isize_expected); - // Console.WriteLine("GZipStream: calc'd data crc(0x{0:X8}) isize({1})", crc32_actual, isize_actual); + int crc32Expected = BitConverter.ToInt32(trailer, 0); + int crc32Actual = this.crc.Crc32Result; + int isizeExpected = BitConverter.ToInt32(trailer, 4); + int isizeActual = (int) (this.z.TotalBytesOut & 0x00000000FFFFFFFF); - if (crc32_actual != crc32_expected) - throw new ZlibException(String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); + // Console.WriteLine("GZipStream: slurped trailer crc(0x{0:X8}) isize({1})", crc32_expected, isize_expected); + // Console.WriteLine("GZipStream: calc'd data crc(0x{0:X8}) isize({1})", crc32_actual, isize_actual); - if (isize_actual != isize_expected) - throw new ZlibException(String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, isize_expected)); - } + if (crc32Actual != crc32Expected) + throw new ZlibException(string.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32Actual, crc32Expected)); + + if (isizeActual != isizeExpected) + throw new ZlibException(string.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isizeActual, isizeExpected)); + } + break; } } - private void end() + private void End() { - if (z == null) + if (this.Z == null) return; //if (_wantCompress) @@ -621,47 +630,47 @@ private void end() // _z.EndDeflate(); //} //else - { - _z.EndInflate(); - } + //{ + this.z.EndInflate(); + //} - _z = null; + this.z = null; } public override void Close() { - if (_stream == null) + if (this.Stream == null) return; try { - finish(); + this.Finish(); } finally { - end(); + this.End(); - if (!_leaveOpen) - _stream.Close(); + if (!this.LeaveOpen) + this.Stream.Close(); - _stream = null; + this.Stream = null; } } public override void Flush() { - _stream.Flush(); + this.Stream.Flush(); } - public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) + public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); //_outStream.Seek(offset, origin); } - public override void SetLength(System.Int64 value) + public override void SetLength(long value) { - _stream.SetLength(value); + this.Stream.SetLength(value); } #if NOT @@ -678,31 +687,30 @@ public int Read() } #endif - private bool nomoreinput = false; + private bool nomoreinput; private string ReadZeroTerminatedString() { - var list = new System.Collections.Generic.List(); + List list = new List(); bool done = false; do { // workitem 7740 - int n = _stream.Read(_buf1, 0, 1); + int n = this.Stream.Read(this.Buf1, 0, 1); if (n != 1) throw new ZlibException("Unexpected EOF reading GZIP header."); + + if (this.Buf1[0] == 0) + done = true; else - { - if (_buf1[0] == 0) - done = true; - else - list.Add(_buf1[0]); - } + list.Add(this.Buf1[0]); } while (!done); byte[] a = list.ToArray(); - return GZipStream.iso8859dash1.GetString(a, 0, a.Length); + + return GZipStream.Iso8859Dash1.GetString(a, 0, a.Length); } private int _ReadAndValidateGzipHeader() @@ -710,7 +718,7 @@ private int _ReadAndValidateGzipHeader() int totalBytesRead = 0; // read the header on the first read byte[] header = new byte[10]; - int n = _stream.Read(header, 0, header.Length); + int n = this.Stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) @@ -722,37 +730,41 @@ private int _ReadAndValidateGzipHeader() if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) throw new ZlibException("Bad GZIP header."); - Int32 timet = BitConverter.ToInt32(header, 4); + int timet = BitConverter.ToInt32(header, 4); - _GzipMtime = GZipStream._unixEpoch.AddSeconds(timet); + this.GzipMtime = GZipStream.UnixEpoch.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field - n = _stream.Read(header, 0, 2); // 2-byte length field + n = this.Stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; - Int16 extraLength = (Int16)(header[0] + header[1] * 256); + short extraLength = (short) (header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; - n = _stream.Read(extra, 0, extra.Length); + + n = this.Stream.Read(extra, 0, extra.Length); + if (n != extraLength) throw new ZlibException("Unexpected end-of-file reading GZIP header."); + totalBytesRead += n; } + if ((header[3] & 0x08) == 0x08) - _GzipFileName = ReadZeroTerminatedString(); + this.GzipFileName = this.ReadZeroTerminatedString(); + if ((header[3] & 0x10) == 0x010) - _GzipComment = ReadZeroTerminatedString(); + this.GzipComment = this.ReadZeroTerminatedString(); + if ((header[3] & 0x02) == 0x02) - Read(_buf1, 0, 1); // CRC16, ignore + this.Read(this.Buf1, 0, 1); // CRC16, ignore return totalBytesRead; } - - - public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) + public override int Read(byte[] buffer, int offset, int count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, @@ -760,85 +772,101 @@ public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, Sys // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to bytes - if (_streamMode == StreamMode.Undefined) + if (this.streamMode == StreamMode.Undefined) { - if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); + if (!this.Stream.CanRead) + throw new ZlibException("The stream is not readable."); + // for the first read, set up some controls. - _streamMode = StreamMode.Reader; + this.streamMode = StreamMode.Reader; + // (The first reference to _z goes through the private accessor which // may initialize it.) - z.AvailableBytesIn = 0; - if (_flavor == ZlibStreamFlavor.GZIP) + this.Z.AvailableBytesIn = 0; + + if (this.Flavor == ZlibStreamFlavor.Gzip) { - _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); + this.GzipHeaderByteCount = this._ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) - if (_gzipHeaderByteCount == 0) + + if (this.GzipHeaderByteCount == 0) return 0; } } - if (_streamMode != StreamMode.Reader) + if (this.streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); - if (count == 0) return 0; - if (buffer == null) throw new ArgumentNullException("buffer"); - if (count < 0) throw new ArgumentOutOfRangeException("count"); - if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); - if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); + if (count == 0) + return 0; + + if (buffer == null) + throw new ArgumentNullException("buffer"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count"); + + if (offset < buffer.GetLowerBound(0)) + throw new ArgumentOutOfRangeException("offset"); + + if ((offset + count) > buffer.GetLength(0)) + throw new ArgumentOutOfRangeException("count"); - int rc = 0; + int rc; // set up the output of the deflate/inflate codec: - _z.OutputBuffer = buffer; - _z.NextOut = offset; - _z.AvailableBytesOut = count; + this.z.OutputBuffer = buffer; + this.z.NextOut = offset; + this.z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) - _z.InputBuffer = workingBuffer; + this.z.InputBuffer = this.WorkingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. - if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) + if ((this.z.AvailableBytesIn == 0) && (!this.nomoreinput)) { // No data available, so try to Read data from the captive stream. - _z.NextIn = 0; - _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); - if (_z.AvailableBytesIn == 0) - nomoreinput = true; + this.z.NextIn = 0; + this.z.AvailableBytesIn = this.Stream.Read(this.workingBuffer, 0, this.workingBuffer.Length); + + if (this.z.AvailableBytesIn == 0) + this.nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate //rc = (_wantCompress) // ? _z.Deflate(_flushMode) // : _z.Inflate(_flushMode); - rc = _z.Inflate(_flushMode); - if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) + rc = this.z.Inflate(this.FlushMode); + + if (this.nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) - throw new ZlibException(String.Format("inflating: rc={0} msg={1}", rc, _z.Message)); + throw new ZlibException(string.Format("inflating: rc={0} msg={1}", rc, this.z.Message)); - if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) + if ((this.nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (this.z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); - while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); + while (this.z.AvailableBytesOut > 0 && !this.nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? - if (_z.AvailableBytesOut > 0) + if (this.z.AvailableBytesOut > 0) { - if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) + if (rc == ZlibConstants.Z_OK && this.z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? - if (nomoreinput) + if (this.nomoreinput) { // and in compression? /*if (_wantCompress) @@ -854,35 +882,33 @@ public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, Sys } - rc = (count - _z.AvailableBytesOut); + rc = (count - this.z.AvailableBytesOut); // calculate CRC after reading - if (crc != null) - crc.SlurpBlock(buffer, offset, rc); + if (this.crc != null) + this.crc.SlurpBlock(buffer, offset, rc); return rc; } - - - public override System.Boolean CanRead + public override bool CanRead { - get { return this._stream.CanRead; } + get { return this.Stream.CanRead; } } - public override System.Boolean CanSeek + public override bool CanSeek { - get { return this._stream.CanSeek; } + get { return this.Stream.CanSeek; } } - public override System.Boolean CanWrite + public override bool CanWrite { - get { return this._stream.CanWrite; } + get { return this.Stream.CanWrite; } } - public override System.Int64 Length + public override long Length { - get { return _stream.Length; } + get { return this.Stream.Length; } } public override long Position @@ -898,7 +924,6 @@ internal enum StreamMode Undefined, } } - } #endif diff --git a/RestSharp/Deserializers/DeserializeAsAttribute.cs b/RestSharp/Deserializers/DeserializeAsAttribute.cs index 3fea84323..6141e8637 100644 --- a/RestSharp/Deserializers/DeserializeAsAttribute.cs +++ b/RestSharp/Deserializers/DeserializeAsAttribute.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -21,7 +23,7 @@ namespace RestSharp.Deserializers /// /// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)] public sealed class DeserializeAsAttribute : Attribute { /// diff --git a/RestSharp/Deserializers/DotNetXmlDeserializer.cs b/RestSharp/Deserializers/DotNetXmlDeserializer.cs index 9b58f4ca4..69f06767b 100644 --- a/RestSharp/Deserializers/DotNetXmlDeserializer.cs +++ b/RestSharp/Deserializers/DotNetXmlDeserializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,10 +13,12 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System.IO; using System.Text; +using System.Xml.Serialization; namespace RestSharp.Deserializers { @@ -37,10 +40,11 @@ public T Deserialize(IRestResponse response) return default(T); } - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content))) + using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content))) { - var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); - return (T)serializer.Deserialize(stream); + XmlSerializer serializer = new XmlSerializer(typeof(T)); + + return (T) serializer.Deserialize(stream); } } } diff --git a/RestSharp/Deserializers/IDeserializer.cs b/RestSharp/Deserializers/IDeserializer.cs index e293a3966..aff48d444 100644 --- a/RestSharp/Deserializers/IDeserializer.cs +++ b/RestSharp/Deserializers/IDeserializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion namespace RestSharp.Deserializers @@ -19,8 +21,11 @@ namespace RestSharp.Deserializers public interface IDeserializer { T Deserialize(IRestResponse response); + string RootElement { get; set; } + string Namespace { get; set; } + string DateFormat { get; set; } } } diff --git a/RestSharp/Deserializers/JsonDeserializer.cs b/RestSharp/Deserializers/JsonDeserializer.cs index 4c0116fd0..ef773c9d9 100644 --- a/RestSharp/Deserializers/JsonDeserializer.cs +++ b/RestSharp/Deserializers/JsonDeserializer.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Reflection; using RestSharp.Extensions; namespace RestSharp.Deserializers @@ -21,37 +22,41 @@ public class JsonDeserializer : IDeserializer public JsonDeserializer() { - Culture = CultureInfo.InvariantCulture; + this.Culture = CultureInfo.InvariantCulture; } public T Deserialize(IRestResponse response) { - var target = Activator.CreateInstance(); + T target = Activator.CreateInstance(); if (target is IList) { - var objType = target.GetType(); + Type objType = target.GetType(); - if (RootElement.HasValue()) + if (this.RootElement.HasValue()) { - var root = FindRoot(response.Content); - target = (T)BuildList(objType, root); + object root = this.FindRoot(response.Content); + + target = (T) this.BuildList(objType, root); } else { - var data = SimpleJson.DeserializeObject(response.Content); - target = (T)BuildList(objType, data); + object data = SimpleJson.DeserializeObject(response.Content); + + target = (T) this.BuildList(objType, data); } } else if (target is IDictionary) { - var root = FindRoot(response.Content); - target = (T)BuildDictionary(target.GetType(), root); + object root = this.FindRoot(response.Content); + + target = (T) this.BuildDictionary(target.GetType(), root); } else { - var root = FindRoot(response.Content); - target = (T)Map(target, (IDictionary)root); + object root = this.FindRoot(response.Content); + + target = (T) this.Map(target, (IDictionary) root); } return target; @@ -59,11 +64,11 @@ public T Deserialize(IRestResponse response) private object FindRoot(string content) { - var data = (IDictionary)SimpleJson.DeserializeObject(content); + IDictionary data = (IDictionary) SimpleJson.DeserializeObject(content); - if (RootElement.HasValue() && data.ContainsKey(RootElement)) + if (this.RootElement.HasValue() && data.ContainsKey(this.RootElement)) { - return data[RootElement]; + return data[this.RootElement]; } return data; @@ -71,18 +76,20 @@ private object FindRoot(string content) private object Map(object target, IDictionary data) { - var objType = target.GetType(); - var props = objType.GetProperties().Where(p => p.CanWrite).ToList(); + Type objType = target.GetType(); + List props = objType.GetProperties() + .Where(p => p.CanWrite) + .ToList(); - foreach (var prop in props) + foreach (PropertyInfo prop in props) { - var type = prop.PropertyType; - var attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); + Type type = prop.PropertyType; + object[] attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); string name; if (attributes.Length > 0) { - var attribute = (DeserializeAsAttribute)attributes[0]; + DeserializeAsAttribute attribute = (DeserializeAsAttribute) attributes[0]; name = attribute.Name; } else @@ -90,25 +97,34 @@ private object Map(object target, IDictionary data) name = prop.Name; } - var parts = name.Split('.'); - var currentData = data; + string[] parts = name.Split('.'); + IDictionary currentData = data; object value = null; - for (var i = 0; i < parts.Length; ++i) + for (int i = 0; i < parts.Length; ++i) { - var actualName = parts[i].GetNameVariants(Culture).FirstOrDefault(currentData.ContainsKey); + string actualName = parts[i].GetNameVariants(this.Culture) + .FirstOrDefault(currentData.ContainsKey); if (actualName == null) + { break; + } if (i == parts.Length - 1) + { value = currentData[actualName]; + } else - currentData = (IDictionary)currentData[actualName]; + { + currentData = (IDictionary) currentData[actualName]; + } } if (value != null) - prop.SetValue(target, ConvertValue(type, value), null); + { + prop.SetValue(target, this.ConvertValue(type, value), null); + } } return target; @@ -116,25 +132,25 @@ private object Map(object target, IDictionary data) private IDictionary BuildDictionary(Type type, object parent) { - var dict = (IDictionary)Activator.CreateInstance(type); - var keyType = type.GetGenericArguments()[0]; - var valueType = type.GetGenericArguments()[1]; + IDictionary dict = (IDictionary) Activator.CreateInstance(type); + Type keyType = type.GetGenericArguments()[0]; + Type valueType = type.GetGenericArguments()[1]; - foreach (var child in (IDictionary)parent) + foreach (KeyValuePair child in (IDictionary) parent) { - var key = keyType != typeof (string) ? - Convert.ChangeType(child.Key, keyType, CultureInfo.InvariantCulture) : - child.Key; + object key = keyType != typeof(string) + ? Convert.ChangeType(child.Key, keyType, CultureInfo.InvariantCulture) + : child.Key; object item; if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List<>)) { - item = BuildList(valueType, child.Value); + item = this.BuildList(valueType, child.Value); } else { - item = ConvertValue(valueType, child.Value); + item = this.ConvertValue(valueType, child.Value); } dict.Add(key, item); @@ -145,17 +161,20 @@ private IDictionary BuildDictionary(Type type, object parent) private IList BuildList(Type type, object parent) { - var list = (IList)Activator.CreateInstance(type); - var listType = type.GetInterfaces().First(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)); - var itemType = listType.GetGenericArguments()[0]; + IList list = (IList) Activator.CreateInstance(type); + Type listType = type.GetInterfaces() + .First + (x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)); + Type itemType = listType.GetGenericArguments()[0]; if (parent is IList) { - foreach (var element in (IList)parent) + foreach (object element in (IList) parent) { if (itemType.IsPrimitive) { - var item = ConvertValue(itemType, element); + object item = this.ConvertValue(itemType, element); + list.Add(item); } else if (itemType == typeof(string)) @@ -176,14 +195,15 @@ private IList BuildList(Type type, object parent) continue; } - var item = ConvertValue(itemType, element); + object item = this.ConvertValue(itemType, element); + list.Add(item); } } } else { - list.Add(ConvertValue(itemType, parent)); + list.Add(this.ConvertValue(itemType, parent)); } return list; @@ -191,31 +211,33 @@ private IList BuildList(Type type, object parent) private object ConvertValue(Type type, object value) { - var stringValue = Convert.ToString(value, Culture); + string stringValue = Convert.ToString(value, this.Culture); // check for nullable and extract underlying type if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { // Since the type is nullable and no value is provided return null - if (String.IsNullOrEmpty(stringValue)) + if (string.IsNullOrEmpty(stringValue)) + { return null; + } type = type.GetGenericArguments()[0]; } - if (type == typeof(Object) && value != null) + if (type == typeof(object) && value != null) { type = value.GetType(); } if (type.IsPrimitive) { - return value.ChangeType(type, Culture); + return value.ChangeType(type, this.Culture); } if (type.IsEnum) { - return type.FindEnumValue(stringValue, Culture); + return type.FindEnumValue(stringValue, this.Culture); } if (type == typeof(Uri)) @@ -228,28 +250,21 @@ private object ConvertValue(Type type, object value) return stringValue; } - if (type == typeof(DateTime) -#if !PocketPC - || type == typeof(DateTimeOffset) -#endif - ) + if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { DateTime dt; - if (DateFormat.HasValue()) + if (this.DateFormat.HasValue()) { - dt = DateTime.ParseExact(stringValue, DateFormat, Culture, + dt = DateTime.ParseExact(stringValue, this.DateFormat, this.Culture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); } else { // try parsing instead - dt = stringValue.ParseJsonDate(Culture); + dt = stringValue.ParseJsonDate(this.Culture); } -#if PocketPC - return dt; -#else if (type == typeof(DateTime)) { return dt; @@ -257,27 +272,33 @@ private object ConvertValue(Type type, object value) if (type == typeof(DateTimeOffset)) { - return (DateTimeOffset)dt; + return (DateTimeOffset) dt; } -#endif } - else if (type == typeof(Decimal)) + else if (type == typeof(decimal)) { if (value is double) - return (decimal)((double)value); + { + return (decimal) ((double) value); + } if (stringValue.Contains("e")) - return Decimal.Parse(stringValue, NumberStyles.Float, Culture); + { + return decimal.Parse(stringValue, NumberStyles.Float, this.Culture); + } - return Decimal.Parse(stringValue, Culture); + return decimal.Parse(stringValue, this.Culture); } else if (type == typeof(Guid)) { - return string.IsNullOrEmpty(stringValue) ? Guid.Empty : new Guid(stringValue); + return string.IsNullOrEmpty(stringValue) + ? Guid.Empty + : new Guid(stringValue); } else if (type == typeof(TimeSpan)) { TimeSpan timeSpan; + if (TimeSpan.TryParse(stringValue, out timeSpan)) { return timeSpan; @@ -288,43 +309,43 @@ private object ConvertValue(Type type, object value) } else if (type.IsGenericType) { - var genericTypeDef = type.GetGenericTypeDefinition(); + Type genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef == typeof(List<>)) { - return BuildList(type, value); + return this.BuildList(type, value); } if (genericTypeDef == typeof(Dictionary<,>)) { - var keyType = type.GetGenericArguments()[0]; + Type keyType = type.GetGenericArguments()[0]; // only supports Dict() if (keyType == typeof(string)) { - return BuildDictionary(type, value); + return this.BuildDictionary(type, value); } } else { // nested property classes - return CreateAndMap(type, value); + return this.CreateAndMap(type, value); } } else if (type.IsSubclassOfRawGeneric(typeof(List<>))) { // handles classes that derive from List - return BuildList(type, value); + return this.BuildList(type, value); } else if (type == typeof(JsonObject)) { // simplify JsonObject into a Dictionary - return BuildDictionary(typeof(Dictionary), value); + return this.BuildDictionary(typeof(Dictionary), value); } else { // nested property classes - return CreateAndMap(type, value); + return this.CreateAndMap(type, value); } return null; @@ -332,9 +353,9 @@ private object ConvertValue(Type type, object value) private object CreateAndMap(Type type, object element) { - var instance = Activator.CreateInstance(type); + object instance = Activator.CreateInstance(type); - Map(instance, (IDictionary)element); + this.Map(instance, (IDictionary) element); return instance; } diff --git a/RestSharp/Deserializers/XmlAttributeDeserializer.cs b/RestSharp/Deserializers/XmlAttributeDeserializer.cs index a9dac6ae9..8d44cee80 100644 --- a/RestSharp/Deserializers/XmlAttributeDeserializer.cs +++ b/RestSharp/Deserializers/XmlAttributeDeserializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System.Reflection; @@ -24,10 +26,10 @@ public class XmlAttributeDeserializer : XmlDeserializer { protected override object GetValueFromXml(XElement root, XName name, PropertyInfo prop) { - var isAttribute = false; + bool isAttribute = false; //Check for the DeserializeAs attribute on the property - var options = prop.GetAttribute(); + DeserializeAsAttribute options = prop.GetAttribute(); if (options != null) { @@ -37,7 +39,7 @@ protected override object GetValueFromXml(XElement root, XName name, PropertyInf if (isAttribute) { - var attributeVal = GetAttributeByName(root, name); + XAttribute attributeVal = GetAttributeByName(root, name); if (attributeVal != null) { diff --git a/RestSharp/Deserializers/XmlDeserializer.cs b/RestSharp/Deserializers/XmlDeserializer.cs index 63c067a3d..c76acc530 100644 --- a/RestSharp/Deserializers/XmlDeserializer.cs +++ b/RestSharp/Deserializers/XmlDeserializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,12 +13,12 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Collections; using System.Collections.Generic; -using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; @@ -25,6 +26,10 @@ using System.Xml.Linq; using RestSharp.Extensions; +#if !SILVERLIGHT && !WINDOWS_PHONE +using System.ComponentModel; +#endif + namespace RestSharp.Deserializers { public class XmlDeserializer : IDeserializer @@ -39,108 +44,116 @@ public class XmlDeserializer : IDeserializer public XmlDeserializer() { - Culture = CultureInfo.InvariantCulture; + this.Culture = CultureInfo.InvariantCulture; } public virtual T Deserialize(IRestResponse response) { if (string.IsNullOrEmpty(response.Content)) + { return default(T); + } - var doc = XDocument.Parse(response.Content); - var root = doc.Root; + XDocument doc = XDocument.Parse(response.Content); + XElement root = doc.Root; - if (RootElement.HasValue() && doc.Root != null) + if (this.RootElement.HasValue() && doc.Root != null) { - root = doc.Root.Element(RootElement.AsNamespaced(Namespace)); + root = doc.Root.Element(this.RootElement.AsNamespaced(this.Namespace)); } // autodetect xml namespace - if (!Namespace.HasValue()) + if (!this.Namespace.HasValue()) { RemoveNamespace(doc); } - var x = Activator.CreateInstance(); - var objType = x.GetType(); + T x = Activator.CreateInstance(); + Type objType = x.GetType(); if (objType.IsSubclassOfRawGeneric(typeof(List<>))) { - x = (T)HandleListDerivative(x, root, objType.Name, objType); + x = (T) this.HandleListDerivative(root, objType.Name, objType); } else { - x = (T)Map(x, root); + x = (T) this.Map(x, root); } return x; } - private void RemoveNamespace(XDocument xdoc) + private static void RemoveNamespace(XDocument xdoc) { - foreach (XElement e in xdoc.Root.DescendantsAndSelf()) + if (xdoc.Root != null) { - if (e.Name.Namespace != XNamespace.None) + foreach (XElement e in xdoc.Root.DescendantsAndSelf()) { - e.Name = XNamespace.None.GetName(e.Name.LocalName); - } + if (e.Name.Namespace != XNamespace.None) + { + e.Name = XNamespace.None.GetName(e.Name.LocalName); + } - if (e.Attributes().Any(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None)) - { - e.ReplaceAttributes( - e.Attributes() - .Select( - a => - a.IsNamespaceDeclaration - ? null - : a.Name.Namespace != XNamespace.None - ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) - : a)); + if (e.Attributes() + .Any(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None)) + { + e.ReplaceAttributes( + e.Attributes() + .Select(a => a.IsNamespaceDeclaration + ? null + : a.Name.Namespace != XNamespace.None + ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) + : a)); + } } } } protected virtual object Map(object x, XElement root) { - var objType = x.GetType(); - var props = objType.GetProperties(); + Type objType = x.GetType(); + PropertyInfo[] props = objType.GetProperties(); - foreach (var prop in props) + foreach (PropertyInfo prop in props) { - var type = prop.PropertyType; - var typeIsPublic = type.IsPublic || type.IsNestedPublic; + Type type = prop.PropertyType; + bool typeIsPublic = type.IsPublic || type.IsNestedPublic; if (!typeIsPublic || !prop.CanWrite) + { continue; + } - var attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); + object[] attributes = prop.GetCustomAttributes(typeof(DeserializeAsAttribute), false); XName name; if (attributes.Length > 0) { - var attribute = (DeserializeAsAttribute)attributes[0]; - name = attribute.Name.AsNamespaced(Namespace); + DeserializeAsAttribute attribute = (DeserializeAsAttribute) attributes[0]; + + name = attribute.Name.AsNamespaced(this.Namespace); } else { - name = prop.Name.AsNamespaced(Namespace); + name = prop.Name.AsNamespaced(this.Namespace); } - var value = GetValueFromXml(root, name, prop); + object value = this.GetValueFromXml(root, name, prop); if (value == null) { // special case for inline list items if (type.IsGenericType) { - var genericType = type.GetGenericArguments()[0]; - var first = GetElementByName(root, genericType.Name); - var list = (IList)Activator.CreateInstance(type); + Type genericType = type.GetGenericArguments()[0]; + XElement first = this.GetElementByName(root, genericType.Name); + IList list = (IList) Activator.CreateInstance(type); - if (first != null) + if (first != null && root != null) { - var elements = root.Elements(first.Name); - PopulateListFromElements(genericType, elements, list); + IEnumerable elements = root.Elements(first.Name); + + this.PopulateListFromElements(genericType, elements, list); } prop.SetValue(x, list, null); @@ -152,7 +165,7 @@ protected virtual object Map(object x, XElement root) if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { // if the value is empty, set the property to null... - if (value == null || String.IsNullOrEmpty(value.ToString())) + if (string.IsNullOrEmpty(value.ToString())) { prop.SetValue(x, null, null); continue; @@ -163,21 +176,25 @@ protected virtual object Map(object x, XElement root) if (type == typeof(bool)) { - var toConvert = value.ToString().ToLower(); + string toConvert = value.ToString() + .ToLower(); + prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null); } else if (type.IsPrimitive) { - prop.SetValue(x, value.ChangeType(type, Culture), null); + prop.SetValue(x, value.ChangeType(type, this.Culture), null); } else if (type.IsEnum) { - var converted = type.FindEnumValue(value.ToString(), Culture); + object converted = type.FindEnumValue(value.ToString(), this.Culture); + prop.SetValue(x, converted, null); } else if (type == typeof(Uri)) { - var uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); + Uri uri = new Uri(value.ToString(), UriKind.RelativeOrAbsolute); + prop.SetValue(x, uri, null); } else if (type == typeof(string)) @@ -186,21 +203,15 @@ protected virtual object Map(object x, XElement root) } else if (type == typeof(DateTime)) { - if (DateFormat.HasValue()) - { - value = DateTime.ParseExact(value.ToString(), DateFormat, Culture); - } - else - { - value = DateTime.Parse(value.ToString(), Culture); - } + value = this.DateFormat.HasValue() + ? DateTime.ParseExact(value.ToString(), this.DateFormat, this.Culture) + : DateTime.Parse(value.ToString(), this.Culture); prop.SetValue(x, value, null); } -#if !PocketPC else if (type == typeof(DateTimeOffset)) { - var toConvert = value.ToString(); + string toConvert = value.ToString(); if (!string.IsNullOrEmpty(toConvert)) { @@ -228,35 +239,43 @@ protected virtual object Map(object x, XElement root) } } } -#endif - else if (type == typeof(Decimal)) + else if (type == typeof(decimal)) { - value = Decimal.Parse(value.ToString(), Culture); + value = decimal.Parse(value.ToString(), this.Culture); prop.SetValue(x, value, null); } else if (type == typeof(Guid)) { - var raw = value.ToString(); - value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()); + string raw = value.ToString(); + + value = string.IsNullOrEmpty(raw) + ? Guid.Empty + : new Guid(value.ToString()); + prop.SetValue(x, value, null); } else if (type == typeof(TimeSpan)) { - var timeSpan = XmlConvert.ToTimeSpan(value.ToString()); + TimeSpan timeSpan = XmlConvert.ToTimeSpan(value.ToString()); + prop.SetValue(x, timeSpan, null); } else if (type.IsGenericType) { - var t = type.GetGenericArguments()[0]; - var list = (IList)Activator.CreateInstance(type); - var container = GetElementByName(root, prop.Name.AsNamespaced(Namespace)); + Type t = type.GetGenericArguments()[0]; + IList list = (IList) Activator.CreateInstance(type); + XElement container = this.GetElementByName(root, prop.Name.AsNamespaced(this.Namespace)); if (container.HasElements) { - var first = container.Elements().FirstOrDefault(); - var elements = container.Elements(first.Name); + XElement first = container.Elements().FirstOrDefault(); + + if (first != null) + { + IEnumerable elements = container.Elements(first.Name); - PopulateListFromElements(t, elements, list); + this.PopulateListFromElements(t, elements, list); + } } prop.SetValue(x, list, null); @@ -265,7 +284,8 @@ protected virtual object Map(object x, XElement root) { // handles classes that derive from List // e.g. a collection that also has attributes - var list = HandleListDerivative(x, root, prop.Name, type); + object list = this.HandleListDerivative(root, prop.Name, type); + prop.SetValue(x, list, null); } else @@ -282,11 +302,12 @@ protected virtual object Map(object x, XElement root) // nested property classes if (root != null) { - var element = GetElementByName(root, name); + XElement element = this.GetElementByName(root, name); if (element != null) { - var item = CreateAndMap(type, element); + object item = this.CreateAndMap(type, element); + prop.SetValue(x, item, null); } } @@ -299,83 +320,88 @@ protected virtual object Map(object x, XElement root) private static bool TryGetFromString(string inputString, out object result, Type type) { -#if !SILVERLIGHT && !WINDOWS_PHONE && !PocketPC - var converter = TypeDescriptor.GetConverter(type); +#if !SILVERLIGHT && !WINDOWS_PHONE + TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { result = (converter.ConvertFromInvariantString(inputString)); + return true; } result = null; + return false; #else result = null; + return false; #endif } private void PopulateListFromElements(Type t, IEnumerable elements, IList list) { - foreach (var element in elements) + foreach (object item in elements.Select(element => this.CreateAndMap(t, element))) { - var item = CreateAndMap(t, element); list.Add(item); } } - private object HandleListDerivative(object x, XElement root, string propName, Type type) + private object HandleListDerivative(XElement root, string propName, Type type) { - Type t; + Type t = type.IsGenericType + ? type.GetGenericArguments()[0] + : type.BaseType.GetGenericArguments()[0]; + IList list = (IList) Activator.CreateInstance(type); + IList elements = root.Descendants(t.Name.AsNamespaced(this.Namespace)) + .ToList(); + string name = t.Name; + DeserializeAsAttribute attribute = t.GetAttribute(); - if (type.IsGenericType) - { - t = type.GetGenericArguments()[0]; - } - else - { - t = type.BaseType.GetGenericArguments()[0]; - } - - var list = (IList)Activator.CreateInstance(type); - var elements = root.Descendants(t.Name.AsNamespaced(Namespace)); - var name = t.Name; - - var attribute = t.GetAttribute(); if (attribute != null) + { name = attribute.Name; + } if (!elements.Any()) { - var lowerName = name.ToLower().AsNamespaced(Namespace); - elements = root.Descendants(lowerName); + XName lowerName = name.ToLower().AsNamespaced(this.Namespace); + + elements = root.Descendants(lowerName).ToList(); } if (!elements.Any()) { - var camelName = name.ToCamelCase(Culture).AsNamespaced(Namespace); - elements = root.Descendants(camelName); + XName camelName = name.ToCamelCase(this.Culture).AsNamespaced(this.Namespace); + + elements = root.Descendants(camelName).ToList(); } if (!elements.Any()) { - elements = root.Descendants().Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == name); + elements = root.Descendants() + .Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == name) + .ToList(); } if (!elements.Any()) { - var lowerName = name.ToLower().AsNamespaced(Namespace); - elements = root.Descendants().Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == lowerName); + XName lowerName = name.ToLower().AsNamespaced(this.Namespace); + + elements = root.Descendants() + .Where(e => e.Name.LocalName.RemoveUnderscoresAndDashes() == lowerName) + .ToList(); } - PopulateListFromElements(t, elements, list); + this.PopulateListFromElements(t, elements, list); // get properties too, not just list items // only if this isn't a generic type if (!type.IsGenericType) { - Map(list, root.Element(propName.AsNamespaced(Namespace)) ?? root); // when using RootElement, the heirarchy is different + this.Map(list, root.Element(propName.AsNamespaced(this.Namespace)) ?? root); + // when using RootElement, the heirarchy is different } return list; @@ -385,18 +411,18 @@ protected virtual object CreateAndMap(Type t, XElement element) { object item; - if (t == typeof(String)) + if (t == typeof(string)) { item = element.Value; } else if (t.IsPrimitive) { - item = element.Value.ChangeType(t, Culture); + item = element.Value.ChangeType(t, this.Culture); } else { item = Activator.CreateInstance(t); - Map(item, element); + this.Map(item, element); } return item; @@ -408,11 +434,11 @@ protected virtual object GetValueFromXml(XElement root, XName name, PropertyInfo if (root != null) { - var element = GetElementByName(root, name); + XElement element = this.GetElementByName(root, name); if (element == null) { - var attribute = GetAttributeByName(root, name); + XAttribute attribute = this.GetAttributeByName(root, name); if (attribute != null) { @@ -433,8 +459,8 @@ protected virtual object GetValueFromXml(XElement root, XName name, PropertyInfo protected virtual XElement GetElementByName(XElement root, XName name) { - var lowerName = name.LocalName.ToLower().AsNamespaced(name.NamespaceName); - var camelName = name.LocalName.ToCamelCase(Culture).AsNamespaced(name.NamespaceName); + XName lowerName = name.LocalName.ToLower().AsNamespaced(name.NamespaceName); + XName camelName = name.LocalName.ToCamelCase(this.Culture).AsNamespaced(name.NamespaceName); if (root.Element(name) != null) { @@ -459,7 +485,7 @@ protected virtual XElement GetElementByName(XElement root, XName name) // try looking for element that matches sanitized property name (Order by depth) return root.Descendants() .OrderBy(d => d.Ancestors().Count()) - .FirstOrDefault(d => d.Name.LocalName.RemoveUnderscoresAndDashes() == name.LocalName) ?? + .FirstOrDefault(d => d.Name.LocalName.RemoveUnderscoresAndDashes() == name.LocalName) ?? root.Descendants() .OrderBy(d => d.Ancestors().Count()) .FirstOrDefault(d => d.Name.LocalName.RemoveUnderscoresAndDashes() == name.LocalName.ToLower()); @@ -467,12 +493,14 @@ protected virtual XElement GetElementByName(XElement root, XName name) protected virtual XAttribute GetAttributeByName(XElement root, XName name) { - var names = new List - { - name.LocalName, - name.LocalName.ToLower().AsNamespaced(name.NamespaceName), - name.LocalName.ToCamelCase(Culture).AsNamespaced(name.NamespaceName) - }; + List names = new List + { + name.LocalName, + name.LocalName.ToLower() + .AsNamespaced(name.NamespaceName), + name.LocalName.ToCamelCase(this.Culture) + .AsNamespaced(name.NamespaceName) + }; return root.DescendantsAndSelf() .OrderBy(d => d.Ancestors().Count()) diff --git a/RestSharp/Enum.cs b/RestSharp/Enum.cs index 6102880cc..5ff6ad02a 100644 --- a/RestSharp/Enum.cs +++ b/RestSharp/Enum.cs @@ -61,12 +61,12 @@ public struct DateFormat /// /// .NET format string for ISO 8601 date format /// - public const string Iso8601 = "s"; + public const string ISO_8601 = "s"; /// /// .NET format string for roundtrip date format /// - public const string RoundTrip = "u"; + public const string ROUND_TRIP = "u"; } /// diff --git a/RestSharp/Extensions/MiscExtensions.cs b/RestSharp/Extensions/MiscExtensions.cs index d2d770dd0..8214f08d2 100644 --- a/RestSharp/Extensions/MiscExtensions.cs +++ b/RestSharp/Extensions/MiscExtensions.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System.IO; @@ -24,7 +26,7 @@ namespace RestSharp.Extensions /// public static class MiscExtensions { -#if !WINDOWS_PHONE && !PocketPC +#if !WINDOWS_PHONE /// /// Save a byte array to a file /// @@ -65,14 +67,16 @@ public static byte[] ReadAsBytes(this Stream input) /// The output stream. public static void CopyTo(this Stream input, Stream output) { - var buffer = new byte[32768]; + byte[] buffer = new byte[32768]; while (true) { - var read = input.Read(buffer, 0, buffer.Length); + int read = input.Read(buffer, 0, buffer.Length); if (read <= 0) + { return; + } output.Write(buffer, 0, read); } @@ -87,7 +91,9 @@ public static void CopyTo(this Stream input, Stream output) public static string AsString(this byte[] buffer) { if (buffer == null) + { return ""; + } // Ansi as default Encoding encoding = Encoding.UTF8; @@ -95,7 +101,7 @@ public static string AsString(this byte[] buffer) #if FRAMEWORK return encoding.GetString(buffer, 0, buffer.Length); #else - if (buffer == null || buffer.Length == 0) + if (buffer.Length == 0) return ""; /* diff --git a/RestSharp/Extensions/MonoHttp/Helpers.cs b/RestSharp/Extensions/MonoHttp/Helpers.cs index 8863e1b9b..8dc7d5862 100644 --- a/RestSharp/Extensions/MonoHttp/Helpers.cs +++ b/RestSharp/Extensions/MonoHttp/Helpers.cs @@ -26,11 +26,12 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // + using System.Globalization; -namespace RestSharp.Contrib +namespace RestSharp.Extensions.MonoHttp { - class Helpers + internal class Helpers { public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; } diff --git a/RestSharp/Extensions/MonoHttp/HtmlEncoder.cs b/RestSharp/Extensions/MonoHttp/HtmlEncoder.cs index f9bcb915b..5317a98ec 100644 --- a/RestSharp/Extensions/MonoHttp/HtmlEncoder.cs +++ b/RestSharp/Extensions/MonoHttp/HtmlEncoder.cs @@ -30,44 +30,36 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // + using System; using System.Collections.Generic; using System.IO; using System.Text; -#if NET_4_0 -using System.Web.Configuration; -#endif -namespace RestSharp.Contrib +namespace RestSharp.Extensions.MonoHttp { -#if NET_4_0 - public -#endif - class HttpEncoder + internal class HttpEncoder { - static char[] hexChars = "0123456789abcdef".ToCharArray(); - static object entitiesLock = new object(); -#if PocketPC - static Dictionary entities; -#else - static SortedDictionary entities; -#endif -#if NET_4_0 - static Lazy defaultEncoder; - static Lazy currentEncoderLazy; -#else - static HttpEncoder defaultEncoder; -#endif - static HttpEncoder currentEncoder; - - static IDictionary Entities + private static readonly char[] hexChars = "0123456789abcdef".ToCharArray(); + + private static readonly object entitiesLock = new object(); + + private static SortedDictionary entities; + + private static readonly HttpEncoder defaultEncoder; + + private static readonly HttpEncoder currentEncoder; + + private static IDictionary Entities { get { lock (entitiesLock) { if (entities == null) + { InitEntities(); + } return entities; } @@ -76,191 +68,111 @@ static IDictionary Entities public static HttpEncoder Current { - get - { -#if NET_4_0 - if (currentEncoder == null) - currentEncoder = currentEncoderLazy.Value; -#endif - return currentEncoder; - } -#if NET_4_0 - set - { - if (value == null) - throw new ArgumentNullException ("value"); - currentEncoder = value; - } -#endif + get { return currentEncoder; } } public static HttpEncoder Default { - get - { -#if NET_4_0 - return defaultEncoder.Value; -#else - return defaultEncoder; -#endif - } + get { return defaultEncoder; } } static HttpEncoder() { -#if NET_4_0 - defaultEncoder = new Lazy (() => new HttpEncoder ()); - currentEncoderLazy = new Lazy (new Func (GetCustomEncoderFromConfig)); -#else defaultEncoder = new HttpEncoder(); currentEncoder = defaultEncoder; -#endif } - public HttpEncoder() { } - -#if NET_4_0 - protected internal virtual -#else - internal static -#endif - void HeaderNameValueEncode(string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue) + internal static void HeaderNameValueEncode(string headerName, string headerValue, out string encodedHeaderName, + out string encodedHeaderValue) { - if (String.IsNullOrEmpty(headerName)) - encodedHeaderName = headerName; - else - encodedHeaderName = EncodeHeaderString(headerName); - - if (String.IsNullOrEmpty(headerValue)) - encodedHeaderValue = headerValue; - else - encodedHeaderValue = EncodeHeaderString(headerValue); + encodedHeaderName = string.IsNullOrEmpty(headerName) + ? headerName + : EncodeHeaderString(headerName); + encodedHeaderValue = string.IsNullOrEmpty(headerValue) + ? headerValue + : EncodeHeaderString(headerValue); } - static void StringBuilderAppend(string s, ref StringBuilder sb) + private static void StringBuilderAppend(string s, ref StringBuilder sb) { if (sb == null) + { sb = new StringBuilder(s); + } else + { sb.Append(s); + } } - static string EncodeHeaderString(string input) + private static string EncodeHeaderString(string input) { StringBuilder sb = null; - char ch; - for (int i = 0; i < input.Length; i++) + foreach (char ch in input) { - ch = input[i]; - if ((ch < 32 && ch != 9) || ch == 127) - StringBuilderAppend(String.Format("%{0:x2}", (int)ch), ref sb); + { + StringBuilderAppend(string.Format("%{0:x2}", (int) ch), ref sb); + } } - if (sb != null) - return sb.ToString(); - - return input; - } - -#if NET_4_0 - protected internal virtual void HtmlAttributeEncode (string value, TextWriter output) - { - - if (output == null) - throw new ArgumentNullException ("output"); - - if (String.IsNullOrEmpty (value)) - return; - - output.Write (HtmlAttributeEncode (value)); - } - - protected internal virtual void HtmlDecode (string value, TextWriter output) - { - if (output == null) - throw new ArgumentNullException ("output"); - - output.Write (HtmlDecode (value)); + return sb != null + ? sb.ToString() + : input; } - protected internal virtual void HtmlEncode (string value, TextWriter output) + internal static string UrlPathEncode(string value) { - if (output == null) - throw new ArgumentNullException ("output"); - - output.Write (HtmlEncode (value)); - } - - protected internal virtual byte[] UrlEncode (byte[] bytes, int offset, int count) - { - return UrlEncodeToBytes (bytes, offset, count); - } - - static HttpEncoder GetCustomEncoderFromConfig () - { - var cfg = WebConfigurationManager.GetSection ("system.web/httpRuntime") as HttpRuntimeSection; - string typeName = cfg.EncoderType; - - if (String.Compare (typeName, "System.Web.Util.HttpEncoder", StringComparison.OrdinalIgnoreCase) == 0) - return Default; - - Type t = Type.GetType (typeName, false); - - if (t == null) - throw new ConfigurationErrorsException (String.Format ("Could not load type '{0}'.", typeName)); - - if (!typeof (HttpEncoder).IsAssignableFrom (t)) - throw new ConfigurationErrorsException ( - String.Format ("'{0}' is not allowed here because it does not extend class 'System.Web.Util.HttpEncoder'.", typeName) - ); - - return Activator.CreateInstance (t, false) as HttpEncoder; - } -#endif - -#if NET_4_0 - protected internal virtual -#else - internal static -#endif - string UrlPathEncode(string value) - { - if (String.IsNullOrEmpty(value)) + if (string.IsNullOrEmpty(value)) + { return value; + } MemoryStream result = new MemoryStream(); int length = value.Length; for (int i = 0; i < length; i++) + { UrlPathEncodeChar(value[i], result); + } byte[] bytes = result.ToArray(); + return Encoding.ASCII.GetString(bytes, 0, bytes.Length); } internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) + { throw new ArgumentNullException("bytes"); + } int blen = bytes.Length; if (blen == 0) + { return new byte[0]; + } if (offset < 0 || offset >= blen) + { throw new ArgumentOutOfRangeException("offset"); + } if (count < 0 || count > blen - offset) + { throw new ArgumentOutOfRangeException("count"); + } MemoryStream result = new MemoryStream(count); int end = offset + count; for (int i = offset; i < end; i++) - UrlEncodeChar((char)bytes[i], result, false); + { + UrlEncodeChar((char) bytes[i], result, false); + } return result.ToArray(); } @@ -268,21 +180,22 @@ internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) internal static string HtmlEncode(string s) { if (s == null) + { return null; + } if (s.Length == 0) - return String.Empty; + { + return string.Empty; + } bool needEncode = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; - if (c == '&' || c == '"' || c == '<' || c == '>' || c > 159 -#if NET_4_0 - || c == '\'' -#endif - ) + + if (c == '&' || c == '"' || c == '<' || c == '>' || c > 159) { needEncode = true; break; @@ -290,10 +203,11 @@ internal static string HtmlEncode(string s) } if (!needEncode) + { return s; + } StringBuilder output = new StringBuilder(); - char ch; int len = s.Length; for (int i = 0; i < len; i++) @@ -316,12 +230,6 @@ internal static string HtmlEncode(string s) output.Append("""); break; -#if NET_4_0 - case '\'': - output.Append ("'"); - break; -#endif - case '\uff1c': output.Append("<"); break; @@ -331,16 +239,19 @@ internal static string HtmlEncode(string s) break; default: - ch = s[i]; + char ch = s[i]; if (ch > 159 && ch < 256) { output.Append("&#"); - output.Append(((int)ch).ToString(Helpers.InvariantCulture)); + output.Append(((int) ch).ToString(Helpers.InvariantCulture)); output.Append(";"); } else + { output.Append(ch); + } + break; } } @@ -350,28 +261,23 @@ internal static string HtmlEncode(string s) internal static string HtmlAttributeEncode(string s) { -#if NET_4_0 - if (String.IsNullOrEmpty (s)) - return String.Empty; -#else - if (s == null) + { return null; + } if (s.Length == 0) - return String.Empty; -#endif + { + return string.Empty; + } bool needEncode = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; - if (c == '&' || c == '"' || c == '<' -#if NET_4_0 - || c == '\'' -#endif - ) + + if (c == '&' || c == '"' || c == '<') { needEncode = true; break; @@ -379,12 +285,15 @@ internal static string HtmlAttributeEncode(string s) } if (!needEncode) + { return s; + } StringBuilder output = new StringBuilder(); int len = s.Length; for (int i = 0; i < len; i++) + { switch (s[i]) { case '&': @@ -399,16 +308,11 @@ internal static string HtmlAttributeEncode(string s) output.Append("<"); break; -#if NET_4_0 - case '\'': - output.Append ("'"); - break; -#endif - default: output.Append(s[i]); break; } + } return output.ToString(); } @@ -416,16 +320,20 @@ internal static string HtmlAttributeEncode(string s) internal static string HtmlDecode(string s) { if (s == null) + { return null; + } if (s.Length == 0) - return String.Empty; + { + return string.Empty; + } if (s.IndexOf('&') == -1) + { return s; -#if NET_4_0 - StringBuilder rawEntity = new StringBuilder (); -#endif + } + StringBuilder entity = new StringBuilder(); StringBuilder output = new StringBuilder(); int len = s.Length; @@ -436,8 +344,8 @@ internal static string HtmlDecode(string s) // 3 -> '#' found after '&' and getting numbers int state = 0; int number = 0; - bool is_hex_value = false; - bool have_trailing_digits = false; + bool isHexValue = false; + bool haveTrailingDigits = false; for (int i = 0; i < len; i++) { @@ -448,9 +356,6 @@ internal static string HtmlDecode(string s) if (c == '&') { entity.Append(c); -#if NET_4_0 - rawEntity.Append (c); -#endif state = 1; } else @@ -465,136 +370,113 @@ internal static string HtmlDecode(string s) { state = 1; - if (have_trailing_digits) + if (haveTrailingDigits) { entity.Append(number.ToString(Helpers.InvariantCulture)); - have_trailing_digits = false; + haveTrailingDigits = false; } - output.Append(entity.ToString()); + output.Append(entity); entity.Length = 0; entity.Append('&'); continue; } - if (state == 1) + switch (state) { - if (c == ';') - { - state = 0; - output.Append(entity.ToString()); - output.Append(c); - entity.Length = 0; - } - else - { - number = 0; - is_hex_value = false; - if (c != '#') + case 1: + if (c == ';') { - state = 2; + state = 0; + output.Append(entity); + output.Append(c); + entity.Length = 0; } else { - state = 3; + number = 0; + isHexValue = false; + state = c != '#' + ? 2 + : 3; + entity.Append(c); } + break; + + case 2: entity.Append(c); -#if NET_4_0 - rawEntity.Append (c); -#endif - } - } - else if (state == 2) - { - entity.Append(c); - if (c == ';') - { - string key = entity.ToString(); + if (c == ';') + { + string key = entity.ToString(); - if (key.Length > 1 && Entities.ContainsKey(key.Substring(1, key.Length - 2))) - key = Entities[key.Substring(1, key.Length - 2)].ToString(); + if (key.Length > 1 && Entities.ContainsKey(key.Substring(1, key.Length - 2))) + { + key = Entities[key.Substring(1, key.Length - 2)].ToString(); + } - output.Append(key); - state = 0; - entity.Length = 0; -#if NET_4_0 - rawEntity.Length = 0; -#endif - } - } - else if (state == 3) - { - if (c == ';') - { -#if NET_4_0 - if (number == 0) - output.Append (rawEntity.ToString () + ";"); - else -#endif - if (number > 65535) + output.Append(key); + state = 0; + entity.Length = 0; + } + break; + + case 3: + if (c == ';') { - output.Append("&#"); - output.Append(number.ToString(Helpers.InvariantCulture)); - output.Append(";"); + if (number > 65535) + { + output.Append("&#"); + output.Append(number.ToString(Helpers.InvariantCulture)); + output.Append(";"); + } + else + { + output.Append((char) number); + } + + state = 0; + entity.Length = 0; + haveTrailingDigits = false; } - else + else if (isHexValue && Uri.IsHexDigit(c)) + { + number = number * 16 + Uri.FromHex(c); + haveTrailingDigits = true; + } + else if (char.IsDigit(c)) { - output.Append((char)number); + number = number * 10 + (c - '0'); + haveTrailingDigits = true; } + else if (number == 0 && (c == 'x' || c == 'X')) + { + isHexValue = true; + } + else + { + state = 2; - state = 0; - entity.Length = 0; -#if NET_4_0 - rawEntity.Length = 0; -#endif - have_trailing_digits = false; - } - else if (is_hex_value && Uri.IsHexDigit(c)) - { - number = number * 16 + Uri.FromHex(c); - have_trailing_digits = true; -#if NET_4_0 - rawEntity.Append (c); -#endif - } - else if (Char.IsDigit(c)) - { - number = number * 10 + ((int)c - '0'); - have_trailing_digits = true; -#if NET_4_0 - rawEntity.Append (c); -#endif - } - else if (number == 0 && (c == 'x' || c == 'X')) - { - is_hex_value = true; -#if NET_4_0 - rawEntity.Append (c); -#endif - } - else - { - state = 2; + if (haveTrailingDigits) + { + entity.Append(number.ToString(Helpers.InvariantCulture)); + haveTrailingDigits = false; + } - if (have_trailing_digits) - { - entity.Append(number.ToString(Helpers.InvariantCulture)); - have_trailing_digits = false; + entity.Append(c); } - entity.Append(c); - } + break; } } if (entity.Length > 0) { - output.Append(entity.ToString()); + output.Append(entity); } - else if (have_trailing_digits) + else if (haveTrailingDigits) { output.Append(number.ToString(Helpers.InvariantCulture)); } @@ -604,11 +486,7 @@ internal static string HtmlDecode(string s) internal static bool NotEncoded(char c) { - return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_' -#if !NET_4_0 - || c == '\'' -#endif - ); + return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'); } internal static void UrlEncodeChar(char c, Stream result, bool isUnicode) @@ -618,32 +496,35 @@ internal static void UrlEncodeChar(char c, Stream result, bool isUnicode) //FIXME: what happens when there is an internal error? //if (!isUnicode) // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256"); - int idx; - int i = (int)c; + int i = c; + + result.WriteByte((byte) '%'); + result.WriteByte((byte) 'u'); - result.WriteByte((byte)'%'); - result.WriteByte((byte)'u'); - idx = i >> 12; - result.WriteByte((byte)hexChars[idx]); + int idx = i >> 12; + + result.WriteByte((byte) hexChars[idx]); idx = (i >> 8) & 0x0F; - result.WriteByte((byte)hexChars[idx]); + result.WriteByte((byte) hexChars[idx]); idx = (i >> 4) & 0x0F; - result.WriteByte((byte)hexChars[idx]); + result.WriteByte((byte) hexChars[idx]); idx = i & 0x0F; - result.WriteByte((byte)hexChars[idx]); + result.WriteByte((byte) hexChars[idx]); return; } if (c > ' ' && NotEncoded(c)) { - result.WriteByte((byte)c); + result.WriteByte((byte) c); + return; } if (c == ' ') { - result.WriteByte((byte)'+'); + result.WriteByte((byte) '+'); + return; } @@ -654,22 +535,26 @@ internal static void UrlEncodeChar(char c, Stream result, bool isUnicode) { if (isUnicode && c > 127) { - result.WriteByte((byte)'%'); - result.WriteByte((byte)'u'); - result.WriteByte((byte)'0'); - result.WriteByte((byte)'0'); + result.WriteByte((byte) '%'); + result.WriteByte((byte) 'u'); + result.WriteByte((byte) '0'); + result.WriteByte((byte) '0'); } else - result.WriteByte((byte)'%'); + { + result.WriteByte((byte) '%'); + } - int idx = ((int)c) >> 4; + int idx = c >> 4; - result.WriteByte((byte)hexChars[idx]); - idx = ((int)c) & 0x0F; - result.WriteByte((byte)hexChars[idx]); + result.WriteByte((byte) hexChars[idx]); + idx = c & 0x0F; + result.WriteByte((byte) hexChars[idx]); } else - result.WriteByte((byte)c); + { + result.WriteByte((byte) c); + } } internal static void UrlPathEncodeChar(char c, Stream result) @@ -680,286 +565,286 @@ internal static void UrlPathEncodeChar(char c, Stream result) for (int i = 0; i < bIn.Length; i++) { - result.WriteByte((byte)'%'); + result.WriteByte((byte) '%'); - int idx = ((int)bIn[i]) >> 4; + int idx = bIn[i] >> 4; - result.WriteByte((byte)hexChars[idx]); - idx = ((int)bIn[i]) & 0x0F; - result.WriteByte((byte)hexChars[idx]); + result.WriteByte((byte) hexChars[idx]); + idx = bIn[i] & 0x0F; + result.WriteByte((byte) hexChars[idx]); } } else if (c == ' ') { - result.WriteByte((byte)'%'); - result.WriteByte((byte)'2'); - result.WriteByte((byte)'0'); + result.WriteByte((byte) '%'); + result.WriteByte((byte) '2'); + result.WriteByte((byte) '0'); } else - result.WriteByte((byte)c); + { + result.WriteByte((byte) c); + } } - static void InitEntities() + private static void InitEntities() { // Build the hash table of HTML entity references. This list comes // from the HTML 4.01 W3C recommendation. -#if PocketPC - entities = new Dictionary(StringComparer.Ordinal); -#else - entities = new SortedDictionary(StringComparer.Ordinal); -#endif - entities.Add("nbsp", '\u00A0'); - entities.Add("iexcl", '\u00A1'); - entities.Add("cent", '\u00A2'); - entities.Add("pound", '\u00A3'); - entities.Add("curren", '\u00A4'); - entities.Add("yen", '\u00A5'); - entities.Add("brvbar", '\u00A6'); - entities.Add("sect", '\u00A7'); - entities.Add("uml", '\u00A8'); - entities.Add("copy", '\u00A9'); - entities.Add("ordf", '\u00AA'); - entities.Add("laquo", '\u00AB'); - entities.Add("not", '\u00AC'); - entities.Add("shy", '\u00AD'); - entities.Add("reg", '\u00AE'); - entities.Add("macr", '\u00AF'); - entities.Add("deg", '\u00B0'); - entities.Add("plusmn", '\u00B1'); - entities.Add("sup2", '\u00B2'); - entities.Add("sup3", '\u00B3'); - entities.Add("acute", '\u00B4'); - entities.Add("micro", '\u00B5'); - entities.Add("para", '\u00B6'); - entities.Add("middot", '\u00B7'); - entities.Add("cedil", '\u00B8'); - entities.Add("sup1", '\u00B9'); - entities.Add("ordm", '\u00BA'); - entities.Add("raquo", '\u00BB'); - entities.Add("frac14", '\u00BC'); - entities.Add("frac12", '\u00BD'); - entities.Add("frac34", '\u00BE'); - entities.Add("iquest", '\u00BF'); - entities.Add("Agrave", '\u00C0'); - entities.Add("Aacute", '\u00C1'); - entities.Add("Acirc", '\u00C2'); - entities.Add("Atilde", '\u00C3'); - entities.Add("Auml", '\u00C4'); - entities.Add("Aring", '\u00C5'); - entities.Add("AElig", '\u00C6'); - entities.Add("Ccedil", '\u00C7'); - entities.Add("Egrave", '\u00C8'); - entities.Add("Eacute", '\u00C9'); - entities.Add("Ecirc", '\u00CA'); - entities.Add("Euml", '\u00CB'); - entities.Add("Igrave", '\u00CC'); - entities.Add("Iacute", '\u00CD'); - entities.Add("Icirc", '\u00CE'); - entities.Add("Iuml", '\u00CF'); - entities.Add("ETH", '\u00D0'); - entities.Add("Ntilde", '\u00D1'); - entities.Add("Ograve", '\u00D2'); - entities.Add("Oacute", '\u00D3'); - entities.Add("Ocirc", '\u00D4'); - entities.Add("Otilde", '\u00D5'); - entities.Add("Ouml", '\u00D6'); - entities.Add("times", '\u00D7'); - entities.Add("Oslash", '\u00D8'); - entities.Add("Ugrave", '\u00D9'); - entities.Add("Uacute", '\u00DA'); - entities.Add("Ucirc", '\u00DB'); - entities.Add("Uuml", '\u00DC'); - entities.Add("Yacute", '\u00DD'); - entities.Add("THORN", '\u00DE'); - entities.Add("szlig", '\u00DF'); - entities.Add("agrave", '\u00E0'); - entities.Add("aacute", '\u00E1'); - entities.Add("acirc", '\u00E2'); - entities.Add("atilde", '\u00E3'); - entities.Add("auml", '\u00E4'); - entities.Add("aring", '\u00E5'); - entities.Add("aelig", '\u00E6'); - entities.Add("ccedil", '\u00E7'); - entities.Add("egrave", '\u00E8'); - entities.Add("eacute", '\u00E9'); - entities.Add("ecirc", '\u00EA'); - entities.Add("euml", '\u00EB'); - entities.Add("igrave", '\u00EC'); - entities.Add("iacute", '\u00ED'); - entities.Add("icirc", '\u00EE'); - entities.Add("iuml", '\u00EF'); - entities.Add("eth", '\u00F0'); - entities.Add("ntilde", '\u00F1'); - entities.Add("ograve", '\u00F2'); - entities.Add("oacute", '\u00F3'); - entities.Add("ocirc", '\u00F4'); - entities.Add("otilde", '\u00F5'); - entities.Add("ouml", '\u00F6'); - entities.Add("divide", '\u00F7'); - entities.Add("oslash", '\u00F8'); - entities.Add("ugrave", '\u00F9'); - entities.Add("uacute", '\u00FA'); - entities.Add("ucirc", '\u00FB'); - entities.Add("uuml", '\u00FC'); - entities.Add("yacute", '\u00FD'); - entities.Add("thorn", '\u00FE'); - entities.Add("yuml", '\u00FF'); - entities.Add("fnof", '\u0192'); - entities.Add("Alpha", '\u0391'); - entities.Add("Beta", '\u0392'); - entities.Add("Gamma", '\u0393'); - entities.Add("Delta", '\u0394'); - entities.Add("Epsilon", '\u0395'); - entities.Add("Zeta", '\u0396'); - entities.Add("Eta", '\u0397'); - entities.Add("Theta", '\u0398'); - entities.Add("Iota", '\u0399'); - entities.Add("Kappa", '\u039A'); - entities.Add("Lambda", '\u039B'); - entities.Add("Mu", '\u039C'); - entities.Add("Nu", '\u039D'); - entities.Add("Xi", '\u039E'); - entities.Add("Omicron", '\u039F'); - entities.Add("Pi", '\u03A0'); - entities.Add("Rho", '\u03A1'); - entities.Add("Sigma", '\u03A3'); - entities.Add("Tau", '\u03A4'); - entities.Add("Upsilon", '\u03A5'); - entities.Add("Phi", '\u03A6'); - entities.Add("Chi", '\u03A7'); - entities.Add("Psi", '\u03A8'); - entities.Add("Omega", '\u03A9'); - entities.Add("alpha", '\u03B1'); - entities.Add("beta", '\u03B2'); - entities.Add("gamma", '\u03B3'); - entities.Add("delta", '\u03B4'); - entities.Add("epsilon", '\u03B5'); - entities.Add("zeta", '\u03B6'); - entities.Add("eta", '\u03B7'); - entities.Add("theta", '\u03B8'); - entities.Add("iota", '\u03B9'); - entities.Add("kappa", '\u03BA'); - entities.Add("lambda", '\u03BB'); - entities.Add("mu", '\u03BC'); - entities.Add("nu", '\u03BD'); - entities.Add("xi", '\u03BE'); - entities.Add("omicron", '\u03BF'); - entities.Add("pi", '\u03C0'); - entities.Add("rho", '\u03C1'); - entities.Add("sigmaf", '\u03C2'); - entities.Add("sigma", '\u03C3'); - entities.Add("tau", '\u03C4'); - entities.Add("upsilon", '\u03C5'); - entities.Add("phi", '\u03C6'); - entities.Add("chi", '\u03C7'); - entities.Add("psi", '\u03C8'); - entities.Add("omega", '\u03C9'); - entities.Add("thetasym", '\u03D1'); - entities.Add("upsih", '\u03D2'); - entities.Add("piv", '\u03D6'); - entities.Add("bull", '\u2022'); - entities.Add("hellip", '\u2026'); - entities.Add("prime", '\u2032'); - entities.Add("Prime", '\u2033'); - entities.Add("oline", '\u203E'); - entities.Add("frasl", '\u2044'); - entities.Add("weierp", '\u2118'); - entities.Add("image", '\u2111'); - entities.Add("real", '\u211C'); - entities.Add("trade", '\u2122'); - entities.Add("alefsym", '\u2135'); - entities.Add("larr", '\u2190'); - entities.Add("uarr", '\u2191'); - entities.Add("rarr", '\u2192'); - entities.Add("darr", '\u2193'); - entities.Add("harr", '\u2194'); - entities.Add("crarr", '\u21B5'); - entities.Add("lArr", '\u21D0'); - entities.Add("uArr", '\u21D1'); - entities.Add("rArr", '\u21D2'); - entities.Add("dArr", '\u21D3'); - entities.Add("hArr", '\u21D4'); - entities.Add("forall", '\u2200'); - entities.Add("part", '\u2202'); - entities.Add("exist", '\u2203'); - entities.Add("empty", '\u2205'); - entities.Add("nabla", '\u2207'); - entities.Add("isin", '\u2208'); - entities.Add("notin", '\u2209'); - entities.Add("ni", '\u220B'); - entities.Add("prod", '\u220F'); - entities.Add("sum", '\u2211'); - entities.Add("minus", '\u2212'); - entities.Add("lowast", '\u2217'); - entities.Add("radic", '\u221A'); - entities.Add("prop", '\u221D'); - entities.Add("infin", '\u221E'); - entities.Add("ang", '\u2220'); - entities.Add("and", '\u2227'); - entities.Add("or", '\u2228'); - entities.Add("cap", '\u2229'); - entities.Add("cup", '\u222A'); - entities.Add("int", '\u222B'); - entities.Add("there4", '\u2234'); - entities.Add("sim", '\u223C'); - entities.Add("cong", '\u2245'); - entities.Add("asymp", '\u2248'); - entities.Add("ne", '\u2260'); - entities.Add("equiv", '\u2261'); - entities.Add("le", '\u2264'); - entities.Add("ge", '\u2265'); - entities.Add("sub", '\u2282'); - entities.Add("sup", '\u2283'); - entities.Add("nsub", '\u2284'); - entities.Add("sube", '\u2286'); - entities.Add("supe", '\u2287'); - entities.Add("oplus", '\u2295'); - entities.Add("otimes", '\u2297'); - entities.Add("perp", '\u22A5'); - entities.Add("sdot", '\u22C5'); - entities.Add("lceil", '\u2308'); - entities.Add("rceil", '\u2309'); - entities.Add("lfloor", '\u230A'); - entities.Add("rfloor", '\u230B'); - entities.Add("lang", '\u2329'); - entities.Add("rang", '\u232A'); - entities.Add("loz", '\u25CA'); - entities.Add("spades", '\u2660'); - entities.Add("clubs", '\u2663'); - entities.Add("hearts", '\u2665'); - entities.Add("diams", '\u2666'); - entities.Add("quot", '\u0022'); - entities.Add("amp", '\u0026'); - entities.Add("lt", '\u003C'); - entities.Add("gt", '\u003E'); - entities.Add("OElig", '\u0152'); - entities.Add("oelig", '\u0153'); - entities.Add("Scaron", '\u0160'); - entities.Add("scaron", '\u0161'); - entities.Add("Yuml", '\u0178'); - entities.Add("circ", '\u02C6'); - entities.Add("tilde", '\u02DC'); - entities.Add("ensp", '\u2002'); - entities.Add("emsp", '\u2003'); - entities.Add("thinsp", '\u2009'); - entities.Add("zwnj", '\u200C'); - entities.Add("zwj", '\u200D'); - entities.Add("lrm", '\u200E'); - entities.Add("rlm", '\u200F'); - entities.Add("ndash", '\u2013'); - entities.Add("mdash", '\u2014'); - entities.Add("lsquo", '\u2018'); - entities.Add("rsquo", '\u2019'); - entities.Add("sbquo", '\u201A'); - entities.Add("ldquo", '\u201C'); - entities.Add("rdquo", '\u201D'); - entities.Add("bdquo", '\u201E'); - entities.Add("dagger", '\u2020'); - entities.Add("Dagger", '\u2021'); - entities.Add("permil", '\u2030'); - entities.Add("lsaquo", '\u2039'); - entities.Add("rsaquo", '\u203A'); - entities.Add("euro", '\u20AC'); + entities = new SortedDictionary(StringComparer.Ordinal) + { + {"nbsp", '\u00A0'}, + {"iexcl", '\u00A1'}, + {"cent", '\u00A2'}, + {"pound", '\u00A3'}, + {"curren", '\u00A4'}, + {"yen", '\u00A5'}, + {"brvbar", '\u00A6'}, + {"sect", '\u00A7'}, + {"uml", '\u00A8'}, + {"copy", '\u00A9'}, + {"ordf", '\u00AA'}, + {"laquo", '\u00AB'}, + {"not", '\u00AC'}, + {"shy", '\u00AD'}, + {"reg", '\u00AE'}, + {"macr", '\u00AF'}, + {"deg", '\u00B0'}, + {"plusmn", '\u00B1'}, + {"sup2", '\u00B2'}, + {"sup3", '\u00B3'}, + {"acute", '\u00B4'}, + {"micro", '\u00B5'}, + {"para", '\u00B6'}, + {"middot", '\u00B7'}, + {"cedil", '\u00B8'}, + {"sup1", '\u00B9'}, + {"ordm", '\u00BA'}, + {"raquo", '\u00BB'}, + {"frac14", '\u00BC'}, + {"frac12", '\u00BD'}, + {"frac34", '\u00BE'}, + {"iquest", '\u00BF'}, + {"Agrave", '\u00C0'}, + {"Aacute", '\u00C1'}, + {"Acirc", '\u00C2'}, + {"Atilde", '\u00C3'}, + {"Auml", '\u00C4'}, + {"Aring", '\u00C5'}, + {"AElig", '\u00C6'}, + {"Ccedil", '\u00C7'}, + {"Egrave", '\u00C8'}, + {"Eacute", '\u00C9'}, + {"Ecirc", '\u00CA'}, + {"Euml", '\u00CB'}, + {"Igrave", '\u00CC'}, + {"Iacute", '\u00CD'}, + {"Icirc", '\u00CE'}, + {"Iuml", '\u00CF'}, + {"ETH", '\u00D0'}, + {"Ntilde", '\u00D1'}, + {"Ograve", '\u00D2'}, + {"Oacute", '\u00D3'}, + {"Ocirc", '\u00D4'}, + {"Otilde", '\u00D5'}, + {"Ouml", '\u00D6'}, + {"times", '\u00D7'}, + {"Oslash", '\u00D8'}, + {"Ugrave", '\u00D9'}, + {"Uacute", '\u00DA'}, + {"Ucirc", '\u00DB'}, + {"Uuml", '\u00DC'}, + {"Yacute", '\u00DD'}, + {"THORN", '\u00DE'}, + {"szlig", '\u00DF'}, + {"agrave", '\u00E0'}, + {"aacute", '\u00E1'}, + {"acirc", '\u00E2'}, + {"atilde", '\u00E3'}, + {"auml", '\u00E4'}, + {"aring", '\u00E5'}, + {"aelig", '\u00E6'}, + {"ccedil", '\u00E7'}, + {"egrave", '\u00E8'}, + {"eacute", '\u00E9'}, + {"ecirc", '\u00EA'}, + {"euml", '\u00EB'}, + {"igrave", '\u00EC'}, + {"iacute", '\u00ED'}, + {"icirc", '\u00EE'}, + {"iuml", '\u00EF'}, + {"eth", '\u00F0'}, + {"ntilde", '\u00F1'}, + {"ograve", '\u00F2'}, + {"oacute", '\u00F3'}, + {"ocirc", '\u00F4'}, + {"otilde", '\u00F5'}, + {"ouml", '\u00F6'}, + {"divide", '\u00F7'}, + {"oslash", '\u00F8'}, + {"ugrave", '\u00F9'}, + {"uacute", '\u00FA'}, + {"ucirc", '\u00FB'}, + {"uuml", '\u00FC'}, + {"yacute", '\u00FD'}, + {"thorn", '\u00FE'}, + {"yuml", '\u00FF'}, + {"fnof", '\u0192'}, + {"Alpha", '\u0391'}, + {"Beta", '\u0392'}, + {"Gamma", '\u0393'}, + {"Delta", '\u0394'}, + {"Epsilon", '\u0395'}, + {"Zeta", '\u0396'}, + {"Eta", '\u0397'}, + {"Theta", '\u0398'}, + {"Iota", '\u0399'}, + {"Kappa", '\u039A'}, + {"Lambda", '\u039B'}, + {"Mu", '\u039C'}, + {"Nu", '\u039D'}, + {"Xi", '\u039E'}, + {"Omicron", '\u039F'}, + {"Pi", '\u03A0'}, + {"Rho", '\u03A1'}, + {"Sigma", '\u03A3'}, + {"Tau", '\u03A4'}, + {"Upsilon", '\u03A5'}, + {"Phi", '\u03A6'}, + {"Chi", '\u03A7'}, + {"Psi", '\u03A8'}, + {"Omega", '\u03A9'}, + {"alpha", '\u03B1'}, + {"beta", '\u03B2'}, + {"gamma", '\u03B3'}, + {"delta", '\u03B4'}, + {"epsilon", '\u03B5'}, + {"zeta", '\u03B6'}, + {"eta", '\u03B7'}, + {"theta", '\u03B8'}, + {"iota", '\u03B9'}, + {"kappa", '\u03BA'}, + {"lambda", '\u03BB'}, + {"mu", '\u03BC'}, + {"nu", '\u03BD'}, + {"xi", '\u03BE'}, + {"omicron", '\u03BF'}, + {"pi", '\u03C0'}, + {"rho", '\u03C1'}, + {"sigmaf", '\u03C2'}, + {"sigma", '\u03C3'}, + {"tau", '\u03C4'}, + {"upsilon", '\u03C5'}, + {"phi", '\u03C6'}, + {"chi", '\u03C7'}, + {"psi", '\u03C8'}, + {"omega", '\u03C9'}, + {"thetasym", '\u03D1'}, + {"upsih", '\u03D2'}, + {"piv", '\u03D6'}, + {"bull", '\u2022'}, + {"hellip", '\u2026'}, + {"prime", '\u2032'}, + {"Prime", '\u2033'}, + {"oline", '\u203E'}, + {"frasl", '\u2044'}, + {"weierp", '\u2118'}, + {"image", '\u2111'}, + {"real", '\u211C'}, + {"trade", '\u2122'}, + {"alefsym", '\u2135'}, + {"larr", '\u2190'}, + {"uarr", '\u2191'}, + {"rarr", '\u2192'}, + {"darr", '\u2193'}, + {"harr", '\u2194'}, + {"crarr", '\u21B5'}, + {"lArr", '\u21D0'}, + {"uArr", '\u21D1'}, + {"rArr", '\u21D2'}, + {"dArr", '\u21D3'}, + {"hArr", '\u21D4'}, + {"forall", '\u2200'}, + {"part", '\u2202'}, + {"exist", '\u2203'}, + {"empty", '\u2205'}, + {"nabla", '\u2207'}, + {"isin", '\u2208'}, + {"notin", '\u2209'}, + {"ni", '\u220B'}, + {"prod", '\u220F'}, + {"sum", '\u2211'}, + {"minus", '\u2212'}, + {"lowast", '\u2217'}, + {"radic", '\u221A'}, + {"prop", '\u221D'}, + {"infin", '\u221E'}, + {"ang", '\u2220'}, + {"and", '\u2227'}, + {"or", '\u2228'}, + {"cap", '\u2229'}, + {"cup", '\u222A'}, + {"int", '\u222B'}, + {"there4", '\u2234'}, + {"sim", '\u223C'}, + {"cong", '\u2245'}, + {"asymp", '\u2248'}, + {"ne", '\u2260'}, + {"equiv", '\u2261'}, + {"le", '\u2264'}, + {"ge", '\u2265'}, + {"sub", '\u2282'}, + {"sup", '\u2283'}, + {"nsub", '\u2284'}, + {"sube", '\u2286'}, + {"supe", '\u2287'}, + {"oplus", '\u2295'}, + {"otimes", '\u2297'}, + {"perp", '\u22A5'}, + {"sdot", '\u22C5'}, + {"lceil", '\u2308'}, + {"rceil", '\u2309'}, + {"lfloor", '\u230A'}, + {"rfloor", '\u230B'}, + {"lang", '\u2329'}, + {"rang", '\u232A'}, + {"loz", '\u25CA'}, + {"spades", '\u2660'}, + {"clubs", '\u2663'}, + {"hearts", '\u2665'}, + {"diams", '\u2666'}, + {"quot", '\u0022'}, + {"amp", '\u0026'}, + {"lt", '\u003C'}, + {"gt", '\u003E'}, + {"OElig", '\u0152'}, + {"oelig", '\u0153'}, + {"Scaron", '\u0160'}, + {"scaron", '\u0161'}, + {"Yuml", '\u0178'}, + {"circ", '\u02C6'}, + {"tilde", '\u02DC'}, + {"ensp", '\u2002'}, + {"emsp", '\u2003'}, + {"thinsp", '\u2009'}, + {"zwnj", '\u200C'}, + {"zwj", '\u200D'}, + {"lrm", '\u200E'}, + {"rlm", '\u200F'}, + {"ndash", '\u2013'}, + {"mdash", '\u2014'}, + {"lsquo", '\u2018'}, + {"rsquo", '\u2019'}, + {"sbquo", '\u201A'}, + {"ldquo", '\u201C'}, + {"rdquo", '\u201D'}, + {"bdquo", '\u201E'}, + {"dagger", '\u2020'}, + {"Dagger", '\u2021'}, + {"permil", '\u2030'}, + {"lsaquo", '\u2039'}, + {"rsaquo", '\u203A'}, + {"euro", '\u20AC'} + }; } } } diff --git a/RestSharp/Extensions/MonoHttp/HttpUtility.cs b/RestSharp/Extensions/MonoHttp/HttpUtility.cs index 8899b3b41..73dfc7423 100644 --- a/RestSharp/Extensions/MonoHttp/HttpUtility.cs +++ b/RestSharp/Extensions/MonoHttp/HttpUtility.cs @@ -36,23 +36,20 @@ using System.IO; using System.Text; -namespace RestSharp.Contrib +namespace RestSharp.Extensions.MonoHttp { - - //#if !MONOTOUCH - // // CAS - no InheritanceDemand here as the class is sealed - // [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] - //#endif public sealed class HttpUtility { - sealed class HttpQSCollection : NameValueCollection + private sealed class HttpQsCollection : NameValueCollection { public override string ToString() { int count = Count; if (count == 0) + { return ""; + } StringBuilder sb = new StringBuilder(); string[] keys = AllKeys; @@ -63,52 +60,29 @@ public override string ToString() } if (sb.Length > 0) + { sb.Length--; + } return sb.ToString(); } } - #region Constructors - - public HttpUtility() { } - - #endregion // Constructors - #region Methods public static void HtmlAttributeEncode(string s, TextWriter output) { if (output == null) { -#if NET_4_0 - throw new ArgumentNullException ("output"); -#else throw new NullReferenceException(".NET emulation"); -#endif } -#if NET_4_0 - HttpEncoder.Current.HtmlAttributeEncode (s, output); -#else output.Write(HttpEncoder.HtmlAttributeEncode(s)); -#endif } public static string HtmlAttributeEncode(string s) { -#if NET_4_0 - if (s == null) - return null; - - using (var sw = new StringWriter ()) - { - HttpEncoder.Current.HtmlAttributeEncode (s, sw); - return sw.ToString (); - } -#else return HttpEncoder.HtmlAttributeEncode(s); -#endif } public static string UrlDecode(string str) @@ -116,59 +90,72 @@ public static string UrlDecode(string str) return UrlDecode(str, Encoding.UTF8); } - static char[] GetChars(MemoryStream b, Encoding e) + private static char[] GetChars(MemoryStream b, Encoding e) { - return e.GetChars(b.GetBuffer(), 0, (int)b.Length); + return e.GetChars(b.GetBuffer(), 0, (int) b.Length); } - static void WriteCharBytes(IList buf, char ch, Encoding e) + private static void WriteCharBytes(IList buf, char ch, Encoding e) { if (ch > 255) { - foreach (byte b in e.GetBytes(new char[] { ch })) + foreach (byte b in e.GetBytes(new [] { ch })) + { buf.Add(b); + } } else - buf.Add((byte)ch); + { + buf.Add((byte) ch); + } } public static string UrlDecode(string s, Encoding e) { if (null == s) + { return null; + } if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) + { return s; + } if (e == null) + { e = Encoding.UTF8; + } long len = s.Length; - var bytes = new List(); - int xchar; - char ch; + List bytes = new List(); for (int i = 0; i < len; i++) { - ch = s[i]; + char ch = s[i]; if (ch == '%' && i + 2 < len && s[i + 1] != '%') { + int xchar; + if (s[i + 1] == 'u' && i + 5 < len) { // unicode hex sequence xchar = GetChar(s, i + 2, 4); + if (xchar != -1) { - WriteCharBytes(bytes, (char)xchar, e); + WriteCharBytes(bytes, (char) xchar, e); i += 5; } else + { WriteCharBytes(bytes, '%', e); + } } else if ((xchar = GetChar(s, i + 1, 2)) != -1) { - WriteCharBytes(bytes, (char)xchar, e); + WriteCharBytes(bytes, (char) xchar, e); i += 2; } else @@ -180,41 +167,53 @@ public static string UrlDecode(string s, Encoding e) } if (ch == '+') + { WriteCharBytes(bytes, ' ', e); + } else + { WriteCharBytes(bytes, ch, e); + } } byte[] buf = bytes.ToArray(); - bytes = null; + return e.GetString(buf, 0, buf.Length); } public static string UrlDecode(byte[] bytes, Encoding e) { if (bytes == null) + { return null; + } return UrlDecode(bytes, 0, bytes.Length, e); } - static int GetInt(byte b) + private static int GetInt(byte b) { - char c = (char)b; + char c = (char) b; if (c >= '0' && c <= '9') + { return c - '0'; + } if (c >= 'a' && c <= 'f') + { return c - 'a' + 10; + } if (c >= 'A' && c <= 'F') + { return c - 'A' + 10; + } return -1; } - static int GetChar(byte[] bytes, int offset, int length) + private static int GetChar(byte[] bytes, int offset, int length) { int value = 0; int end = length + offset; @@ -224,7 +223,9 @@ static int GetChar(byte[] bytes, int offset, int length) int current = GetInt(bytes[i]); if (current == -1) + { return -1; + } value = (value << 4) + current; } @@ -232,7 +233,7 @@ static int GetChar(byte[] bytes, int offset, int length) return value; } - static int GetChar(string str, int offset, int length) + private static int GetChar(string str, int offset, int length) { int val = 0; int end = length + offset; @@ -242,12 +243,16 @@ static int GetChar(string str, int offset, int length) char c = str[i]; if (c > 127) + { return -1; + } - int current = GetInt((byte)c); + int current = GetInt((byte) c); if (current == -1) + { return -1; + } val = (val << 4) + current; } @@ -258,31 +263,42 @@ static int GetChar(string str, int offset, int length) public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) { if (bytes == null) + { return null; + } if (count == 0) - return String.Empty; + { + return string.Empty; + } if (bytes == null) + { throw new ArgumentNullException("bytes"); + } if (offset < 0 || offset > bytes.Length) + { throw new ArgumentOutOfRangeException("offset"); + } if (count < 0 || offset + count > bytes.Length) + { throw new ArgumentOutOfRangeException("count"); + } StringBuilder output = new StringBuilder(); MemoryStream acc = new MemoryStream(); int end = count + offset; - int xchar; for (int i = offset; i < end; i++) { if (bytes[i] == '%' && i + 2 < count && bytes[i + 1] != '%') { - if (bytes[i + 1] == (byte)'u' && i + 5 < end) + int xchar; + + if (bytes[i + 1] == (byte) 'u' && i + 5 < end) { if (acc.Length > 0) { @@ -294,7 +310,7 @@ public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) if (xchar != -1) { - output.Append((char)xchar); + output.Append((char) xchar); i += 5; continue; @@ -302,7 +318,7 @@ public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) } else if ((xchar = GetChar(bytes, i + 1, 2)) != -1) { - acc.WriteByte((byte)xchar); + acc.WriteByte((byte) xchar); i += 2; continue; @@ -321,7 +337,7 @@ public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) } else { - output.Append((char)bytes[i]); + output.Append((char) bytes[i]); } } @@ -330,15 +346,15 @@ public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) output.Append(GetChars(acc, e)); } - acc = null; - return output.ToString(); } public static byte[] UrlDecodeToBytes(byte[] bytes) { if (bytes == null) + { return null; + } return UrlDecodeToBytes(bytes, 0, bytes.Length); } @@ -351,10 +367,14 @@ public static byte[] UrlDecodeToBytes(string str) public static byte[] UrlDecodeToBytes(string str, Encoding e) { if (str == null) + { return null; + } if (e == null) + { throw new ArgumentNullException("e"); + } return UrlDecodeToBytes(e.GetBytes(str)); } @@ -362,25 +382,33 @@ public static byte[] UrlDecodeToBytes(string str, Encoding e) public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) + { return null; + } if (count == 0) + { return new byte[0]; + } int len = bytes.Length; if (offset < 0 || offset >= len) + { throw new ArgumentOutOfRangeException("offset"); + } if (count < 0 || offset > len - count) + { throw new ArgumentOutOfRangeException("count"); + } MemoryStream result = new MemoryStream(); int end = offset + count; for (int i = offset; i < end; i++) { - char c = (char)bytes[i]; + char c = (char) bytes[i]; if (c == '+') { @@ -392,12 +420,12 @@ public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count) if (xchar != -1) { - c = (char)xchar; + c = (char) xchar; i += 2; } } - result.WriteByte((byte)c); + result.WriteByte((byte) c); } return result.ToArray(); @@ -408,13 +436,17 @@ public static string UrlEncode(string str) return UrlEncode(str, Encoding.UTF8); } - public static string UrlEncode(string s, Encoding Enc) + public static string UrlEncode(string s, Encoding enc) { if (s == null) + { return null; + } - if (s == String.Empty) - return String.Empty; + if (s == string.Empty) + { + return string.Empty; + } bool needEncode = false; int len = s.Length; @@ -426,7 +458,9 @@ public static string UrlEncode(string s, Encoding Enc) if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) { if (HttpEncoder.NotEncoded(c)) + { continue; + } needEncode = true; break; @@ -434,11 +468,13 @@ public static string UrlEncode(string s, Encoding Enc) } if (!needEncode) + { return s; + } // avoided GetByteCount call - byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)]; - int realLen = Enc.GetBytes(s, 0, s.Length, bytes, 0); + byte[] bytes = new byte[enc.GetMaxByteCount(s.Length)]; + int realLen = enc.GetBytes(s, 0, s.Length, bytes, 0); byte[] r = UrlEncodeToBytes(bytes, 0, realLen); return Encoding.ASCII.GetString(r, 0, r.Length); @@ -447,10 +483,14 @@ public static string UrlEncode(string s, Encoding Enc) public static string UrlEncode(byte[] bytes) { if (bytes == null) + { return null; + } if (bytes.Length == 0) - return String.Empty; + { + return string.Empty; + } byte[] r = UrlEncodeToBytes(bytes, 0, bytes.Length); @@ -460,10 +500,14 @@ public static string UrlEncode(byte[] bytes) public static string UrlEncode(byte[] bytes, int offset, int count) { if (bytes == null) + { return null; + } if (bytes.Length == 0) - return String.Empty; + { + return string.Empty; + } byte[] r = UrlEncodeToBytes(bytes, offset, count); @@ -478,10 +522,14 @@ public static byte[] UrlEncodeToBytes(string str) public static byte[] UrlEncodeToBytes(string str, Encoding e) { if (str == null) + { return null; + } if (str.Length == 0) + { return new byte[0]; + } byte[] bytes = e.GetBytes(str); @@ -491,10 +539,14 @@ public static byte[] UrlEncodeToBytes(string str, Encoding e) public static byte[] UrlEncodeToBytes(byte[] bytes) { if (bytes == null) + { return null; + } if (bytes.Length == 0) + { return new byte[0]; + } return UrlEncodeToBytes(bytes, 0, bytes.Length); } @@ -502,19 +554,19 @@ public static byte[] UrlEncodeToBytes(byte[] bytes) public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) + { return null; + } -#if NET_4_0 - return HttpEncoder.Current.UrlEncode (bytes, offset, count); -#else return HttpEncoder.UrlEncodeToBytes(bytes, offset, count); -#endif } public static string UrlEncodeUnicode(string str) { if (str == null) + { return null; + } byte[] r = UrlEncodeUnicodeToBytes(str); @@ -524,10 +576,14 @@ public static string UrlEncodeUnicode(string str) public static byte[] UrlEncodeUnicodeToBytes(string str) { if (str == null) + { return null; + } if (str.Length == 0) + { return new byte[0]; + } MemoryStream result = new MemoryStream(str.Length); @@ -546,18 +602,7 @@ public static byte[] UrlEncodeUnicodeToBytes(string str) /// The decoded text. public static string HtmlDecode(string s) { -#if NET_4_0 - if (s == null) - return null; - - using (var sw = new StringWriter ()) - { - HttpEncoder.Current.HtmlDecode (s, sw); - return sw.ToString (); - } -#else return HttpEncoder.HtmlDecode(s); -#endif } /// @@ -569,37 +614,18 @@ public static void HtmlDecode(string s, TextWriter output) { if (output == null) { -#if NET_4_0 - throw new ArgumentNullException ("output"); -#else throw new NullReferenceException(".NET emulation"); -#endif } - if (!String.IsNullOrEmpty(s)) + if (!string.IsNullOrEmpty(s)) { -#if NET_4_0 - HttpEncoder.Current.HtmlDecode (s, output); -#else output.Write(HttpEncoder.HtmlDecode(s)); -#endif } } public static string HtmlEncode(string s) { -#if NET_4_0 - if (s == null) - return null; - - using (var sw = new StringWriter ()) - { - HttpEncoder.Current.HtmlEncode (s, sw); - return sw.ToString (); - } -#else return HttpEncoder.HtmlEncode(s); -#endif } /// @@ -611,128 +637,18 @@ public static void HtmlEncode(string s, TextWriter output) { if (output == null) { -#if NET_4_0 - throw new ArgumentNullException ("output"); -#else throw new NullReferenceException(".NET emulation"); -#endif } - if (!String.IsNullOrEmpty(s)) + if (!string.IsNullOrEmpty(s)) { -#if NET_4_0 - HttpEncoder.Current.HtmlEncode (s, output); -#else output.Write(HttpEncoder.HtmlEncode(s)); -#endif } } -#if NET_4_0 - public static string HtmlEncode (object value) - { - if (value == null) - return null; - - IHtmlString htmlString = value as IHtmlString; - - if (htmlString != null) - return htmlString.ToHtmlString (); - - return HtmlEncode (value.ToString ()); - } - - public static string JavaScriptStringEncode (string value) - { - return JavaScriptStringEncode (value, false); - } - - public static string JavaScriptStringEncode (string value, bool addDoubleQuotes) - { - if (String.IsNullOrEmpty (value)) - return addDoubleQuotes ? "\"\"" : String.Empty; - - int len = value.Length; - bool needEncode = false; - char c; - - for (int i = 0; i < len; i++) - { - c = value [i]; - - if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92) { - needEncode = true; - break; - } - } - - if (!needEncode) - return addDoubleQuotes ? "\"" + value + "\"" : value; - - var sb = new StringBuilder(); - - if (addDoubleQuotes) - sb.Append ('"'); - - for (int i = 0; i < len; i++) - { - c = value [i]; - - if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62) - sb.AppendFormat ("\\u{0:x4}", (int)c); - else - { - switch ((int)c) - { - case 8: - sb.Append ("\\b"); - break; - - case 9: - sb.Append ("\\t"); - break; - - case 10: - sb.Append ("\\n"); - break; - - case 12: - sb.Append ("\\f"); - break; - - case 13: - sb.Append ("\\r"); - break; - - case 34: - sb.Append ("\\\""); - break; - - case 92: - sb.Append ("\\\\"); - break; - - default: - sb.Append (c); - break; - } - } - } - - if (addDoubleQuotes) - sb.Append ('"'); - - return sb.ToString (); - } -#endif - public static string UrlPathEncode(string s) { -#if NET_4_0 - return HttpEncoder.Current.UrlPathEncode (s); -#else return HttpEncoder.UrlPathEncode(s); -#endif } public static NameValueCollection ParseQueryString(string query) @@ -743,18 +659,26 @@ public static NameValueCollection ParseQueryString(string query) public static NameValueCollection ParseQueryString(string query, Encoding encoding) { if (query == null) + { throw new ArgumentNullException("query"); + } if (encoding == null) + { throw new ArgumentNullException("encoding"); + } if (query.Length == 0 || (query.Length == 1 && query[0] == '?')) + { return new NameValueCollection(); + } if (query[0] == '?') + { query = query.Substring(1); + } - NameValueCollection result = new HttpQSCollection(); + NameValueCollection result = new HttpQsCollection(); ParseQueryString(query, encoding, result); @@ -764,7 +688,9 @@ public static NameValueCollection ParseQueryString(string query, Encoding encodi internal static void ParseQueryString(string query, Encoding encoding, NameValueCollection result) { if (query.Length == 0) + { return; + } string decoded = HtmlDecode(query); int decodedLength = decoded.Length; @@ -773,7 +699,8 @@ internal static void ParseQueryString(string query, Encoding encoding, NameValue while (namePos <= decodedLength) { - int valuePos = -1, valueEnd = -1; + int valuePos = -1, + valueEnd = -1; for (int q = namePos; q < decodedLength; q++) { @@ -793,11 +720,12 @@ internal static void ParseQueryString(string query, Encoding encoding, NameValue first = false; if (decoded[namePos] == '?') + { namePos++; + } } - string name, - value; + string name; if (valuePos == -1) { @@ -819,15 +747,17 @@ internal static void ParseQueryString(string query, Encoding encoding, NameValue namePos = valueEnd + 1; } - value = UrlDecode(decoded.Substring(valuePos, valueEnd - valuePos), encoding); + string value = UrlDecode(decoded.Substring(valuePos, valueEnd - valuePos), encoding); result.Add(name, value); if (namePos == -1) + { break; + } } } - #endregion // Methods + #endregion } } diff --git a/RestSharp/Extensions/ReflectionExtensions.cs b/RestSharp/Extensions/ReflectionExtensions.cs index 2c40af09c..a872b2566 100644 --- a/RestSharp/Extensions/ReflectionExtensions.cs +++ b/RestSharp/Extensions/ReflectionExtensions.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,13 +13,17 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Globalization; -using System.Linq; using System.Reflection; +#if FRAMEWORK +using System.Linq; +#endif + namespace RestSharp.Extensions { /// @@ -56,9 +61,11 @@ public static T GetAttribute(this Type type) where T : Attribute /// public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) { - while (toCheck != typeof(object)) + while (toCheck != null && toCheck != typeof(object)) { - var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; + Type cur = toCheck.IsGenericType + ? toCheck.GetGenericTypeDefinition() + : toCheck; if (generic == cur) { @@ -73,7 +80,7 @@ public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) public static object ChangeType(this object source, Type newType) { -#if FRAMEWORK && !PocketPC +#if FRAMEWORK return Convert.ChangeType(source, newType); #else return Convert.ChangeType(source, newType, null); @@ -99,20 +106,20 @@ public static object ChangeType(this object source, Type newType, CultureInfo cu /// public static object FindEnumValue(this Type type, string value, CultureInfo culture) { -#if FRAMEWORK && !PocketPC - var ret = Enum.GetValues(type) - .Cast() - .FirstOrDefault(v => v.ToString() - .GetNameVariants(culture) - .Contains(value, StringComparer.Create(culture, true))); +#if FRAMEWORK + Enum ret = Enum.GetValues(type) + .Cast() + .FirstOrDefault(v => v.ToString() + .GetNameVariants(culture) + .Contains(value, StringComparer.Create(culture, true))); if (ret == null) { - var enumValueAsUnderlyingType = Convert.ChangeType(value, Enum.GetUnderlyingType(type), culture); + object enumValueAsUnderlyingType = Convert.ChangeType(value, Enum.GetUnderlyingType(type), culture); if (enumValueAsUnderlyingType != null && Enum.IsDefined(type, enumValueAsUnderlyingType)) { - ret = (Enum)Enum.ToObject(type, enumValueAsUnderlyingType); + ret = (Enum) Enum.ToObject(type, enumValueAsUnderlyingType); } } diff --git a/RestSharp/Extensions/ResponseExtensions.cs b/RestSharp/Extensions/ResponseExtensions.cs index ec078a12f..ed747cccb 100644 --- a/RestSharp/Extensions/ResponseExtensions.cs +++ b/RestSharp/Extensions/ResponseExtensions.cs @@ -1,26 +1,25 @@ - -namespace RestSharp.Extensions +namespace RestSharp.Extensions { public static class ResponseExtensions { public static IRestResponse ToAsyncResponse(this IRestResponse response) { return new RestResponse - { - ContentEncoding = response.ContentEncoding, - ContentLength = response.ContentLength, - ContentType = response.ContentType, - Cookies = response.Cookies, - ErrorException = response.ErrorException, - ErrorMessage = response.ErrorMessage, - Headers = response.Headers, - RawBytes = response.RawBytes, - ResponseStatus = response.ResponseStatus, - ResponseUri = response.ResponseUri, - Server = response.Server, - StatusCode = response.StatusCode, - StatusDescription = response.StatusDescription - }; + { + ContentEncoding = response.ContentEncoding, + ContentLength = response.ContentLength, + ContentType = response.ContentType, + Cookies = response.Cookies, + ErrorException = response.ErrorException, + ErrorMessage = response.ErrorMessage, + Headers = response.Headers, + RawBytes = response.RawBytes, + ResponseStatus = response.ResponseStatus, + ResponseUri = response.ResponseUri, + Server = response.Server, + StatusCode = response.StatusCode, + StatusDescription = response.StatusDescription + }; } } } diff --git a/RestSharp/Extensions/StringExtensions.cs b/RestSharp/Extensions/StringExtensions.cs index 64c33a0ce..48cbd8cbc 100644 --- a/RestSharp/Extensions/StringExtensions.cs +++ b/RestSharp/Extensions/StringExtensions.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,37 +13,35 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Collections.Generic; -using System.Linq; -using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Globalization; -#if SILVERLIGHT -using System.Windows.Browser; +#if WINDOWS_PHONE +using System.Net; #endif -#if WINDOWS_PHONE +#if SILVERLIGHT +using System.Windows.Browser; #endif -#if FRAMEWORK || MONOTOUCH || MONODROID -using RestSharp.Contrib; +#if !SILVERLIGHT && !WINDOWS_PHONE +using RestSharp.Extensions.MonoHttp; #endif namespace RestSharp.Extensions { public static class StringExtensions { -#if !PocketPC public static string UrlDecode(this string input) { return HttpUtility.UrlDecode(input); } -#endif /// /// Uses Uri.EscapeDataString() based on recommendations on MSDN @@ -51,11 +50,16 @@ public static string UrlDecode(this string input) public static string UrlEncode(this string input) { const int maxLength = 32766; + if (input == null) + { throw new ArgumentNullException("input"); + } if (input.Length <= maxLength) + { return Uri.EscapeDataString(input); + } StringBuilder sb = new StringBuilder(input.Length * 2); int index = 0; @@ -72,7 +76,6 @@ public static string UrlEncode(this string input) return sb.ToString(); } -#if !PocketPC public static string HtmlDecode(this string input) { return HttpUtility.HtmlDecode(input); @@ -82,7 +85,6 @@ public static string HtmlEncode(this string input) { return HttpUtility.HtmlEncode(input); } -#endif #if FRAMEWORK public static string HtmlAttributeEncode(this string input) @@ -108,7 +110,8 @@ public static bool HasValue(this string input) /// string public static string RemoveUnderscoresAndDashes(this string input) { - return input.Replace("_", "").Replace("-", ""); // avoiding regex + return input.Replace("_", "") + .Replace("-", ""); // avoiding regex } /// @@ -123,18 +126,13 @@ public static DateTime ParseJsonDate(this string input, CultureInfo culture) input = input.Replace("\r", ""); input = input.RemoveSurroundingQuotes(); - long? unix = null; + long unix; - try + if (long.TryParse(input, out unix)) { - unix = Int64.Parse(input); - } - catch (Exception) { }; + DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - if (unix.HasValue) - { - var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return epoch.AddSeconds(unix.Value); + return epoch.AddSeconds(unix); } if (input.Contains("/Date(")) @@ -145,6 +143,7 @@ public static DateTime ParseJsonDate(this string input, CultureInfo culture) if (input.Contains("new Date(")) { input = input.Replace(" ", ""); + // because all whitespace is removed, match against newDate( instead of new Date( return ExtractDate(input, @"newDate\((-?\d+)*\)", culture); } @@ -170,7 +169,7 @@ public static string RemoveSurroundingQuotes(this string input) private static DateTime ParseFormattedDate(string input, CultureInfo culture) { - var formats = new[] + string[] formats = { "u", "s", @@ -182,22 +181,6 @@ private static DateTime ParseFormattedDate(string input, CultureInfo culture) "M/d/yyyy h:mm:ss tt" // default format for invariant culture }; -#if PocketPC - foreach (string format in formats) - { - try - { - return DateTime.ParseExact(input, format, culture); - } - catch (Exception) { } - } - - try - { - return DateTime.Parse(input, culture); - } - catch (Exception) { } -#else DateTime date; if (DateTime.TryParseExact(input, formats, culture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out date)) @@ -209,7 +192,6 @@ private static DateTime ParseFormattedDate(string input, CultureInfo culture) { return date; } -#endif return default(DateTime); } @@ -217,30 +199,25 @@ private static DateTime ParseFormattedDate(string input, CultureInfo culture) private static DateTime ExtractDate(string input, string pattern, CultureInfo culture) { DateTime dt = DateTime.MinValue; - var regex = new Regex(pattern); + Regex regex = new Regex(pattern); if (regex.IsMatch(input)) { - var matches = regex.Matches(input); - var match = matches[0]; - var ms = Convert.ToInt64(match.Groups[1].Value); - var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + MatchCollection matches = regex.Matches(input); + Match match = matches[0]; + long ms = Convert.ToInt64(match.Groups[1].Value); + DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); dt = epoch.AddMilliseconds(ms); // adjust if time zone modifier present - if (match.Groups.Count > 2 && !String.IsNullOrEmpty(match.Groups[3].Value)) + if (match.Groups.Count > 2 && !string.IsNullOrEmpty(match.Groups[3].Value)) { - var mod = DateTime.ParseExact(match.Groups[3].Value, "HHmm", culture); + DateTime mod = DateTime.ParseExact(match.Groups[3].Value, "HHmm", culture); - if (match.Groups[2].Value == "+") - { - dt = dt.Add(mod.TimeOfDay); - } - else - { - dt = dt.Subtract(mod.TimeOfDay); - } + dt = match.Groups[2].Value == "+" + ? dt.Add(mod.TimeOfDay) + : dt.Subtract(mod.TimeOfDay); } } @@ -278,12 +255,16 @@ public static string ToPascalCase(this string lowercaseAndUnderscoredWord, Cultu /// public static string ToPascalCase(this string text, bool removeUnderscores, CultureInfo culture) { - if (String.IsNullOrEmpty(text)) + if (string.IsNullOrEmpty(text)) + { return text; + } text = text.Replace("_", " "); - string joinString = removeUnderscores ? String.Empty : "_"; + string joinString = removeUnderscores + ? string.Empty + : "_"; string[] words = text.Split(' '); if (words.Length > 1 || words[0].IsUpperCase()) @@ -296,18 +277,20 @@ public static string ToPascalCase(this string text, bool removeUnderscores, Cult string restOfWord = word.Substring(1); if (restOfWord.IsUpperCase()) + { restOfWord = restOfWord.ToLower(culture); + } char firstChar = char.ToUpper(word[0], culture); - words[i] = String.Concat(firstChar, restOfWord); + words[i] = string.Concat(firstChar, restOfWord); } } - return String.Join(joinString, words); + return string.Join(joinString, words); } - return String.Concat(words[0].Substring(0, 1).ToUpper(culture), words[0].Substring(1)); + return string.Concat(words[0].Substring(0, 1).ToUpper(culture), words[0].Substring(1)); } /// @@ -328,7 +311,7 @@ public static string ToCamelCase(this string lowercaseAndUnderscoredWord, Cultur /// string public static string MakeInitialLowerCase(this string word) { - return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); + return string.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); } /// @@ -407,8 +390,10 @@ public static string AddSpaces(this string pascalCasedWord) /// IEnumerable<string> public static IEnumerable GetNameVariants(this string name, CultureInfo culture) { - if (String.IsNullOrEmpty(name)) + if (string.IsNullOrEmpty(name)) + { yield break; + } yield return name; diff --git a/RestSharp/Extensions/XmlExtensions.cs b/RestSharp/Extensions/XmlExtensions.cs index a066c19d3..b515d445c 100644 --- a/RestSharp/Extensions/XmlExtensions.cs +++ b/RestSharp/Extensions/XmlExtensions.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System.Xml.Linq; @@ -34,7 +36,9 @@ public static XName AsNamespaced(this string name, string @namespace) XName xName = name; if (@namespace.HasValue()) + { xName = XName.Get(name, @namespace); + } return xName; } diff --git a/RestSharp/FileParameter.cs b/RestSharp/FileParameter.cs index f04001978..51fdfe3c7 100644 --- a/RestSharp/FileParameter.cs +++ b/RestSharp/FileParameter.cs @@ -18,20 +18,20 @@ public class FileParameter ///The public static FileParameter Create(string name, byte[] data, string filename, string contentType) { -#if FRAMEWORK && !PocketPC - var length = data.LongLength; +#if FRAMEWORK + long length = data.LongLength; #else - var length = (long)data.Length; + long length = data.Length; #endif return new FileParameter - { - Writer = s => s.Write(data, 0, data.Length), - FileName = filename, - ContentType = contentType, - ContentLength = length, - Name = name - }; + { + Writer = s => s.Write(data, 0, data.Length), + FileName = filename, + ContentType = contentType, + ContentLength = length, + Name = name + }; } /// @@ -50,10 +50,12 @@ public static FileParameter Create(string name, byte[] data, string filename) /// The length of data to be sent /// public long ContentLength { get; set; } + /// /// Provides raw data for file /// public Action Writer { get; set; } + /// /// Name of the file to use when uploading /// diff --git a/RestSharp/Http.Async.cs b/RestSharp/Http.Async.cs index 684cfda6a..c9577b318 100644 --- a/RestSharp/Http.Async.cs +++ b/RestSharp/Http.Async.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,26 +13,24 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; -using System.Linq; +using System.IO; using System.Net; -using System.Threading; using RestSharp.Extensions; -#if SILVERLIGHT -using System.Windows.Browser; -using System.Net.Browser; +#if !WINDOWS_PHONE +using System.Linq; #endif -#if WINDOWS_PHONE -using System.Windows.Threading; -using System.Windows; +#if SILVERLIGHT +using System.Net.Browser; #endif -#if (FRAMEWORK && !MONOTOUCH && !MONODROID && !PocketPC) -using System.Web; +#if !WINDOWS_PHONE && !SILVERLIGHT +using System.Threading; #endif namespace RestSharp @@ -45,42 +44,42 @@ public partial class Http public HttpWebRequest DeleteAsync(Action action) { - return GetStyleMethodInternalAsync("DELETE", action); + return this.GetStyleMethodInternalAsync("DELETE", action); } public HttpWebRequest GetAsync(Action action) { - return GetStyleMethodInternalAsync("GET", action); + return this.GetStyleMethodInternalAsync("GET", action); } public HttpWebRequest HeadAsync(Action action) { - return GetStyleMethodInternalAsync("HEAD", action); + return this.GetStyleMethodInternalAsync("HEAD", action); } public HttpWebRequest OptionsAsync(Action action) { - return GetStyleMethodInternalAsync("OPTIONS", action); + return this.GetStyleMethodInternalAsync("OPTIONS", action); } public HttpWebRequest PostAsync(Action action) { - return PutPostInternalAsync("POST", action); + return this.PutPostInternalAsync("POST", action); } public HttpWebRequest PutAsync(Action action) { - return PutPostInternalAsync("PUT", action); + return this.PutPostInternalAsync("PUT", action); } public HttpWebRequest PatchAsync(Action action) { - return PutPostInternalAsync("PATCH", action); + return this.PutPostInternalAsync("PATCH", action); } public HttpWebRequest MergeAsync(Action action) { - return PutPostInternalAsync("MERGE", action); + return this.PutPostInternalAsync("MERGE", action); } /// @@ -91,11 +90,7 @@ public HttpWebRequest MergeAsync(Action action) /// public HttpWebRequest AsPostAsync(Action action, string httpMethod) { -#if PocketPC - return PutPostInternalAsync(httpMethod.ToUpper(), action); -#else - return PutPostInternalAsync(httpMethod.ToUpperInvariant(), action); -#endif + return this.PutPostInternalAsync(httpMethod.ToUpperInvariant(), action); } /// @@ -106,11 +101,7 @@ public HttpWebRequest AsPostAsync(Action action, string httpMethod /// public HttpWebRequest AsGetAsync(Action action, string httpMethod) { -#if PocketPC - return GetStyleMethodInternalAsync(httpMethod.ToUpper(), action); -#else - return GetStyleMethodInternalAsync(httpMethod.ToUpperInvariant(), action); -#endif + return this.GetStyleMethodInternalAsync(httpMethod.ToUpperInvariant(), action); } private HttpWebRequest GetStyleMethodInternalAsync(string method, Action callback) @@ -119,27 +110,28 @@ private HttpWebRequest GetStyleMethodInternalAsync(string method, Action ResponseCallback(result, callback), webRequest); + IAsyncResult asyncResult = webRequest.BeginGetResponse( + result => this.ResponseCallback(result, callback), webRequest); - SetTimeout(asyncResult, this.timeoutState); + this.SetTimeout(asyncResult, this.timeoutState); } } catch (Exception ex) { - ExecuteCallback(CreateErrorResponse(ex), callback); + ExecuteCallback(this.CreateErrorResponse(ex), callback); } return webRequest; @@ -147,18 +139,22 @@ private HttpWebRequest GetStyleMethodInternalAsync(string method, Action try { - webRequest = ConfigureAsyncWebRequest(method, Url); - PreparePostBody(webRequest); - WriteRequestBodyAsync(webRequest, callback); + webRequest = this.ConfigureAsyncWebRequest(method, this.Url); + this.PreparePostBody(webRequest); + this.WriteRequestBodyAsync(webRequest, callback); } catch (Exception ex) { - ExecuteCallback(CreateErrorResponse(ex), callback); + ExecuteCallback(this.CreateErrorResponse(ex), callback); } return webRequest; @@ -185,35 +181,39 @@ private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action RequestStreamCallback(result, callback), webRequest); + asyncResult = webRequest.BeginGetRequestStream( + result => this.RequestStreamCallback(result, callback), webRequest); } else { - asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest); + asyncResult = webRequest.BeginGetResponse(r => this.ResponseCallback(r, callback), webRequest); } - SetTimeout(asyncResult, this.timeoutState); + this.SetTimeout(asyncResult, this.timeoutState); } +#if !WINDOWS_PHONE private long CalculateContentLength() { - if (RequestBodyBytes != null) - return RequestBodyBytes.Length; + if (this.RequestBodyBytes != null) + { + return this.RequestBodyBytes.Length; + } - if (!HasFiles && !AlwaysMultipartFormData) + if (!this.HasFiles && !this.AlwaysMultipartFormData) { - return encoding.GetByteCount(RequestBody); + return this.encoding.GetByteCount(this.RequestBody); } // calculate length for multipart form long length = 0; - foreach (var file in Files) + foreach (HttpFile file in this.Files) { length += this.Encoding.GetByteCount(GetMultipartFileHeader(file)); length += file.ContentLength; @@ -224,56 +224,62 @@ private long CalculateContentLength() (current, param) => current + this.Encoding.GetByteCount(this.GetMultipartFormData(param))); length += this.Encoding.GetByteCount(GetMultipartFooter()); + return length; } +#endif private void RequestStreamCallback(IAsyncResult result, Action callback) { - var webRequest = (HttpWebRequest)result.AsyncState; + HttpWebRequest webRequest = (HttpWebRequest) result.AsyncState; if (this.timeoutState.TimedOut) { - var response = new HttpResponse { ResponseStatus = ResponseStatus.TimedOut }; + HttpResponse response = new HttpResponse { ResponseStatus = ResponseStatus.TimedOut }; + ExecuteCallback(response, callback); + return; } // write body to request stream try { - using (var requestStream = webRequest.EndGetRequestStream(result)) + using (Stream requestStream = webRequest.EndGetRequestStream(result)) { - if (HasFiles || AlwaysMultipartFormData) + if (this.HasFiles || this.AlwaysMultipartFormData) { - WriteMultipartFormData(requestStream); + this.WriteMultipartFormData(requestStream); } - else if (RequestBodyBytes != null) + else if (this.RequestBodyBytes != null) { - requestStream.Write(RequestBodyBytes, 0, RequestBodyBytes.Length); + requestStream.Write(this.RequestBodyBytes, 0, this.RequestBodyBytes.Length); } - else if (RequestBody != null) + else if (this.RequestBody != null) { - WriteStringTo(requestStream, RequestBody); + this.WriteStringTo(requestStream, this.RequestBody); } } } catch (Exception ex) { - ExecuteCallback(CreateErrorResponse(ex), callback); + ExecuteCallback(this.CreateErrorResponse(ex), callback); + return; } - IAsyncResult asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest); - SetTimeout(asyncResult, this.timeoutState); + IAsyncResult asyncResult = webRequest.BeginGetResponse(r => this.ResponseCallback(r, callback), webRequest); + + this.SetTimeout(asyncResult, this.timeoutState); } private void SetTimeout(IAsyncResult asyncResult, TimeOutState timeOutState) { -#if FRAMEWORK && !PocketPC - if (Timeout != 0) +#if FRAMEWORK + if (this.Timeout != 0) { ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, - TimeoutCallback, timeOutState, Timeout, true); + TimeoutCallback, timeOutState, this.Timeout, true); } #endif } @@ -281,9 +287,11 @@ private void SetTimeout(IAsyncResult asyncResult, TimeOutState timeOutState) private static void TimeoutCallback(object state, bool timedOut) { if (!timedOut) + { return; + } - var timeoutState = state as TimeOutState; + TimeOutState timeoutState = state as TimeOutState; if (timeoutState == null) { @@ -307,7 +315,8 @@ private static void GetRawResponseAsync(IAsyncResult result, Action callback) { - var response = new HttpResponse { ResponseStatus = ResponseStatus.None }; + HttpResponse response = new HttpResponse { ResponseStatus = ResponseStatus.None }; try { @@ -351,18 +360,19 @@ private void ResponseCallback(IAsyncResult result, Action callback { response.ResponseStatus = ResponseStatus.TimedOut; ExecuteCallback(response, callback); + return; } GetRawResponseAsync(result, webResponse => - { - ExtractResponseData(response, webResponse); - ExecuteCallback(response, callback); - }); + { + this.ExtractResponseData(response, webResponse); + ExecuteCallback(response, callback); + }); } catch (Exception ex) { - ExecuteCallback(CreateErrorResponse(ex), callback); + ExecuteCallback(this.CreateErrorResponse(ex), callback); } } @@ -381,6 +391,7 @@ private static void PopulateErrorForIncompleteResponse(HttpResponse response) } } +#if SILVERLIGHT || WINDOW_PHONE partial void AddAsyncHeaderActions() { #if SILVERLIGHT @@ -392,6 +403,7 @@ partial void AddAsyncHeaderActions() restrictedHeaderActions.Add("Content-Length", (r, v) => { }); #endif } +#endif // TODO: Try to merge the shared parts between ConfigureWebRequest and ConfigureAsyncWebRequest (quite a bit of code // TODO: duplication at the moment). @@ -401,81 +413,78 @@ private HttpWebRequest ConfigureAsyncWebRequest(string method, Uri url) WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp); WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); #endif - var webRequest = (HttpWebRequest)WebRequest.Create(url); -#if !PocketPC - webRequest.UseDefaultCredentials = UseDefaultCredentials; -#endif + HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url); + + webRequest.UseDefaultCredentials = this.UseDefaultCredentials; #if !WINDOWS_PHONE && !SILVERLIGHT - webRequest.PreAuthenticate = PreAuthenticate; + webRequest.PreAuthenticate = this.PreAuthenticate; #endif - AppendHeaders(webRequest); - AppendCookies(webRequest); + this.AppendHeaders(webRequest); + this.AppendCookies(webRequest); webRequest.Method = method; // make sure Content-Length header is always sent since default is -1 -#if !WINDOWS_PHONE && !PocketPC +#if !WINDOWS_PHONE // WP7 doesn't as of Beta doesn't support a way to set this value either directly // or indirectly - if (!HasFiles && !AlwaysMultipartFormData) + if (!this.HasFiles && !this.AlwaysMultipartFormData) { webRequest.ContentLength = 0; } #endif - if (Credentials != null) + if (this.Credentials != null) { - webRequest.Credentials = Credentials; + webRequest.Credentials = this.Credentials; } #if !SILVERLIGHT - if (UserAgent.HasValue()) + if (this.UserAgent.HasValue()) { - webRequest.UserAgent = UserAgent; + webRequest.UserAgent = this.UserAgent; } #endif #if FRAMEWORK - if (ClientCertificates != null) + if (this.ClientCertificates != null) { - webRequest.ClientCertificates.AddRange(ClientCertificates); + webRequest.ClientCertificates.AddRange(this.ClientCertificates); } webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None; webRequest.ServicePoint.Expect100Continue = false; - if (Timeout != 0) + if (this.Timeout != 0) { - webRequest.Timeout = Timeout; + webRequest.Timeout = this.Timeout; } - if (ReadWriteTimeout != 0) + if (this.ReadWriteTimeout != 0) { - webRequest.ReadWriteTimeout = ReadWriteTimeout; + webRequest.ReadWriteTimeout = this.ReadWriteTimeout; } - if (Proxy != null) + if (this.Proxy != null) { - webRequest.Proxy = Proxy; + webRequest.Proxy = this.Proxy; } -#if FRAMEWORK - if (CachePolicy != null) + if (this.CachePolicy != null) { - webRequest.CachePolicy = CachePolicy; + webRequest.CachePolicy = this.CachePolicy; } -#endif - if (FollowRedirects && MaxRedirects.HasValue) + if (this.FollowRedirects && this.MaxRedirects.HasValue) { - webRequest.MaximumAutomaticRedirections = MaxRedirects.Value; + webRequest.MaximumAutomaticRedirections = this.MaxRedirects.Value; } #endif #if !SILVERLIGHT - webRequest.AllowAutoRedirect = FollowRedirects; + webRequest.AllowAutoRedirect = this.FollowRedirects; #endif return webRequest; } diff --git a/RestSharp/Http.Sync.cs b/RestSharp/Http.Sync.cs index a08d234db..24e2080ff 100644 --- a/RestSharp/Http.Sync.cs +++ b/RestSharp/Http.Sync.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,16 +13,14 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion -#if FRAMEWORK || PocketPC +#if FRAMEWORK + using System; +using System.IO; using System.Net; - -#if !MONOTOUCH && !MONODROID && !PocketPC -using System.Web; -#endif - using RestSharp.Extensions; namespace RestSharp @@ -36,7 +35,7 @@ public partial class Http /// public HttpResponse Post() { - return PostPutInternal("POST"); + return this.PostPutInternal("POST"); } /// @@ -44,7 +43,7 @@ public HttpResponse Post() /// public HttpResponse Put() { - return PostPutInternal("PUT"); + return this.PostPutInternal("PUT"); } /// @@ -52,7 +51,7 @@ public HttpResponse Put() /// public HttpResponse Get() { - return GetStyleMethodInternal("GET"); + return this.GetStyleMethodInternal("GET"); } /// @@ -60,7 +59,7 @@ public HttpResponse Get() /// public HttpResponse Head() { - return GetStyleMethodInternal("HEAD"); + return this.GetStyleMethodInternal("HEAD"); } /// @@ -68,7 +67,7 @@ public HttpResponse Head() /// public HttpResponse Options() { - return GetStyleMethodInternal("OPTIONS"); + return this.GetStyleMethodInternal("OPTIONS"); } /// @@ -76,7 +75,7 @@ public HttpResponse Options() /// public HttpResponse Delete() { - return GetStyleMethodInternal("DELETE"); + return this.GetStyleMethodInternal("DELETE"); } /// @@ -84,7 +83,7 @@ public HttpResponse Delete() /// public HttpResponse Patch() { - return PostPutInternal("PATCH"); + return this.PostPutInternal("PATCH"); } /// @@ -92,7 +91,7 @@ public HttpResponse Patch() /// public HttpResponse Merge() { - return PostPutInternal("MERGE"); + return this.PostPutInternal("MERGE"); } /// @@ -102,11 +101,7 @@ public HttpResponse Merge() /// public HttpResponse AsGet(string httpMethod) { -#if PocketPC - return GetStyleMethodInternal(httpMethod.ToUpper()); -#else - return GetStyleMethodInternal(httpMethod.ToUpperInvariant()); -#endif + return this.GetStyleMethodInternal(httpMethod.ToUpperInvariant()); } /// @@ -116,56 +111,57 @@ public HttpResponse AsGet(string httpMethod) /// public HttpResponse AsPost(string httpMethod) { -#if PocketPC - return PostPutInternal(httpMethod.ToUpper()); -#else - return PostPutInternal(httpMethod.ToUpperInvariant()); -#endif + return this.PostPutInternal(httpMethod.ToUpperInvariant()); } private HttpResponse GetStyleMethodInternal(string method) { - var webRequest = ConfigureWebRequest(method, Url); + HttpWebRequest webRequest = this.ConfigureWebRequest(method, this.Url); - if (HasBody && (method == "DELETE" || method == "OPTIONS")) + if (this.HasBody && (method == "DELETE" || method == "OPTIONS")) { - webRequest.ContentType = RequestContentType; - WriteRequestBody(webRequest); + webRequest.ContentType = this.RequestContentType; + this.WriteRequestBody(webRequest); } - return GetResponse(webRequest); + return this.GetResponse(webRequest); } private HttpResponse PostPutInternal(string method) { - var webRequest = ConfigureWebRequest(method, Url); + HttpWebRequest webRequest = this.ConfigureWebRequest(method, this.Url); - PreparePostBody(webRequest); + this.PreparePostBody(webRequest); - WriteRequestBody(webRequest); - return GetResponse(webRequest); + this.WriteRequestBody(webRequest); + return this.GetResponse(webRequest); } partial void AddSyncHeaderActions() { - restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v); - restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); - restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v); - restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v)); - restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v); - restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; }); - restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v); + this.restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v); + this.restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); + this.restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v); + this.restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v)); + this.restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v); + this.restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => + { + r.TransferEncoding = v; + r.SendChunked = true; + }); + this.restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v); } private void ExtractErrorResponse(HttpResponse httpResponse, Exception ex) { - var webException = ex as WebException; + WebException webException = ex as WebException; if (webException != null && webException.Status == WebExceptionStatus.Timeout) { httpResponse.ResponseStatus = ResponseStatus.TimedOut; httpResponse.ErrorMessage = ex.Message; httpResponse.ErrorException = webException; + return; } @@ -176,16 +172,17 @@ private void ExtractErrorResponse(HttpResponse httpResponse, Exception ex) private HttpResponse GetResponse(HttpWebRequest request) { - var response = new HttpResponse { ResponseStatus = ResponseStatus.None }; + HttpResponse response = new HttpResponse { ResponseStatus = ResponseStatus.None }; try { - var webResponse = GetRawResponse(request); - ExtractResponseData(response, webResponse); + HttpWebResponse webResponse = GetRawResponse(request); + + this.ExtractResponseData(response, webResponse); } catch (Exception ex) { - ExtractErrorResponse(response, ex); + this.ExtractErrorResponse(response, ex); } return response; @@ -195,12 +192,11 @@ private static HttpWebResponse GetRawResponse(HttpWebRequest request) { try { - return (HttpWebResponse)request.GetResponse(); + return (HttpWebResponse) request.GetResponse(); } catch (WebException ex) { - -#if MONODROID +#if MONODROID // In Android the connections might start to hang (never return // responces) after 3 sequential connection failures (i.e: exceptions) request.Abort(); @@ -223,26 +219,26 @@ private static HttpWebResponse GetRawResponse(HttpWebRequest request) private void WriteRequestBody(HttpWebRequest webRequest) { - if (HasBody || HasFiles || AlwaysMultipartFormData) + if (this.HasBody || this.HasFiles || this.AlwaysMultipartFormData) { -#if !WINDOWS_PHONE && !PocketPC - webRequest.ContentLength = CalculateContentLength(); +#if !WINDOWS_PHONE + webRequest.ContentLength = this.CalculateContentLength(); #endif } - using (var requestStream = webRequest.GetRequestStream()) + using (Stream requestStream = webRequest.GetRequestStream()) { - if (HasFiles || AlwaysMultipartFormData) + if (this.HasFiles || this.AlwaysMultipartFormData) { - WriteMultipartFormData(requestStream); + this.WriteMultipartFormData(requestStream); } - else if (RequestBodyBytes != null) + else if (this.RequestBodyBytes != null) { - requestStream.Write(RequestBodyBytes, 0, RequestBodyBytes.Length); + requestStream.Write(this.RequestBodyBytes, 0, this.RequestBodyBytes.Length); } - else if (RequestBody != null) + else if (this.RequestBody != null) { - WriteStringTo(requestStream, RequestBody); + this.WriteStringTo(requestStream, this.RequestBody); } } } @@ -251,21 +247,19 @@ private void WriteRequestBody(HttpWebRequest webRequest) // TODO: duplication at the moment). private HttpWebRequest ConfigureWebRequest(string method, Uri url) { - var webRequest = (HttpWebRequest)WebRequest.Create(url); -#if !PocketPC - webRequest.UseDefaultCredentials = UseDefaultCredentials; -#endif - webRequest.PreAuthenticate = PreAuthenticate; + HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url); + webRequest.UseDefaultCredentials = this.UseDefaultCredentials; + webRequest.PreAuthenticate = this.PreAuthenticate; webRequest.ServicePoint.Expect100Continue = false; - AppendHeaders(webRequest); - AppendCookies(webRequest); + this.AppendHeaders(webRequest); + this.AppendCookies(webRequest); webRequest.Method = method; // make sure Content-Length header is always sent since default is -1 - if (!HasFiles && !AlwaysMultipartFormData) + if (!this.HasFiles && !this.AlwaysMultipartFormData) { webRequest.ContentLength = 0; } @@ -273,48 +267,49 @@ private HttpWebRequest ConfigureWebRequest(string method, Uri url) webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None; #if FRAMEWORK - if (ClientCertificates != null) + if (this.ClientCertificates != null) { - webRequest.ClientCertificates.AddRange(ClientCertificates); + webRequest.ClientCertificates.AddRange(this.ClientCertificates); } #endif - if (UserAgent.HasValue()) + if (this.UserAgent.HasValue()) { - webRequest.UserAgent = UserAgent; + webRequest.UserAgent = this.UserAgent; } - if (Timeout != 0) + if (this.Timeout != 0) { - webRequest.Timeout = Timeout; + webRequest.Timeout = this.Timeout; } - if (ReadWriteTimeout != 0) + if (this.ReadWriteTimeout != 0) { - webRequest.ReadWriteTimeout = ReadWriteTimeout; + webRequest.ReadWriteTimeout = this.ReadWriteTimeout; } - if (Credentials != null) + if (this.Credentials != null) { - webRequest.Credentials = Credentials; + webRequest.Credentials = this.Credentials; } - if (Proxy != null) + if (this.Proxy != null) { - webRequest.Proxy = Proxy; + webRequest.Proxy = this.Proxy; } #if FRAMEWORK - if (CachePolicy != null) + if (this.CachePolicy != null) { - webRequest.CachePolicy = CachePolicy; + webRequest.CachePolicy = this.CachePolicy; } #endif - webRequest.AllowAutoRedirect = FollowRedirects; - if (FollowRedirects && MaxRedirects.HasValue) + webRequest.AllowAutoRedirect = this.FollowRedirects; + + if (this.FollowRedirects && this.MaxRedirects.HasValue) { - webRequest.MaximumAutomaticRedirections = MaxRedirects.Value; + webRequest.MaximumAutomaticRedirections = this.MaxRedirects.Value; } return webRequest; diff --git a/RestSharp/Http.cs b/RestSharp/Http.cs index 2112802dd..30f138c0b 100644 --- a/RestSharp/Http.cs +++ b/RestSharp/Http.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -19,15 +21,17 @@ using System.IO; using System.Linq; using System.Net; -using System.Security.Cryptography.X509Certificates; using System.Text; using RestSharp.Extensions; #if WINDOWS_PHONE using RestSharp.Compression.ZLib; #endif + #if FRAMEWORK using System.Net.Cache; +using System.Security.Cryptography.X509Certificates; +using System.Text.RegularExpressions; #endif namespace RestSharp @@ -53,7 +57,7 @@ public IHttp Create() /// protected bool HasParameters { - get { return Parameters.Any(); } + get { return this.Parameters.Any(); } } /// @@ -61,7 +65,7 @@ protected bool HasParameters /// protected bool HasCookies { - get { return Cookies.Any(); } + get { return this.Cookies.Any(); } } /// @@ -69,7 +73,7 @@ protected bool HasCookies /// protected bool HasBody { - get { return RequestBodyBytes != null || !string.IsNullOrEmpty(RequestBody); } + get { return this.RequestBodyBytes != null || !string.IsNullOrEmpty(this.RequestBody); } } /// @@ -77,7 +81,7 @@ protected bool HasBody /// protected bool HasFiles { - get { return Files.Any(); } + get { return this.Files.Any(); } } /// @@ -105,12 +109,10 @@ protected bool HasFiles /// public ICredentials Credentials { get; set; } -#if !PocketPC /// /// The System.Net.CookieContainer to be used for the request /// public CookieContainer CookieContainer { get; set; } -#endif /// /// The method to use to write the response instead of reading into RawBytes @@ -134,25 +136,26 @@ protected bool HasFiles /// X509CertificateCollection to be sent with request /// public X509CertificateCollection ClientCertificates { get; set; } -#endif -#if FRAMEWORK || PocketPC /// /// Maximum number of automatic redirects to follow if FollowRedirects is true /// public int? MaxRedirects { get; set; } #endif -#if !PocketPC /// /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) /// will be sent along to the server. /// public bool UseDefaultCredentials { get; set; } -#endif + private Encoding encoding = Encoding.UTF8; - public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } } + public Encoding Encoding + { + get { return this.encoding; } + set { this.encoding = value; } + } /// /// HTTP headers to be sent with request @@ -194,14 +197,12 @@ protected bool HasFiles /// public bool PreAuthenticate { get; set; } -#if FRAMEWORK || PocketPC +#if FRAMEWORK /// /// Proxy info to be sent with request /// public IWebProxy Proxy { get; set; } -#endif -#if FRAMEWORK /// /// Caching policy for requests created with this wrapper. /// @@ -217,8 +218,8 @@ public Http() this.Files = new List(); this.Parameters = new List(); this.Cookies = new List(); - - restrictedHeaderActions = new Dictionary>(StringComparer.OrdinalIgnoreCase); + this.restrictedHeaderActions = new Dictionary>( + StringComparer.OrdinalIgnoreCase); this.AddSharedHeaderActions(); this.AddSyncHeaderActions(); @@ -226,31 +227,33 @@ public Http() partial void AddSyncHeaderActions(); +#if SILVERLIGHT || WINDOWS_PHONE partial void AddAsyncHeaderActions(); +#endif private void AddSharedHeaderActions() { - restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v); - restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v); + this.restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v); + this.restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v); #if NET4 restrictedHeaderActions.Add("Date", (r, v) => - { - DateTime parsed; + { + DateTime parsed; - if (DateTime.TryParse(v, out parsed)) - { - r.Date = parsed; - } - }); + if (DateTime.TryParse(v, out parsed)) + { + r.Date = parsed; + } + }); restrictedHeaderActions.Add("Host", (r, v) => r.Host = v); #else - restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ }); - restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ }); + this.restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ }); + this.restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ }); #endif #if FRAMEWORK - restrictedHeaderActions.Add("Range", AddRange); + this.restrictedHeaderActions.Add("Range", AddRange); #endif } @@ -263,13 +266,14 @@ private static string GetMultipartFormContentType() private static string GetMultipartFileHeader(HttpFile file) { - return string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}", + return string.Format( + "--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}", FORM_BOUNDARY, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK); } private string GetMultipartFormData(HttpParameter param) { - string format = param.Name == RequestContentType + string format = param.Name == this.RequestContentType ? "--{0}{3}Content-Type: {4}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}" : "--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}"; @@ -287,11 +291,11 @@ private static string GetMultipartFooter() // http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx private void AppendHeaders(HttpWebRequest webRequest) { - foreach (var header in Headers) + foreach (HttpHeader header in this.Headers) { - if (restrictedHeaderActions.ContainsKey(header.Name)) + if (this.restrictedHeaderActions.ContainsKey(header.Name)) { - restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value); + this.restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value); } else { @@ -306,44 +310,42 @@ private void AppendHeaders(HttpWebRequest webRequest) private void AppendCookies(HttpWebRequest webRequest) { -#if !PocketPC webRequest.CookieContainer = this.CookieContainer ?? new CookieContainer(); -#endif - foreach (var httpCookie in Cookies) + + foreach (HttpCookie httpCookie in this.Cookies) { -#if !PocketPC #if FRAMEWORK - var cookie = new Cookie - { - Name = httpCookie.Name, - Value = httpCookie.Value, - Domain = webRequest.RequestUri.Host - }; + Cookie cookie = new Cookie + { + Name = httpCookie.Name, + Value = httpCookie.Value, + Domain = webRequest.RequestUri.Host + }; webRequest.CookieContainer.Add(cookie); #else - var cookie = new Cookie - { - Name = httpCookie.Name, - Value = httpCookie.Value - }; - - var uri = webRequest.RequestUri; + Cookie cookie = new Cookie + { + Name = httpCookie.Name, + Value = httpCookie.Value + }; + Uri uri = webRequest.RequestUri; webRequest.CookieContainer.Add(new Uri(string.Format("{0}://{1}", uri.Scheme, uri.Host)), cookie); -#endif #endif } } private string EncodeParameters() { - var querystring = new StringBuilder(); + StringBuilder querystring = new StringBuilder(); - foreach (var p in Parameters) + foreach (HttpParameter p in this.Parameters) { if (querystring.Length > 1) + { querystring.Append("&"); + } querystring.AppendFormat("{0}={1}", p.Name.UrlEncode(), p.Value.UrlEncode()); } @@ -353,45 +355,46 @@ private string EncodeParameters() private void PreparePostBody(HttpWebRequest webRequest) { - if (HasFiles || AlwaysMultipartFormData) + if (this.HasFiles || this.AlwaysMultipartFormData) { webRequest.ContentType = GetMultipartFormContentType(); } - else if (HasParameters) + else if (this.HasParameters) { webRequest.ContentType = "application/x-www-form-urlencoded"; - RequestBody = EncodeParameters(); + this.RequestBody = this.EncodeParameters(); } - else if (HasBody) + else if (this.HasBody) { - webRequest.ContentType = RequestContentType; + webRequest.ContentType = this.RequestContentType; } } private void WriteStringTo(Stream stream, string toWrite) { - var bytes = this.Encoding.GetBytes(toWrite); + byte[] bytes = this.Encoding.GetBytes(toWrite); + stream.Write(bytes, 0, bytes.Length); } private void WriteMultipartFormData(Stream requestStream) { - foreach (var param in Parameters) + foreach (HttpParameter param in this.Parameters) { - WriteStringTo(requestStream, GetMultipartFormData(param)); + this.WriteStringTo(requestStream, this.GetMultipartFormData(param)); } - foreach (var file in Files) + foreach (HttpFile file in this.Files) { // Add just the first part of this param, since we will write the file data directly to the Stream - WriteStringTo(requestStream, GetMultipartFileHeader(file)); + this.WriteStringTo(requestStream, GetMultipartFileHeader(file)); // Write the file data directly to the Stream, rather than serializing it to a string. file.Writer(requestStream); - WriteStringTo(requestStream, LINE_BREAK); + this.WriteStringTo(requestStream, LINE_BREAK); } - WriteStringTo(requestStream, GetMultipartFooter()); + this.WriteStringTo(requestStream, GetMultipartFooter()); } private void ExtractResponseData(HttpResponse response, HttpWebResponse webResponse) @@ -404,12 +407,14 @@ private void ExtractResponseData(HttpResponse response, HttpWebResponse webRespo #endif response.ContentType = webResponse.ContentType; response.ContentLength = webResponse.ContentLength; + Stream webResponseStream = webResponse.GetResponseStream(); #if WINDOWS_PHONE - if (String.Equals(webResponse.Headers[HttpRequestHeader.ContentEncoding], "gzip", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(webResponse.Headers[HttpRequestHeader.ContentEncoding], "gzip", StringComparison.OrdinalIgnoreCase)) { - var gzStream = new GZipStream(webResponseStream); + GZipStream gzStream = new GZipStream(webResponseStream); + ProcessResponseStream(gzStream, response); } else @@ -417,42 +422,47 @@ private void ExtractResponseData(HttpResponse response, HttpWebResponse webRespo ProcessResponseStream(webResponseStream, response); } #else - ProcessResponseStream(webResponseStream, response); + this.ProcessResponseStream(webResponseStream, response); #endif + response.StatusCode = webResponse.StatusCode; response.StatusDescription = webResponse.StatusDescription; response.ResponseUri = webResponse.ResponseUri; response.ResponseStatus = ResponseStatus.Completed; -#if !PocketPC if (webResponse.Cookies != null) { foreach (Cookie cookie in webResponse.Cookies) { response.Cookies.Add(new HttpCookie - { - Comment = cookie.Comment, - CommentUri = cookie.CommentUri, - Discard = cookie.Discard, - Domain = cookie.Domain, - Expired = cookie.Expired, - Expires = cookie.Expires, - HttpOnly = cookie.HttpOnly, - Name = cookie.Name, - Path = cookie.Path, - Port = cookie.Port, - Secure = cookie.Secure, - TimeStamp = cookie.TimeStamp, - Value = cookie.Value, - Version = cookie.Version - }); + { + Comment = cookie.Comment, + CommentUri = cookie.CommentUri, + Discard = cookie.Discard, + Domain = cookie.Domain, + Expired = cookie.Expired, + Expires = cookie.Expires, + HttpOnly = cookie.HttpOnly, + Name = cookie.Name, + Path = cookie.Path, + Port = cookie.Port, + Secure = cookie.Secure, + TimeStamp = cookie.TimeStamp, + Value = cookie.Value, + Version = cookie.Version + }); } } -#endif - foreach (var headerName in webResponse.Headers.AllKeys) + + foreach (string headerName in webResponse.Headers.AllKeys) { - var headerValue = webResponse.Headers[headerName]; - response.Headers.Add(new HttpHeader { Name = headerName, Value = headerValue }); + string headerValue = webResponse.Headers[headerName]; + + response.Headers.Add(new HttpHeader + { + Name = headerName, + Value = headerValue + }); } webResponse.Close(); @@ -461,20 +471,20 @@ private void ExtractResponseData(HttpResponse response, HttpWebResponse webRespo private void ProcessResponseStream(Stream webResponseStream, HttpResponse response) { - if (ResponseWriter == null) + if (this.ResponseWriter == null) { response.RawBytes = webResponseStream.ReadAsBytes(); } else { - ResponseWriter(webResponseStream); + this.ResponseWriter(webResponseStream); } } #if FRAMEWORK - private void AddRange(HttpWebRequest r, string range) + private static void AddRange(HttpWebRequest r, string range) { - System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(range, "(\\w+)=(\\d+)-(\\d+)$"); + Match m = Regex.Match(range, "(\\w+)=(\\d+)-(\\d+)$"); if (!m.Success) { diff --git a/RestSharp/HttpHeader.cs b/RestSharp/HttpHeader.cs index 6ad0786e2..6544aea32 100644 --- a/RestSharp/HttpHeader.cs +++ b/RestSharp/HttpHeader.cs @@ -1,5 +1,4 @@ - -namespace RestSharp +namespace RestSharp { /// /// Representation of an HTTP header diff --git a/RestSharp/HttpParameter.cs b/RestSharp/HttpParameter.cs index c65c268a7..735073411 100644 --- a/RestSharp/HttpParameter.cs +++ b/RestSharp/HttpParameter.cs @@ -1,5 +1,4 @@ - -namespace RestSharp +namespace RestSharp { /// /// Representation of an HTTP parameter (QueryString or Form value) diff --git a/RestSharp/HttpResponse.cs b/RestSharp/HttpResponse.cs index 98c3d54a9..bce4e376e 100644 --- a/RestSharp/HttpResponse.cs +++ b/RestSharp/HttpResponse.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -26,15 +28,16 @@ namespace RestSharp /// public class HttpResponse : IHttpResponse { - private string _content; + private string content; /// /// Default constructor /// public HttpResponse() { - Headers = new List(); - Cookies = new List(); + this.ResponseStatus = ResponseStatus.None; + this.Headers = new List(); + this.Cookies = new List(); } /// @@ -57,8 +60,9 @@ public HttpResponse() /// public string Content { - get { return _content ?? (_content = RawBytes.AsString()); } + get { return this.content ?? (this.content = this.RawBytes.AsString()); } } + /// /// HTTP response status code /// @@ -94,17 +98,11 @@ public string Content /// public IList Cookies { get; private set; } - private ResponseStatus _responseStatus = ResponseStatus.None; - /// /// Status of the request. Will return Error for transport errors. /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead /// - public ResponseStatus ResponseStatus - { - get { return _responseStatus; } - set { _responseStatus = value; } - } + public ResponseStatus ResponseStatus { get; set; } /// /// Transport or other non-HTTP error generated while attempting request diff --git a/RestSharp/IHttp.cs b/RestSharp/IHttp.cs index fd249122c..75e967585 100644 --- a/RestSharp/IHttp.cs +++ b/RestSharp/IHttp.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,17 +13,18 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Collections.Generic; using System.IO; using System.Net; -using System.Security.Cryptography.X509Certificates; using System.Text; #if FRAMEWORK using System.Net.Cache; +using System.Security.Cryptography.X509Certificates; #endif namespace RestSharp @@ -31,9 +33,7 @@ public interface IHttp { Action ResponseWriter { get; set; } -#if !PocketPC CookieContainer CookieContainer { get; set; } -#endif ICredentials Credentials { get; set; } @@ -58,9 +58,7 @@ public interface IHttp int? MaxRedirects { get; set; } #endif -#if !PocketPC bool UseDefaultCredentials { get; set; } -#endif Encoding Encoding { get; set; } @@ -109,7 +107,7 @@ public interface IHttp HttpWebRequest AsGetAsync(Action action, string httpMethod); -#if FRAMEWORK || PocketPC +#if FRAMEWORK HttpResponse Delete(); HttpResponse Get(); diff --git a/RestSharp/IHttpFactory.cs b/RestSharp/IHttpFactory.cs index 98e586836..b49a64967 100644 --- a/RestSharp/IHttpFactory.cs +++ b/RestSharp/IHttpFactory.cs @@ -1,11 +1,13 @@ -namespace RestSharp + +namespace RestSharp { public interface IHttpFactory { IHttp Create(); } - public class SimpleFactory : IHttpFactory where T : IHttp, new() + public class SimpleFactory : IHttpFactory + where T : IHttp, new() { public IHttp Create() { diff --git a/RestSharp/IRestClient.cs b/RestSharp/IRestClient.cs index 8fab9bbc6..1b200e506 100644 --- a/RestSharp/IRestClient.cs +++ b/RestSharp/IRestClient.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,30 +13,32 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Net; using System.Collections.Generic; -using System.Security.Cryptography.X509Certificates; using System.Text; +using RestSharp.Authenticators; using RestSharp.Deserializers; #if NET4 || MONODROID || MONOTOUCH || WP8 using System.Threading; using System.Threading.Tasks; #endif + #if FRAMEWORK using System.Net.Cache; +using System.Security.Cryptography.X509Certificates; #endif namespace RestSharp { public interface IRestClient { -#if !PocketPC CookieContainer CookieContainer { get; set; } -#endif + int? MaxRedirects { get; set; } string UserAgent { get; set; } @@ -60,7 +63,7 @@ public interface IRestClient RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action, RestRequestAsyncHandle> callback); -#if FRAMEWORK || PocketPC +#if FRAMEWORK IRestResponse Execute(IRestRequest request); IRestResponse Execute(IRestRequest request) where T : new(); @@ -89,7 +92,8 @@ public interface IRestClient /// Request to be executed /// Callback function to be executed upon completion providing access to the async handle. /// The HTTP method to execute - RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action callback, string httpMethod); + RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action callback, string httpMethod); /// /// Executes a POST-style request and callback asynchronously, authenticating if needed @@ -97,7 +101,8 @@ public interface IRestClient /// Request to be executed /// Callback function to be executed upon completion providing access to the async handle. /// The HTTP method to execute - RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action callback, string httpMethod); + RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action callback, string httpMethod); /// /// Executes a GET-style request and callback asynchronously, authenticating if needed @@ -106,7 +111,8 @@ public interface IRestClient /// Request to be executed /// Callback function to be executed upon completion /// The HTTP method to execute - RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action, RestRequestAsyncHandle> callback, string httpMethod); + RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action, + RestRequestAsyncHandle> callback, string httpMethod); /// /// Executes a GET-style request and callback asynchronously, authenticating if needed @@ -115,7 +121,8 @@ public interface IRestClient /// Request to be executed /// Callback function to be executed upon completion /// The HTTP method to execute - RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action, RestRequestAsyncHandle> callback, string httpMethod); + RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action, + RestRequestAsyncHandle> callback, string httpMethod); void AddHandler(string contentType, IDeserializer deserializer); diff --git a/RestSharp/IRestRequest.cs b/RestSharp/IRestRequest.cs index 7d79444af..2d0b0c88d 100644 --- a/RestSharp/IRestRequest.cs +++ b/RestSharp/IRestRequest.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; diff --git a/RestSharp/Parameter.cs b/RestSharp/Parameter.cs index 0a0f82422..9e7c932ad 100644 --- a/RestSharp/Parameter.cs +++ b/RestSharp/Parameter.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion namespace RestSharp @@ -47,7 +49,7 @@ public class Parameter /// String public override string ToString() { - return string.Format("{0}={1}", Name, Value); + return string.Format("{0}={1}", this.Name, this.Value); } } } diff --git a/RestSharp/Properties/AssemblyInfo.cs b/RestSharp/Properties/AssemblyInfo.cs index ca865fde0..89c28dc18 100644 --- a/RestSharp/Properties/AssemblyInfo.cs +++ b/RestSharp/Properties/AssemblyInfo.cs @@ -5,20 +5,24 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("RestSharp")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. + [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("d2b12a34-b748-47f9-8ad6-f84da992c64b")] #if SIGNED [assembly: InternalsVisibleTo("RestSharp.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d"), InternalsVisibleTo("RestSharp.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d")] #else + [assembly: InternalsVisibleTo("RestSharp.IntegrationTests"), InternalsVisibleTo("RestSharp.Tests")] #endif diff --git a/RestSharp/RestClient.Async.cs b/RestSharp/RestClient.Async.cs index afdf7456f..911ff1969 100644 --- a/RestSharp/RestClient.Async.cs +++ b/RestSharp/RestClient.Async.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,17 +13,17 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Threading; +using System.Net; #if NET4 || MONODROID || MONOTOUCH || WP8 using System.Threading.Tasks; #endif -using System.Net; - namespace RestSharp { public partial class RestClient @@ -35,11 +36,7 @@ public partial class RestClient public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action callback) { -#if PocketPC - string method = request.Method.ToString(); -#else string method = Enum.GetName(typeof(Method), request.Method); -#endif switch (request.Method) { @@ -83,44 +80,41 @@ private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action callback, string httpMethod, Func, string, HttpWebRequest> getWebRequest) { - var http = this.HttpFactory.Create(); + IHttp http = this.HttpFactory.Create(); this.AuthenticateIfNeeded(this, request); - this.ConfigureHttp(request, http); - var asyncHandle = new RestRequestAsyncHandle(); - - Action response_cb = r => this.ProcessResponse(request, r, asyncHandle, callback); + RestRequestAsyncHandle asyncHandle = new RestRequestAsyncHandle(); + Action responseCb = r => ProcessResponse(request, r, asyncHandle, callback); -#if !PocketPC if (this.UseSynchronizationContext && SynchronizationContext.Current != null) { - var ctx = SynchronizationContext.Current; - var cb = response_cb; + SynchronizationContext ctx = SynchronizationContext.Current; + Action cb = responseCb; - response_cb = resp => ctx.Post(s => cb(resp), null); + responseCb = resp => ctx.Post(s => cb(resp), null); } -#endif - asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod); + asyncHandle.WebRequest = getWebRequest(http, responseCb, httpMethod); + return asyncHandle; } - private static HttpWebRequest DoAsGetAsync(IHttp http, Action response_cb, string method) + private static HttpWebRequest DoAsGetAsync(IHttp http, Action responseCb, string method) { - return http.AsGetAsync(response_cb, method); + return http.AsGetAsync(responseCb, method); } - private static HttpWebRequest DoAsPostAsync(IHttp http, Action response_cb, string method) + private static HttpWebRequest DoAsPostAsync(IHttp http, Action responseCb, string method) { - return http.AsPostAsync(response_cb, method); + return http.AsPostAsync(responseCb, method); } - private void ProcessResponse(IRestRequest request, HttpResponse httpResponse, RestRequestAsyncHandle asyncHandle, - Action callback) + private static void ProcessResponse(IRestRequest request, HttpResponse httpResponse, + RestRequestAsyncHandle asyncHandle, Action callback) { - var restResponse = ConvertToRestResponse(request, httpResponse); + RestResponse restResponse = ConvertToRestResponse(request, httpResponse); callback(restResponse, asyncHandle); } @@ -165,9 +159,8 @@ public virtual RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, (response, asyncHandle) => this.DeserializeResponse(request, callback, response, asyncHandle), httpMethod); } - private void DeserializeResponse(IRestRequest request, - Action, RestRequestAsyncHandle> callback, IRestResponse response, - RestRequestAsyncHandle asyncHandle) + private void DeserializeResponse(IRestRequest request, Action, + RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle) { IRestResponse restResponse; @@ -178,12 +171,12 @@ private void DeserializeResponse(IRestRequest request, catch (Exception ex) { restResponse = new RestResponse - { - Request = request, - ResponseStatus = ResponseStatus.Error, - ErrorMessage = ex.Message, - ErrorException = ex - }; + { + Request = request, + ResponseStatus = ResponseStatus.Error, + ErrorMessage = ex.Message, + ErrorException = ex + }; } callback(restResponse, asyncHandle); @@ -214,6 +207,7 @@ public virtual Task> ExecuteGetTaskAsync(IRestRequest reques } request.Method = Method.GET; + return this.ExecuteTaskAsync(request, token); } @@ -241,6 +235,7 @@ public virtual Task> ExecutePostTaskAsync(IRestRequest reque } request.Method = Method.POST; + return this.ExecuteTaskAsync(request, token); } @@ -267,28 +262,34 @@ public virtual Task> ExecuteTaskAsync(IRestRequest request, throw new ArgumentNullException("request"); } - var taskCompletionSource = new TaskCompletionSource>(); + TaskCompletionSource> taskCompletionSource = new TaskCompletionSource>(); try { - var async = this.ExecuteAsync(request, (response, _) => + RestRequestAsyncHandle async = this.ExecuteAsync( + request, + (response, _) => { if (token.IsCancellationRequested) { taskCompletionSource.TrySetCanceled(); } - //Don't run TrySetException, since we should set Error properties and swallow exceptions to be consistent with sync methods + // Don't run TrySetException, since we should set Error properties and swallow exceptions + // to be consistent with sync methods else { taskCompletionSource.TrySetResult(response); } }); - var registration = token.Register(() => - { - async.Abort(); - taskCompletionSource.TrySetCanceled(); - }); +#if !WINDOWS_PHONE + CancellationTokenRegistration registration = +#endif + token.Register(() => + { + async.Abort(); + taskCompletionSource.TrySetCanceled(); + }); #if !WINDOWS_PHONE taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token); @@ -333,6 +334,7 @@ public virtual Task ExecuteGetTaskAsync(IRestRequest request, Can } request.Method = Method.GET; + return this.ExecuteTaskAsync(request, token); } @@ -358,6 +360,7 @@ public virtual Task ExecutePostTaskAsync(IRestRequest request, Ca } request.Method = Method.POST; + return this.ExecuteTaskAsync(request, token); } @@ -373,28 +376,35 @@ public virtual Task ExecuteTaskAsync(IRestRequest request, Cancel throw new ArgumentNullException("request"); } - var taskCompletionSource = new TaskCompletionSource(); + TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); try { - var async = this.ExecuteAsync(request, (response, _) => + RestRequestAsyncHandle async = this.ExecuteAsync( + request, + (response, _) => { if (token.IsCancellationRequested) { taskCompletionSource.TrySetCanceled(); } - //Don't run TrySetException, since we should set Error properties and swallow exceptions to be consistent with sync methods + // Don't run TrySetException, since we should set Error + // properties and swallow exceptions to be consistent + // with sync methods else { taskCompletionSource.TrySetResult(response); } }); - var registration = token.Register(() => - { - async.Abort(); - taskCompletionSource.TrySetCanceled(); - }); +#if !WINDOWS_PHONE + CancellationTokenRegistration registration = +#endif + token.Register(() => + { + async.Abort(); + taskCompletionSource.TrySetCanceled(); + }); #if !WINDOWS_PHONE taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token); diff --git a/RestSharp/RestClient.Sync.cs b/RestSharp/RestClient.Sync.cs index 6c1d756aa..dedaca6e6 100644 --- a/RestSharp/RestClient.Sync.cs +++ b/RestSharp/RestClient.Sync.cs @@ -1,4 +1,5 @@ -#if FRAMEWORK || PocketPC +#if FRAMEWORK + using System; namespace RestSharp @@ -12,7 +13,8 @@ public partial class RestClient /// Response data public byte[] DownloadData(IRestRequest request) { - var response = Execute(request); + IRestResponse response = this.Execute(request); + return response.RawBytes; } @@ -23,52 +25,49 @@ public byte[] DownloadData(IRestRequest request) /// RestResponse public virtual IRestResponse Execute(IRestRequest request) { -#if PocketPC - var method = request.Method.ToString(); -#else - var method = Enum.GetName(typeof (Method), request.Method); -#endif + string method = Enum.GetName(typeof(Method), request.Method); + switch (request.Method) { case Method.POST: case Method.PUT: case Method.PATCH: case Method.MERGE: - return Execute(request, method, DoExecuteAsPost); + return this.Execute(request, method, DoExecuteAsPost); default: - return Execute(request, method, DoExecuteAsGet); + return this.Execute(request, method, DoExecuteAsGet); } } public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) { - return Execute(request, httpMethod, DoExecuteAsGet); + return this.Execute(request, httpMethod, DoExecuteAsGet); } public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) { request.Method = Method.POST; // Required by RestClient.BuildUri... - return Execute(request, httpMethod, DoExecuteAsPost); + + return this.Execute(request, httpMethod, DoExecuteAsPost); } private IRestResponse Execute(IRestRequest request, string httpMethod, Func getResponse) { - AuthenticateIfNeeded(this, request); + this.AuthenticateIfNeeded(this, request); IRestResponse response = new RestResponse(); try { - var http = HttpFactory.Create(); + IHttp http = this.HttpFactory.Create(); - ConfigureHttp(request, http); + this.ConfigureHttp(request, http); response = ConvertToRestResponse(request, getResponse(http, httpMethod)); response.Request = request; response.Request.IncreaseNumAttempts(); - } catch (Exception ex) { @@ -98,17 +97,17 @@ private static HttpResponse DoExecuteAsPost(IHttp http, string method) /// RestResponse[[T]] with deserialized data in Data property public virtual IRestResponse Execute(IRestRequest request) where T : new() { - return Deserialize(request, Execute(request)); + return this.Deserialize(request, this.Execute(request)); } public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) where T : new() { - return Deserialize(request, ExecuteAsGet(request, httpMethod)); + return this.Deserialize(request, this.ExecuteAsGet(request, httpMethod)); } public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) where T : new() { - return Deserialize(request, ExecuteAsPost(request, httpMethod)); + return this.Deserialize(request, this.ExecuteAsPost(request, httpMethod)); } } } diff --git a/RestSharp/RestClient.cs b/RestSharp/RestClient.cs index 8376d36d9..7b33c730e 100644 --- a/RestSharp/RestClient.cs +++ b/RestSharp/RestClient.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -19,14 +21,15 @@ using System.Linq; using System.Net; using System.Reflection; -using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; +using RestSharp.Authenticators; using RestSharp.Deserializers; using RestSharp.Extensions; #if FRAMEWORK using System.Net.Cache; +using System.Security.Cryptography.X509Certificates; #endif namespace RestSharp @@ -37,13 +40,9 @@ namespace RestSharp public partial class RestClient : IRestClient { // silverlight friendly way to get current version -#if PocketPC - static readonly Version version = Assembly.GetExecutingAssembly().GetName().Version; -#else private static readonly Version version = new AssemblyName(Assembly.GetExecutingAssembly().FullName).Version; -#endif - public IHttpFactory HttpFactory = new SimpleFactory(); + public IHttpFactory HttpFactory = new SimpleFactory(); /// /// Maximum number of redirects to follow if FollowRedirects is true @@ -74,12 +73,10 @@ public partial class RestClient : IRestClient /// public bool FollowRedirects { get; set; } -#if !PocketPC /// /// The CookieContainer used for requests made by this client instance /// public CookieContainer CookieContainer { get; set; } -#endif /// /// UserAgent to use for requests made by this client instance @@ -115,9 +112,7 @@ public partial class RestClient : IRestClient /// public virtual Uri BaseUrl { get; set; } - private Encoding encoding = Encoding.UTF8; - - public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } } + public Encoding Encoding { get; set; } public bool PreAuthenticate { get; set; } @@ -126,6 +121,7 @@ public partial class RestClient : IRestClient /// public RestClient() { + this.Encoding = Encoding.UTF8; #if WINDOWS_PHONE this.UseSynchronizationContext = true; #endif @@ -162,8 +158,10 @@ public RestClient(Uri baseUrl) : this() /// public RestClient(string baseUrl) : this() { - if (String.IsNullOrEmpty(baseUrl)) + if (string.IsNullOrEmpty(baseUrl)) + { throw new ArgumentNullException("baseUrl"); + } this.BaseUrl = new Uri(baseUrl); } @@ -187,11 +185,11 @@ public void AddHandler(string contentType, IDeserializer deserializer) { this.ContentHandlers[contentType] = deserializer; - if (contentType != "*" && !structuredSyntaxSuffixWildcardRegex.IsMatch(contentType)) + if (contentType != "*" && !this.structuredSyntaxSuffixWildcardRegex.IsMatch(contentType)) { this.AcceptTypes.Add(contentType); // add Accept header based on registered deserializers - var accepts = string.Join(", ", AcceptTypes.ToArray()); + string accepts = string.Join(", ", this.AcceptTypes.ToArray()); this.RemoveDefaultParameter("Accept"); this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader); @@ -227,49 +225,61 @@ public void ClearHandlers() private IDeserializer GetHandler(string contentType) { if (contentType == null) + { throw new ArgumentNullException("contentType"); + } if (string.IsNullOrEmpty(contentType) && this.ContentHandlers.ContainsKey("*")) { - return ContentHandlers["*"]; + return this.ContentHandlers["*"]; } - var semicolonIndex = contentType.IndexOf(';'); + int semicolonIndex = contentType.IndexOf(';'); if (semicolonIndex > -1) + { contentType = contentType.Substring(0, semicolonIndex); + } if (this.ContentHandlers.ContainsKey(contentType)) + { return this.ContentHandlers[contentType]; + } // https://tools.ietf.org/html/rfc6839#page-4 - Match structuredSyntaxSuffixMatch = structuredSyntaxSuffixRegex.Match(contentType); + Match structuredSyntaxSuffixMatch = this.structuredSyntaxSuffixRegex.Match(contentType); if (structuredSyntaxSuffixMatch.Success) { string structuredSyntaxSuffixWildcard = "*" + structuredSyntaxSuffixMatch.Value; if (this.ContentHandlers.ContainsKey(structuredSyntaxSuffixWildcard)) + { return this.ContentHandlers[structuredSyntaxSuffixWildcard]; + } } if (this.ContentHandlers.ContainsKey("*")) + { return this.ContentHandlers["*"]; + } return null; } #if SILVERLIGHT private readonly Regex structuredSyntaxSuffixRegex = new Regex(@"\+\w+$"); + private readonly Regex structuredSyntaxSuffixWildcardRegex = new Regex(@"^\*\+\w+$"); #else private readonly Regex structuredSyntaxSuffixRegex = new Regex(@"\+\w+$", RegexOptions.Compiled); + private readonly Regex structuredSyntaxSuffixWildcardRegex = new Regex(@"^\*\+\w+$", RegexOptions.Compiled); #endif private void AuthenticateIfNeeded(RestClient client, IRestRequest request) { - if (Authenticator != null) + if (this.Authenticator != null) { this.Authenticator.Authenticate(client, request); } @@ -283,13 +293,15 @@ private void AuthenticateIfNeeded(RestClient client, IRestRequest request) public Uri BuildUri(IRestRequest request) { if (this.BaseUrl == null) + { throw new NullReferenceException("RestClient must contain a value for BaseUrl"); + } - var assembled = request.Resource; - var urlParms = request.Parameters.Where(p => p.Type == ParameterType.UrlSegment); - var builder = new UriBuilder(this.BaseUrl); + string assembled = request.Resource; + IEnumerable urlParms = request.Parameters.Where(p => p.Type == ParameterType.UrlSegment); + UriBuilder builder = new UriBuilder(this.BaseUrl); - foreach (var p in urlParms) + foreach (Parameter p in urlParms) { if (p.Value == null) { @@ -299,7 +311,9 @@ public Uri BuildUri(IRestRequest request) } if (!string.IsNullOrEmpty(assembled)) + { assembled = assembled.Replace("{" + p.Name + "}", p.Value.ToString().UrlEncode()); + } builder.Path = builder.Path.UrlDecode().Replace("{" + p.Name + "}", p.Value.ToString().UrlEncode()); } @@ -314,7 +328,9 @@ public Uri BuildUri(IRestRequest request) if (this.BaseUrl != null && !string.IsNullOrEmpty(this.BaseUrl.AbsoluteUri)) { if (!this.BaseUrl.AbsoluteUri.EndsWith("/") && !string.IsNullOrEmpty(assembled)) + { assembled = string.Concat("/", assembled); + } assembled = string.IsNullOrEmpty(assembled) ? this.BaseUrl.AbsoluteUri @@ -325,20 +341,28 @@ public Uri BuildUri(IRestRequest request) if (request.Method != Method.POST && request.Method != Method.PUT && request.Method != Method.PATCH) { - parameters = request.Parameters.Where( - p => p.Type == ParameterType.GetOrPost || p.Type == ParameterType.QueryString).ToList(); + parameters = request.Parameters + .Where(p => p.Type == ParameterType.GetOrPost || + p.Type == ParameterType.QueryString) + .ToList(); } else { - parameters = request.Parameters.Where(p => p.Type == ParameterType.QueryString).ToList(); + parameters = request.Parameters + .Where(p => p.Type == ParameterType.QueryString) + .ToList(); } if (!parameters.Any()) + { return new Uri(assembled); + } // build and attach querystring - var data = EncodeParameters(parameters); - var separator = assembled.Contains("?") ? "&" : "?"; + string data = EncodeParameters(parameters); + string separator = assembled != null && assembled.Contains("?") + ? "&" + : "?"; assembled = string.Concat(assembled, separator, data); @@ -347,11 +371,8 @@ public Uri BuildUri(IRestRequest request) private static string EncodeParameters(IEnumerable parameters) { -#if !PocketPC - return string.Join("&", parameters.Select(EncodeParameter).ToArray()); -#else - return string.Join("&", parameters.Select(x => EncodeParameter(x)).ToArray()); -#endif + return string.Join("&", parameters.Select(EncodeParameter) + .ToArray()); } private static string EncodeParameter(Parameter parameter) @@ -365,15 +386,12 @@ private void ConfigureHttp(IRestRequest request, IHttp http) { http.Encoding = this.Encoding; http.AlwaysMultipartFormData = request.AlwaysMultipartFormData; -#if !PocketPC http.UseDefaultCredentials = request.UseDefaultCredentials; -#endif http.ResponseWriter = request.ResponseWriter; -#if !PocketPC - http.CookieContainer = CookieContainer; -#endif + http.CookieContainer = this.CookieContainer; + // move RestClient.DefaultParameters into Request.Parameters - foreach (var p in DefaultParameters) + foreach (Parameter p in this.DefaultParameters) { if (request.Parameters.Any(p2 => p2.Name == p.Name && p2.Type == p.Type)) { @@ -384,31 +402,34 @@ private void ConfigureHttp(IRestRequest request, IHttp http) } // Add Accept header based on registered deserializers if none has been set by the caller. -#if PocketPC - if (request.Parameters.All(p2 => p2.Name.ToLower() != "accept")) -#else if (request.Parameters.All(p2 => p2.Name.ToLowerInvariant() != "accept")) -#endif { - var accepts = string.Join(", ", AcceptTypes.ToArray()); + string accepts = string.Join(", ", this.AcceptTypes.ToArray()); + request.AddParameter("Accept", accepts, ParameterType.HttpHeader); } - http.Url = BuildUri(request); + http.Url = this.BuildUri(request); http.PreAuthenticate = this.PreAuthenticate; - var userAgent = UserAgent ?? http.UserAgent; + string userAgent = this.UserAgent ?? http.UserAgent; - http.UserAgent = userAgent.HasValue() ? userAgent : "RestSharp/" + version; + http.UserAgent = userAgent.HasValue() + ? userAgent + : "RestSharp/" + version; - var timeout = request.Timeout > 0 ? request.Timeout : Timeout; + int timeout = request.Timeout > 0 + ? request.Timeout + : this.Timeout; if (timeout > 0) { http.Timeout = timeout; } - var readWriteTimeout = request.ReadWriteTimeout > 0 ? request.ReadWriteTimeout : ReadWriteTimeout; + int readWriteTimeout = request.ReadWriteTimeout > 0 + ? request.ReadWriteTimeout + : this.ReadWriteTimeout; if (readWriteTimeout > 0) { @@ -416,18 +437,17 @@ private void ConfigureHttp(IRestRequest request, IHttp http) } #if !SILVERLIGHT - http.FollowRedirects = FollowRedirects; + http.FollowRedirects = this.FollowRedirects; #endif #if FRAMEWORK - if (ClientCertificates != null) + if (this.ClientCertificates != null) { http.ClientCertificates = this.ClientCertificates; } - http.MaxRedirects = MaxRedirects; - - http.CachePolicy = CachePolicy; + http.MaxRedirects = this.MaxRedirects; + http.CachePolicy = this.CachePolicy; #endif if (request.Credentials != null) @@ -435,47 +455,46 @@ private void ConfigureHttp(IRestRequest request, IHttp http) http.Credentials = request.Credentials; } - var headers = from p in request.Parameters - where p.Type == ParameterType.HttpHeader - select new HttpHeader - { - Name = p.Name, - Value = Convert.ToString(p.Value) - }; + IEnumerable headers = from p in request.Parameters + where p.Type == ParameterType.HttpHeader + select new HttpHeader + { + Name = p.Name, + Value = Convert.ToString(p.Value) + }; - foreach (var header in headers) + foreach (HttpHeader header in headers) { http.Headers.Add(header); } - var cookies = from p in request.Parameters - where p.Type == ParameterType.Cookie - select new HttpCookie - { - Name = p.Name, - Value = Convert.ToString(p.Value) - }; + IEnumerable cookies = from p in request.Parameters + where p.Type == ParameterType.Cookie + select new HttpCookie + { + Name = p.Name, + Value = Convert.ToString(p.Value) + }; - foreach (var cookie in cookies) + foreach (HttpCookie cookie in cookies) { http.Cookies.Add(cookie); } - var @params = from p in request.Parameters - where p.Type == ParameterType.GetOrPost - && p.Value != null - select new HttpParameter - { - Name = p.Name, - Value = Convert.ToString(p.Value) - }; + IEnumerable @params = from p in request.Parameters + where p.Type == ParameterType.GetOrPost && p.Value != null + select new HttpParameter + { + Name = p.Name, + Value = Convert.ToString(p.Value) + }; - foreach (var parameter in @params) + foreach (HttpParameter parameter in @params) { http.Parameters.Add(parameter); } - foreach (var file in request.Files) + foreach (FileParameter file in request.Files) { http.Files.Add(new HttpFile { @@ -487,9 +506,7 @@ private void ConfigureHttp(IRestRequest request, IHttp http) }); } - var body = (from p in request.Parameters - where p.Type == ParameterType.RequestBody - select p).FirstOrDefault(); + Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody); // Only add the body if there aren't any files to make it a multipart form request // If there are files, then add the body to the HTTP Parameters @@ -502,9 +519,13 @@ private void ConfigureHttp(IRestRequest request, IHttp http) object val = body.Value; if (val is byte[]) - http.RequestBodyBytes = (byte[])val; + { + http.RequestBodyBytes = (byte[]) val; + } else + { http.RequestBody = Convert.ToString(body.Value); + } } else { @@ -524,33 +545,33 @@ private void ConfigureHttp(IRestRequest request, IHttp http) #if FRAMEWORK private void ConfigureProxy(IHttp http) { - if (Proxy != null) + if (this.Proxy != null) { - http.Proxy = Proxy; + http.Proxy = this.Proxy; } } #endif private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponse httpResponse) { - var restResponse = new RestResponse - { - Content = httpResponse.Content, - ContentEncoding = httpResponse.ContentEncoding, - ContentLength = httpResponse.ContentLength, - ContentType = httpResponse.ContentType, - ErrorException = httpResponse.ErrorException, - ErrorMessage = httpResponse.ErrorMessage, - RawBytes = httpResponse.RawBytes, - ResponseStatus = httpResponse.ResponseStatus, - ResponseUri = httpResponse.ResponseUri, - Server = httpResponse.Server, - StatusCode = httpResponse.StatusCode, - StatusDescription = httpResponse.StatusDescription, - Request = request - }; - - foreach (var header in httpResponse.Headers) + RestResponse restResponse = new RestResponse + { + Content = httpResponse.Content, + ContentEncoding = httpResponse.ContentEncoding, + ContentLength = httpResponse.ContentLength, + ContentType = httpResponse.ContentType, + ErrorException = httpResponse.ErrorException, + ErrorMessage = httpResponse.ErrorMessage, + RawBytes = httpResponse.RawBytes, + ResponseStatus = httpResponse.ResponseStatus, + ResponseUri = httpResponse.ResponseUri, + Server = httpResponse.Server, + StatusCode = httpResponse.StatusCode, + StatusDescription = httpResponse.StatusDescription, + Request = request + }; + + foreach (HttpHeader header in httpResponse.Headers) { restResponse.Headers.Add(new Parameter { @@ -560,7 +581,7 @@ private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResp }); } - foreach (var cookie in httpResponse.Cookies) + foreach (HttpCookie cookie in httpResponse.Cookies) { restResponse.Cookies.Add(new RestResponseCookie { diff --git a/RestSharp/RestClientExtensions.cs b/RestSharp/RestClientExtensions.cs index 669a63767..99cafea4b 100644 --- a/RestSharp/RestClientExtensions.cs +++ b/RestSharp/RestClientExtensions.cs @@ -1,12 +1,13 @@ using System; using System.Linq; + #if NET4 || MONODROID || MONOTOUCH || WP8 using System.Threading.Tasks; #endif namespace RestSharp { - public static partial class RestClientExtensions + public static class RestClientExtensions { /// /// Executes the request and callback asynchronously, authenticating if needed @@ -37,55 +38,63 @@ public static RestRequestAsyncHandle GetAsync(this IRestClient client, IRestR Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.GET; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle PostAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.POST; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle PutAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.PUT; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle HeadAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.HEAD; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle OptionsAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.OPTIONS; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle PatchAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.PATCH; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle DeleteAsync(this IRestClient client, IRestRequest request, Action, RestRequestAsyncHandle> callback) where T : new() { request.Method = Method.DELETE; - return client.ExecuteAsync(request, callback); + + return client.ExecuteAsync(request, callback); } public static RestRequestAsyncHandle GetAsync(this IRestClient client, IRestRequest request, Action callback) { request.Method = Method.GET; + return client.ExecuteAsync(request, callback); } @@ -93,6 +102,7 @@ public static RestRequestAsyncHandle PostAsync(this IRestClient client, IRestReq Action callback) { request.Method = Method.POST; + return client.ExecuteAsync(request, callback); } @@ -100,6 +110,7 @@ public static RestRequestAsyncHandle PutAsync(this IRestClient client, IRestRequ Action callback) { request.Method = Method.PUT; + return client.ExecuteAsync(request, callback); } @@ -107,6 +118,7 @@ public static RestRequestAsyncHandle HeadAsync(this IRestClient client, IRestReq Action callback) { request.Method = Method.HEAD; + return client.ExecuteAsync(request, callback); } @@ -114,6 +126,7 @@ public static RestRequestAsyncHandle OptionsAsync(this IRestClient client, IRest Action callback) { request.Method = Method.OPTIONS; + return client.ExecuteAsync(request, callback); } @@ -121,6 +134,7 @@ public static RestRequestAsyncHandle PatchAsync(this IRestClient client, IRestRe Action callback) { request.Method = Method.PATCH; + return client.ExecuteAsync(request, callback); } @@ -128,9 +142,23 @@ public static RestRequestAsyncHandle DeleteAsync(this IRestClient client, IRestR Action callback) { request.Method = Method.DELETE; + return client.ExecuteAsync(request, callback); } +#if NET4 + public static RestResponse ExecuteDynamic(this IRestClient client, IRestRequest request) + { + IRestResponse response = client.Execute(request); + RestResponse generic = (RestResponse)response; + dynamic content = SimpleJson.DeserializeObject(response.Content); + + generic.Data = content; + + return generic; + } +#endif + #if NET4 || MONODROID || MONOTOUCH || WP8 public static Task GetTaskAsync(this IRestClient client, IRestRequest request) where T : new() { @@ -145,30 +173,35 @@ public static RestRequestAsyncHandle DeleteAsync(this IRestClient client, IRestR public static Task PutTaskAsync(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.PUT; + return client.ExecuteTaskAsync(request).ContinueWith(x => x.Result.Data); } public static Task HeadTaskAsync(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.HEAD; + return client.ExecuteTaskAsync(request).ContinueWith(x => x.Result.Data); } public static Task OptionsTaskAsync(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.OPTIONS; + return client.ExecuteTaskAsync(request).ContinueWith(x => x.Result.Data); } public static Task PatchTaskAsync(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.PATCH; + return client.ExecuteTaskAsync(request).ContinueWith(x => x.Result.Data); } public static Task DeleteTaskAsync(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.DELETE; + return client.ExecuteTaskAsync(request).ContinueWith(x => x.Result.Data); } #endif @@ -177,84 +210,98 @@ public static RestRequestAsyncHandle DeleteAsync(this IRestClient client, IRestR public static IRestResponse Get(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.GET; + return client.Execute(request); } public static IRestResponse Post(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.POST; + return client.Execute(request); } public static IRestResponse Put(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.PUT; + return client.Execute(request); } public static IRestResponse Head(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.HEAD; + return client.Execute(request); } public static IRestResponse Options(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.OPTIONS; + return client.Execute(request); } public static IRestResponse Patch(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.PATCH; + return client.Execute(request); } public static IRestResponse Delete(this IRestClient client, IRestRequest request) where T : new() { request.Method = Method.DELETE; + return client.Execute(request); } public static IRestResponse Get(this IRestClient client, IRestRequest request) { request.Method = Method.GET; + return client.Execute(request); } public static IRestResponse Post(this IRestClient client, IRestRequest request) { request.Method = Method.POST; + return client.Execute(request); } public static IRestResponse Put(this IRestClient client, IRestRequest request) { request.Method = Method.PUT; + return client.Execute(request); } public static IRestResponse Head(this IRestClient client, IRestRequest request) { request.Method = Method.HEAD; + return client.Execute(request); } public static IRestResponse Options(this IRestClient client, IRestRequest request) { request.Method = Method.OPTIONS; + return client.Execute(request); } public static IRestResponse Patch(this IRestClient client, IRestRequest request) { request.Method = Method.PATCH; + return client.Execute(request); } public static IRestResponse Delete(this IRestClient client, IRestRequest request) { request.Method = Method.DELETE; + return client.Execute(request); } #endif @@ -284,9 +331,8 @@ public static void AddDefaultParameter(this IRestClient restClient, Parameter p) /// public static void RemoveDefaultParameter(this IRestClient restClient, string name) { - var parameter = - restClient.DefaultParameters.SingleOrDefault( - p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + Parameter parameter = restClient.DefaultParameters.SingleOrDefault( + p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (parameter != null) { @@ -304,7 +350,12 @@ public static void RemoveDefaultParameter(this IRestClient restClient, string na /// This request public static void AddDefaultParameter(this IRestClient restClient, string name, object value) { - restClient.AddDefaultParameter(new Parameter {Name = name, Value = value, Type = ParameterType.GetOrPost}); + restClient.AddDefaultParameter(new Parameter + { + Name = name, + Value = value, + Type = ParameterType.GetOrPost + }); } /// @@ -322,7 +373,12 @@ public static void AddDefaultParameter(this IRestClient restClient, string name, public static void AddDefaultParameter(this IRestClient restClient, string name, object value, ParameterType type) { - restClient.AddDefaultParameter(new Parameter {Name = name, Value = value, Type = type}); + restClient.AddDefaultParameter(new Parameter + { + Name = name, + Value = value, + Type = type + }); } /// diff --git a/RestSharp/RestRequest.cs b/RestSharp/RestRequest.cs index 03ae59f1b..f7cc6b2b7 100644 --- a/RestSharp/RestRequest.cs +++ b/RestSharp/RestRequest.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -19,10 +21,14 @@ using System.IO; using System.Linq; using System.Net; +using System.Reflection; using System.Text.RegularExpressions; -using RestSharp.Extensions; using RestSharp.Serializers; +#if FRAMEWORK +using RestSharp.Extensions; +#endif + namespace RestSharp { /// @@ -63,6 +69,8 @@ public class RestRequest : IRestRequest /// public RestRequest() { + this.RequestFormat = DataFormat.Xml; + this.Method = Method.GET; this.Parameters = new List(); this.Files = new List(); this.XmlSerializer = new XmlSerializer(); @@ -109,7 +117,9 @@ public RestRequest(Uri resource) : this(resource, Method.GET) { } /// Resource to use for this request /// Method to use for this request public RestRequest(Uri resource, Method method) - : this(resource.IsAbsoluteUri ? resource.AbsolutePath + resource.Query : resource.OriginalString, method) + : this(resource.IsAbsoluteUri + ? resource.AbsolutePath + resource.Query + : resource.OriginalString, method) { //resource.PathAndQuery not supported by Silverlight :( } @@ -127,19 +137,19 @@ public IRestRequest AddFile(string name, string path, string contentType = null) FileInfo f = new FileInfo(path); long fileLength = f.Length; - return AddFile(new FileParameter + return this.AddFile(new FileParameter { Name = name, FileName = Path.GetFileName(path), ContentLength = fileLength, Writer = s => { - using (var file = new StreamReader(path)) + using (StreamReader file = new StreamReader(path)) { file.BaseStream.CopyTo(s); } }, - ContentType = contentType + ContentType = contentType }); } @@ -166,18 +176,19 @@ public IRestRequest AddFile(string name, byte[] bytes, string fileName, string c /// This request public IRestRequest AddFile(string name, Action writer, string fileName, string contentType = null) { - return AddFile(new FileParameter - { - Name = name, - Writer = writer, - FileName = fileName, - ContentType = contentType - }); + return this.AddFile(new FileParameter + { + Name = name, + Writer = writer, + FileName = fileName, + ContentType = contentType + }); } private IRestRequest AddFile(FileParameter file) { this.Files.Add(file); + return this; } @@ -193,20 +204,20 @@ public IRestRequest AddFileBytes(string name, byte[] bytes, string filename, str { long length = bytes.Length; - return AddFile(new FileParameter - { - Name = name, - FileName = filename, - ContentLength = length, - ContentType = contentType, - Writer = s => - { - using (var file = new StreamReader(new MemoryStream(bytes))) - { - file.BaseStream.CopyTo(s); - } - } - }); + return this.AddFile(new FileParameter + { + Name = name, + FileName = filename, + ContentLength = length, + ContentType = contentType, + Writer = s => + { + using (StreamReader file = new StreamReader(new MemoryStream(bytes))) + { + file.BaseStream.CopyTo(s); + } + } + }); } /// @@ -221,17 +232,17 @@ public IRestRequest AddBody(object obj, string xmlNamespace) string serialized; string contentType; - switch (RequestFormat) + switch (this.RequestFormat) { case DataFormat.Json: - serialized = JsonSerializer.Serialize(obj); - contentType = JsonSerializer.ContentType; + serialized = this.JsonSerializer.Serialize(obj); + contentType = this.JsonSerializer.ContentType; break; case DataFormat.Xml: this.XmlSerializer.Namespace = xmlNamespace; - serialized = XmlSerializer.Serialize(obj); - contentType = XmlSerializer.ContentType; + serialized = this.XmlSerializer.Serialize(obj); + contentType = this.XmlSerializer.ContentType; break; default: @@ -265,6 +276,7 @@ public IRestRequest AddBody(object obj) public IRestRequest AddJsonBody(object obj) { this.RequestFormat = DataFormat.Json; + return this.AddBody(obj, ""); } @@ -276,6 +288,7 @@ public IRestRequest AddJsonBody(object obj) public IRestRequest AddXmlBody(object obj) { this.RequestFormat = DataFormat.Xml; + return this.AddBody(obj, ""); } @@ -289,6 +302,7 @@ public IRestRequest AddXmlBody(object obj) public IRestRequest AddXmlBody(object obj, string xmlNamespace) { this.RequestFormat = DataFormat.Xml; + return this.AddBody(obj, xmlNamespace); } @@ -304,42 +318,45 @@ public IRestRequest AddXmlBody(object obj, string xmlNamespace) public IRestRequest AddObject(object obj, params string[] includedProperties) { // automatically create parameters from object props - var type = obj.GetType(); - var props = type.GetProperties(); + Type type = obj.GetType(); + PropertyInfo[] props = type.GetProperties(); - foreach (var prop in props) + foreach (PropertyInfo prop in props) { bool isAllowed = includedProperties.Length == 0 || (includedProperties.Length > 0 && includedProperties.Contains(prop.Name)); if (!isAllowed) + { continue; + } - var propType = prop.PropertyType; - var val = prop.GetValue(obj, null); + Type propType = prop.PropertyType; + object val = prop.GetValue(obj, null); if (val == null) + { continue; + } if (propType.IsArray) { - var elementType = propType.GetElementType(); + Type elementType = propType.GetElementType(); - if (((Array)val).Length > 0 && + if (((Array) val).Length > 0 && elementType != null && - (elementType.IsPrimitive|| elementType.IsValueType || elementType == typeof(string))) + (elementType.IsPrimitive || elementType.IsValueType || elementType == typeof(string))) { // convert the array to an array of strings - var values = (from object item in ((Array)val) - select item.ToString()) - .ToArray(); + string[] values = (from object item in ((Array) val) + select item.ToString()).ToArray(); val = string.Join(",", values); } else { // try to cast it - val = string.Join(",", (string[])val); + val = string.Join(",", (string[]) val); } } @@ -357,6 +374,7 @@ select item.ToString()) public IRestRequest AddObject(object obj) { this.AddObject(obj, new string[] { }); + return this; } @@ -368,6 +386,7 @@ public IRestRequest AddObject(object obj) public IRestRequest AddParameter(Parameter p) { this.Parameters.Add(p); + return this; } @@ -423,12 +442,12 @@ public IRestRequest AddParameter(string name, object value, ParameterType type) public IRestRequest AddParameter(string name, object value, string contentType, ParameterType type) { return this.AddParameter(new Parameter - { - Name = name, - Value = value, - ContentType = contentType, - Type = type - }); + { + Name = name, + Value = value, + ContentType = contentType, + Type = type + }); } /// @@ -496,17 +515,11 @@ public IRestRequest AddQueryParameter(string name, string value) /// public List Files { get; private set; } - private Method method = Method.GET; - /// /// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS /// Default is GET /// - public Method Method - { - get { return this.method; } - set { this.method = value; } - } + public Method Method { get; set; } /// /// The Resource URL to make the request against. @@ -522,17 +535,11 @@ public Method Method /// public string Resource { get; set; } - private DataFormat requestFormat = DataFormat.Xml; - /// /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. /// By default XmlSerializer is used. /// - public DataFormat RequestFormat - { - get { return this.requestFormat; } - set { this.requestFormat = value; } - } + public DataFormat RequestFormat { get; set; } /// /// Used by the default deserializers to determine where to start deserializing from. diff --git a/RestSharp/RestRequestAsyncHandle.cs b/RestSharp/RestRequestAsyncHandle.cs index 0066c4f2f..666e8bea2 100644 --- a/RestSharp/RestRequestAsyncHandle.cs +++ b/RestSharp/RestRequestAsyncHandle.cs @@ -6,19 +6,19 @@ public class RestRequestAsyncHandle { public HttpWebRequest WebRequest; - public RestRequestAsyncHandle() - { - } + public RestRequestAsyncHandle() { } public RestRequestAsyncHandle(HttpWebRequest webRequest) { - WebRequest = webRequest; + this.WebRequest = webRequest; } public void Abort() { - if (WebRequest != null) - WebRequest.Abort(); + if (this.WebRequest != null) + { + this.WebRequest.Abort(); + } } } } diff --git a/RestSharp/RestResponse.cs b/RestSharp/RestResponse.cs index 7ffdf9510..8c5c57907 100644 --- a/RestSharp/RestResponse.cs +++ b/RestSharp/RestResponse.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -26,15 +28,16 @@ namespace RestSharp /// public abstract class RestResponseBase { - private string _content; + private string content; /// /// Default constructor /// - public RestResponseBase() + protected RestResponseBase() { - Headers = new List(); - Cookies = new List(); + this.ResponseStatus = ResponseStatus.None; + this.Headers = new List(); + this.Cookies = new List(); } /// @@ -65,16 +68,8 @@ public RestResponseBase() /// public string Content { - get - { - if (_content == null) - { - _content = RawBytes.AsString(); - } - - return _content; - } - set { _content = value; } + get { return this.content ?? (this.content = this.RawBytes.AsString()); } + set { this.content = value; } } /// @@ -112,17 +107,11 @@ public string Content /// public IList Headers { get; protected internal set; } - private ResponseStatus _responseStatus = ResponseStatus.None; - /// /// Status of the request. Will return Error for transport errors. /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead /// - public ResponseStatus ResponseStatus - { - get { return _responseStatus; } - set { _responseStatus = value; } - } + public ResponseStatus ResponseStatus { get; set; } /// /// Transport or other non-HTTP error generated while attempting request @@ -149,22 +138,22 @@ public class RestResponse : RestResponseBase, IRestResponse public static explicit operator RestResponse(RestResponse response) { return new RestResponse - { - ContentEncoding = response.ContentEncoding, - ContentLength = response.ContentLength, - ContentType = response.ContentType, - Cookies = response.Cookies, - ErrorMessage = response.ErrorMessage, - ErrorException = response.ErrorException, - Headers = response.Headers, - RawBytes = response.RawBytes, - ResponseStatus = response.ResponseStatus, - ResponseUri = response.ResponseUri, - Server = response.Server, - StatusCode = response.StatusCode, - StatusDescription = response.StatusDescription, - Request = response.Request - }; + { + ContentEncoding = response.ContentEncoding, + ContentLength = response.ContentLength, + ContentType = response.ContentType, + Cookies = response.Cookies, + ErrorMessage = response.ErrorMessage, + ErrorException = response.ErrorException, + Headers = response.Headers, + RawBytes = response.RawBytes, + ResponseStatus = response.ResponseStatus, + ResponseUri = response.ResponseUri, + Server = response.Server, + StatusCode = response.StatusCode, + StatusDescription = response.StatusDescription, + Request = response.Request + }; } } diff --git a/RestSharp/RestSharp.Compact.csproj b/RestSharp/RestSharp.Compact.csproj deleted file mode 100644 index 7dcba3d69..000000000 --- a/RestSharp/RestSharp.Compact.csproj +++ /dev/null @@ -1,160 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {A29E330B-F854-4287-BEB2-C4CBE9D9C637} - Library - Properties - RestSharp.Compact - RestSharp.Compact - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - RestSharp.Compact - v3.5 - Windows Mobile 5.0 Pocket PC SDK - - - - - true - full - false - bin_compact\Debug\ - TRACE;DEBUG;PocketPC SIMPLE_JSON_NO_LINQ_EXPRESSION - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin_compact\Release\ - TRACE;PocketPC SIMPLE_JSON_NO_LINQ_EXPRESSION FRAMEWORK - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - T4Helper.log - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/RestSharp/RestSharp.Signed.csproj b/RestSharp/RestSharp.Net35.Signed.csproj similarity index 98% rename from RestSharp/RestSharp.Signed.csproj rename to RestSharp/RestSharp.Net35.Signed.csproj index 020845cc8..bd42d9160 100644 --- a/RestSharp/RestSharp.Signed.csproj +++ b/RestSharp/RestSharp.Net35.Signed.csproj @@ -5,7 +5,7 @@ AnyCPU 9.0.30729 2.0 - {2ECECFBF-5F3E-40EE-A963-72336DC7ABE2} + {3190E0DC-674C-4C41-A7A3-BD2F406963B0} Library Properties RestSharp @@ -201,9 +201,9 @@ - + {ccc30138-3d68-44d8-af1a-d22f769ee8dc} - RestSharp.Build.Signed + RestSharp.Build diff --git a/RestSharp/RestSharp.csproj b/RestSharp/RestSharp.Net35.csproj similarity index 100% rename from RestSharp/RestSharp.csproj rename to RestSharp/RestSharp.Net35.csproj diff --git a/RestSharp/Serializers/DotNetXmlSerializer.cs b/RestSharp/Serializers/DotNetXmlSerializer.cs index e322821f3..cd962cce2 100644 --- a/RestSharp/Serializers/DotNetXmlSerializer.cs +++ b/RestSharp/Serializers/DotNetXmlSerializer.cs @@ -14,8 +14,8 @@ public class DotNetXmlSerializer : ISerializer /// public DotNetXmlSerializer() { - ContentType = "application/xml"; - Encoding = Encoding.UTF8; + this.ContentType = "application/xml"; + this.Encoding = Encoding.UTF8; } /// @@ -25,7 +25,7 @@ public DotNetXmlSerializer() public DotNetXmlSerializer(string @namespace) : this() { - Namespace = @namespace; + this.Namespace = @namespace; } /// @@ -35,12 +35,12 @@ public DotNetXmlSerializer(string @namespace) /// XML as string public string Serialize(object obj) { - var ns = new XmlSerializerNamespaces(); + XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); - ns.Add(string.Empty, Namespace); + ns.Add(string.Empty, this.Namespace); - var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); - var writer = new EncodingStringWriter(Encoding); + System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); + EncodingStringWriter writer = new EncodingStringWriter(this.Encoding); serializer.Serialize(writer, obj, ns); @@ -86,7 +86,7 @@ public EncodingStringWriter(Encoding encoding) public override Encoding Encoding { - get { return encoding; } + get { return this.encoding; } } } } diff --git a/RestSharp/Serializers/ISerializer.cs b/RestSharp/Serializers/ISerializer.cs index 084a66e92..db1c4b052 100644 --- a/RestSharp/Serializers/ISerializer.cs +++ b/RestSharp/Serializers/ISerializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion namespace RestSharp.Serializers diff --git a/RestSharp/Serializers/JsonSerializer.cs b/RestSharp/Serializers/JsonSerializer.cs index eeadd5450..a3a45b374 100644 --- a/RestSharp/Serializers/JsonSerializer.cs +++ b/RestSharp/Serializers/JsonSerializer.cs @@ -12,7 +12,7 @@ public class JsonSerializer : ISerializer /// public JsonSerializer() { - ContentType = "application/json"; + this.ContentType = "application/json"; } /// diff --git a/RestSharp/Serializers/SerializeAsAttribute.cs b/RestSharp/Serializers/SerializeAsAttribute.cs index 026b9512e..028ba5f90 100644 --- a/RestSharp/Serializers/SerializeAsAttribute.cs +++ b/RestSharp/Serializers/SerializeAsAttribute.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -25,14 +27,14 @@ namespace RestSharp.Serializers /// Currently not supported with the JsonSerializer /// When specified at the property level the class-level specification is overridden /// - [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)] public sealed class SerializeAsAttribute : Attribute { public SerializeAsAttribute() { - NameStyle = NameStyle.AsIs; - Index = int.MaxValue; - Culture = CultureInfo.InvariantCulture; + this.NameStyle = NameStyle.AsIs; + this.Index = int.MaxValue; + this.Culture = CultureInfo.InvariantCulture; } /// @@ -67,15 +69,15 @@ public SerializeAsAttribute() /// String public string TransformName(string input) { - var name = this.Name ?? input; + string name = this.Name ?? input; - switch (NameStyle) + switch (this.NameStyle) { case NameStyle.CamelCase: - return name.ToCamelCase(Culture); + return name.ToCamelCase(this.Culture); case NameStyle.PascalCase: - return name.ToPascalCase(Culture); + return name.ToPascalCase(this.Culture); case NameStyle.LowerCase: return name.ToLower(); diff --git a/RestSharp/Serializers/XmlSerializer.cs b/RestSharp/Serializers/XmlSerializer.cs index 5b4d176af..46357cb9e 100644 --- a/RestSharp/Serializers/XmlSerializer.cs +++ b/RestSharp/Serializers/XmlSerializer.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,12 +13,15 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; using System.Collections; +using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Reflection; using System.Xml.Linq; using RestSharp.Extensions; @@ -33,7 +37,7 @@ public class XmlSerializer : ISerializer /// public XmlSerializer() { - ContentType = "text/xml"; + this.ContentType = "text/xml"; } /// @@ -42,8 +46,8 @@ public XmlSerializer() /// XML namespace public XmlSerializer(string @namespace) { - Namespace = @namespace; - ContentType = "text/xml"; + this.Namespace = @namespace; + this.ContentType = "text/xml"; } /// @@ -53,26 +57,26 @@ public XmlSerializer(string @namespace) /// XML as string public string Serialize(object obj) { - var doc = new XDocument(); - var t = obj.GetType(); - var name = t.Name; - var options = t.GetAttribute(); + XDocument doc = new XDocument(); + Type t = obj.GetType(); + string name = t.Name; + SerializeAsAttribute options = t.GetAttribute(); if (options != null) { name = options.TransformName(options.Name ?? name); } - var root = new XElement(name.AsNamespaced(Namespace)); + XElement root = new XElement(name.AsNamespaced(this.Namespace)); if (obj is IList) { - var itemTypeName = ""; + string itemTypeName = ""; - foreach (var item in (IList)obj) + foreach (object item in (IList) obj) { - var type = item.GetType(); - var opts = type.GetAttribute(); + Type type = item.GetType(); + SerializeAsAttribute opts = type.GetAttribute(); if (opts != null) { @@ -84,18 +88,20 @@ public string Serialize(object obj) itemTypeName = type.Name; } - var instance = new XElement(itemTypeName.AsNamespaced(Namespace)); + XElement instance = new XElement(itemTypeName.AsNamespaced(this.Namespace)); - Map(instance, item); + this.Map(instance, item); root.Add(instance); } } else - Map(root, obj); + { + this.Map(root, obj); + } - if (RootElement.HasValue()) + if (this.RootElement.HasValue()) { - var wrapper = new XElement(RootElement.AsNamespaced(Namespace), root); + XElement wrapper = new XElement(this.RootElement.AsNamespaced(this.Namespace), root); doc.Add(wrapper); } else @@ -106,38 +112,42 @@ public string Serialize(object obj) return doc.ToString(); } - private void Map(XElement root, object obj) + private void Map(XContainer root, object obj) { - var objType = obj.GetType(); - var props = from p in objType.GetProperties() - let indexAttribute = p.GetAttribute() - where p.CanRead && p.CanWrite - orderby indexAttribute == null ? int.MaxValue : indexAttribute.Index - select p; - var globalOptions = objType.GetAttribute(); - - foreach (var prop in props) + Type objType = obj.GetType(); + IEnumerable props = from p in objType.GetProperties() + let indexAttribute = p.GetAttribute() + where p.CanRead && p.CanWrite + orderby indexAttribute == null + ? int.MaxValue + : indexAttribute.Index + select p; + SerializeAsAttribute globalOptions = objType.GetAttribute(); + + foreach (PropertyInfo prop in props) { - var name = prop.Name; - var rawValue = prop.GetValue(obj, null); + string name = prop.Name; + object rawValue = prop.GetValue(obj, null); if (rawValue == null) { continue; } - var value = GetSerializedValue(rawValue); - var propType = prop.PropertyType; - var useAttribute = false; - var settings = prop.GetAttribute(); + string value = this.GetSerializedValue(rawValue); + Type propType = prop.PropertyType; + bool useAttribute = false; + SerializeAsAttribute settings = prop.GetAttribute(); if (settings != null) { - name = settings.Name.HasValue() ? settings.Name : name; + name = settings.Name.HasValue() + ? settings.Name + : name; useAttribute = settings.Attribute; } - var options = prop.GetAttribute(); + SerializeAsAttribute options = prop.GetAttribute(); if (options != null) { @@ -148,8 +158,8 @@ where p.CanRead && p.CanWrite name = globalOptions.TransformName(name); } - var nsName = name.AsNamespaced(Namespace); - var element = new XElement(nsName); + XName nsName = name.AsNamespaced(this.Namespace); + XElement element = new XElement(nsName); if (propType.IsPrimitive || propType.IsValueType || propType == typeof(string)) { @@ -163,28 +173,29 @@ where p.CanRead && p.CanWrite } else if (rawValue is IList) { - var itemTypeName = ""; + string itemTypeName = ""; - foreach (var item in (IList)rawValue) + foreach (object item in (IList) rawValue) { if (itemTypeName == "") { - var type = item.GetType(); - var setting = type.GetAttribute(); + Type type = item.GetType(); + SerializeAsAttribute setting = type.GetAttribute(); + itemTypeName = setting != null && setting.Name.HasValue() ? setting.Name : type.Name; } - var instance = new XElement(itemTypeName.AsNamespaced(Namespace)); + XElement instance = new XElement(itemTypeName.AsNamespaced(this.Namespace)); - Map(instance, item); + this.Map(instance, item); element.Add(instance); } } else { - Map(element, rawValue); + this.Map(element, rawValue); } root.Add(element); @@ -193,16 +204,16 @@ where p.CanRead && p.CanWrite private string GetSerializedValue(object obj) { - var output = obj; + object output = obj; - if (obj is DateTime && DateFormat.HasValue()) + if (obj is DateTime && this.DateFormat.HasValue()) { - output = ((DateTime)obj).ToString(DateFormat, CultureInfo.InvariantCulture); + output = ((DateTime) obj).ToString(this.DateFormat, CultureInfo.InvariantCulture); } if (obj is bool) { - output = ((bool)obj).ToString(CultureInfo.InvariantCulture).ToLower(); + output = ((bool) obj).ToString(CultureInfo.InvariantCulture).ToLower(); } if (IsNumeric(obj)) @@ -213,67 +224,102 @@ private string GetSerializedValue(object obj) return output.ToString(); } - static string SerializeNumber(object number) + private static string SerializeNumber(object number) { if (number is long) - return ((long)number).ToString(CultureInfo.InvariantCulture); + { + return ((long) number).ToString(CultureInfo.InvariantCulture); + } if (number is ulong) - return ((ulong)number).ToString(CultureInfo.InvariantCulture); + { + return ((ulong) number).ToString(CultureInfo.InvariantCulture); + } if (number is int) - return ((int)number).ToString(CultureInfo.InvariantCulture); + { + return ((int) number).ToString(CultureInfo.InvariantCulture); + } if (number is uint) - return ((uint)number).ToString(CultureInfo.InvariantCulture); + { + return ((uint) number).ToString(CultureInfo.InvariantCulture); + } if (number is decimal) - return ((decimal)number).ToString(CultureInfo.InvariantCulture); + { + return ((decimal) number).ToString(CultureInfo.InvariantCulture); + } if (number is float) - return ((float)number).ToString(CultureInfo.InvariantCulture); + { + return ((float) number).ToString(CultureInfo.InvariantCulture); + } - return (Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); + return (Convert.ToDouble(number, CultureInfo.InvariantCulture) + .ToString("r", CultureInfo.InvariantCulture)); } /// /// Determines if a given object is numeric in any way /// (can be integer, double, null, etc). /// - static bool IsNumeric(object value) + private static bool IsNumeric(object value) { if (value is sbyte) + { return true; + } if (value is byte) + { return true; + } if (value is short) + { return true; + } if (value is ushort) + { return true; + } if (value is int) + { return true; + } if (value is uint) + { return true; + } if (value is long) + { return true; + } if (value is ulong) + { return true; + } if (value is float) + { return true; + } if (value is double) + { return true; + } if (value is decimal) + { return true; + } return false; } diff --git a/RestSharp/SharedAssemblyInfo.cs b/RestSharp/SharedAssemblyInfo.cs index 43d7c8ee1..8f1faecc1 100644 --- a/RestSharp/SharedAssemblyInfo.cs +++ b/RestSharp/SharedAssemblyInfo.cs @@ -1,9 +1,11 @@ using System; using System.Reflection; +using RestSharp; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyDescription("Simple REST and HTTP API Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("John Sheehan, RestSharp Community")] @@ -22,24 +24,27 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion(SharedAssemblyInfo.Version + ".0")] -#if !PocketPC +[assembly: AssemblyVersion(SharedAssemblyInfo.VERSION + ".0")] + #if SIGNED -[assembly: AssemblyInformationalVersion(SharedAssemblyInfo.FileVersion)] -[assembly: AssemblyFileVersion(SharedAssemblyInfo.FileVersion + ".0")] +[assembly: AssemblyInformationalVersion(SharedAssemblyInfo.FILE_VERSION)] +[assembly: AssemblyFileVersion(SharedAssemblyInfo.FILE_VERSION + ".0")] #else -[assembly: AssemblyInformationalVersion(SharedAssemblyInfo.Version)] -[assembly: AssemblyFileVersion(SharedAssemblyInfo.Version + ".0")] -#endif + +[assembly: AssemblyInformationalVersion(SharedAssemblyInfo.VERSION)] +[assembly: AssemblyFileVersion(SharedAssemblyInfo.VERSION + ".0")] #endif -class SharedAssemblyInfo +namespace RestSharp { + internal class SharedAssemblyInfo + { #if SIGNED - public const string Version = "100.0.0"; - public const string FileVersion = "105.1.0"; + public const string VERSION = "100.0.0"; + public const string FILE_VERSION = "105.1.0"; #else - public const string Version = "105.1.0"; + public const string VERSION = "105.1.0"; #endif + } } diff --git a/RestSharp/SimpleJson.cs b/RestSharp/SimpleJson.cs index 4e857b69c..674ae2ee6 100644 --- a/RestSharp/SimpleJson.cs +++ b/RestSharp/SimpleJson.cs @@ -167,7 +167,8 @@ internal static object GetAtIndex(IDictionary obj, int index) throw new ArgumentOutOfRangeException("index"); int i = 0; foreach (KeyValuePair o in obj) - if (i++ == index) return o.Value; + if (i++ == index) + return o.Value; return null; } @@ -278,7 +279,8 @@ public bool Contains(KeyValuePair item) /// Index of the array. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array == null) throw new ArgumentNullException("array"); + if (array == null) + throw new ArgumentNullException("array"); int num = Count; foreach (KeyValuePair kvp in this) { @@ -526,7 +528,7 @@ static class SimpleJson static SimpleJson() { EscapeTable = new char[93]; - EscapeTable['"'] = '"'; + EscapeTable['"'] = '"'; EscapeTable['\\'] = '\\'; EscapeTable['\b'] = 'b'; EscapeTable['\f'] = 'f'; @@ -560,7 +562,7 @@ public static object DeserializeObject(string json) /// /// Returns true if successfull otherwise false. /// - [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] public static bool TryDeserializeObject(string json, out object obj) { bool success = true; @@ -591,12 +593,12 @@ public static object DeserializeObject(string json, Type type) public static T DeserializeObject(string json, IJsonSerializerStrategy jsonSerializerStrategy) { - return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy); + return (T) DeserializeObject(json, typeof(T), jsonSerializerStrategy); } public static T DeserializeObject(string json) { - return (T)DeserializeObject(json, typeof(T), null); + return (T) DeserializeObject(json, typeof(T), null); } /// @@ -854,8 +856,8 @@ static string ParseString(char[] json, ref int index, ref bool success) { if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate { - s.Append((char)codePoint); - s.Append((char)lowCodePoint); + s.Append((char) codePoint); + s.Append((char) lowCodePoint); index += 6; // skip 6 chars continue; } @@ -864,7 +866,7 @@ static string ParseString(char[] json, ref int index, ref bool success) success = false; // invalid surrogate pair return ""; } - s.Append(ConvertFromUtf32((int)codePoint)); + s.Append(ConvertFromUtf32((int) codePoint)); // skip 4 chars index += 4; } @@ -891,9 +893,9 @@ private static string ConvertFromUtf32(int utf32) if (0xD800 <= utf32 && utf32 <= 0xDFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); if (utf32 < 0x10000) - return new string((char)utf32, 1); + return new string((char) utf32, 1); utf32 -= 0x10000; - return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) }); + return new string(new char[] { (char) ((utf32 >> 10) + 0xD800), (char) (utf32 % 0x0400 + 0xDC00) }); } static object ParseNumber(char[] json, ref int index, ref bool success) @@ -923,14 +925,16 @@ static int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) - if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; + if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) + break; return lastIndex - 1; } static void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) - if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; + if (" \t\n\r\b\f".IndexOf(json[index]) == -1) + break; } static int LookAhead(char[] json, int index) @@ -1036,7 +1040,7 @@ static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, objec else if (IsNumeric(value)) success = SerializeNumber(value, builder); else if (value is bool) - builder.Append((bool)value ? "true" : "false"); + builder.Append((bool) value ? "true" : "false"); else if (value == null) builder.Append("null"); else @@ -1068,7 +1072,8 @@ static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnu if (stringKey != null) SerializeString(stringKey, builder); else - if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; builder.Append(":"); if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; @@ -1146,17 +1151,17 @@ static bool SerializeString(string aString, StringBuilder builder) static bool SerializeNumber(object number, StringBuilder builder) { if (number is long) - builder.Append(((long)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((long) number).ToString(CultureInfo.InvariantCulture)); else if (number is ulong) - builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((ulong) number).ToString(CultureInfo.InvariantCulture)); else if (number is int) - builder.Append(((int)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((int) number).ToString(CultureInfo.InvariantCulture)); else if (number is uint) - builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((uint) number).ToString(CultureInfo.InvariantCulture)); else if (number is decimal) - builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((decimal) number).ToString(CultureInfo.InvariantCulture)); else if (number is float) - builder.Append(((float)number).ToString(CultureInfo.InvariantCulture)); + builder.Append(((float) number).ToString(CultureInfo.InvariantCulture)); else builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); return true; @@ -1168,17 +1173,28 @@ static bool SerializeNumber(object number, StringBuilder builder) /// static bool IsNumeric(object value) { - if (value is sbyte) return true; - if (value is byte) return true; - if (value is short) return true; - if (value is ushort) return true; - if (value is int) return true; - if (value is uint) return true; - if (value is long) return true; - if (value is ulong) return true; - if (value is float) return true; - if (value is double) return true; - if (value is decimal) return true; + if (value is sbyte) + return true; + if (value is byte) + return true; + if (value is short) + return true; + if (value is ushort) + return true; + if (value is int) + return true; + if (value is uint) + return true; + if (value is long) + return true; + if (value is ulong) + return true; + if (value is float) + return true; + if (value is double) + return true; + if (value is decimal) + return true; return false; } @@ -1226,7 +1242,7 @@ public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrat #endif } - + [GeneratedCode("simple-json", "1.0.0")] #if SIMPLE_JSON_INTERNAL internal @@ -1235,7 +1251,7 @@ public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrat #endif interface IJsonSerializerStrategy { - [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] bool TrySerializeNonPrimitiveObject(object input, out object output); object DeserializeObject(object value, Type type); } @@ -1331,15 +1347,16 @@ public virtual bool TrySerializeNonPrimitiveObject(object input, out object outp [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public virtual object DeserializeObject(object value, Type type) { - if (type == null) throw new ArgumentNullException("type"); + if (type == null) + throw new ArgumentNullException("type"); string str = value as string; - if (type == typeof (Guid) && string.IsNullOrEmpty(str)) + if (type == typeof(Guid) && string.IsNullOrEmpty(str)) return default(Guid); if (value == null) return null; - + object obj = null; if (str != null) @@ -1348,25 +1365,27 @@ public virtual object DeserializeObject(object value, Type type) { if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime))) return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset))) return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))) return new Guid(str); if (type == typeof(Uri)) { - bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute); + bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute); Uri result; if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result)) return result; - return null; + return null; } - - if (type == typeof(string)) - return str; - return Convert.ChangeType(str, type, CultureInfo.InvariantCulture); + if (type == typeof(string)) + return str; + + return Convert.ChangeType(str, type, CultureInfo.InvariantCulture); } else { @@ -1383,7 +1402,7 @@ public virtual object DeserializeObject(object value, Type type) } else if (value is bool) return value; - + bool valueIsLong = value is long; bool valueIsDouble = value is double; if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double))) @@ -1410,7 +1429,7 @@ public virtual object DeserializeObject(object value, Type type) Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); - IDictionary dict = (IDictionary)ConstructorCache[genericType](); + IDictionary dict = (IDictionary) ConstructorCache[genericType](); foreach (KeyValuePair kvp in jsonObject) dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType)); @@ -1446,7 +1465,7 @@ public virtual object DeserializeObject(object value, Type type) if (type.IsArray) { - list = (IList)ConstructorCache[type](jsonObject.Count); + list = (IList) ConstructorCache[type](jsonObject.Count); int i = 0; foreach (object o in jsonObject) list[i++] = DeserializeObject(o, type.GetElementType()); @@ -1454,7 +1473,7 @@ public virtual object DeserializeObject(object value, Type type) else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type)) { Type innerType = ReflectionUtils.GetGenericListElementType(type); - list = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count); + list = (IList) (ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count); foreach (object o in jsonObject) list.Add(DeserializeObject(o, innerType)); } @@ -1473,21 +1492,23 @@ protected virtual object SerializeEnum(Enum p) return Convert.ToDouble(p, CultureInfo.InvariantCulture); } - [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] protected virtual bool TrySerializeKnownTypes(object input, out object output) { bool returnValue = true; + if (input is DateTime) - output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + output = ((DateTime) input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); else if (input is DateTimeOffset) - output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + output = ((DateTimeOffset) input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); else if (input is Guid) - output = ((Guid)input).ToString("D"); + output = ((Guid) input).ToString("D"); else if (input is Uri) output = input.ToString(); else { Enum inputEnum = input as Enum; + if (inputEnum != null) output = SerializeEnum(inputEnum); else @@ -1496,12 +1517,14 @@ protected virtual bool TrySerializeKnownTypes(object input, out object output) output = null; } } + return returnValue; } - [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] protected virtual bool TrySerializeUnknownTypes(object input, out object output) { - if (input == null) throw new ArgumentNullException("input"); + if (input == null) + throw new ArgumentNullException("input"); output = null; Type type = input.GetType(); if (type.FullName == null) @@ -1600,7 +1623,7 @@ private static bool CanAdd(MemberInfo info, out string jsonKey) namespace Reflection { // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules - // that might be in place in the target project. + // that might be in place in the target project. [GeneratedCode("reflection-utils", "1.0.0")] #if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC public @@ -1653,7 +1676,7 @@ public static Type GetGenericListElementType(Type type) foreach (Type implementedInterface in interfaces) { if (IsTypeGeneric(implementedInterface) && - implementedInterface.GetGenericTypeDefinition() == typeof (IList<>)) + implementedInterface.GetGenericTypeDefinition() == typeof(IList<>)) { return GetGenericTypeArguments(implementedInterface)[0]; } @@ -1703,7 +1726,7 @@ public static bool IsTypeGenericeCollectionInterface(Type type) || genericDefinition == typeof(IReadOnlyCollection<>) || genericDefinition == typeof(IReadOnlyList<>) #endif - ); +); } public static bool IsAssignableFrom(Type type1, Type type2) diff --git a/RestSharp/Validation/Require.cs b/RestSharp/Validation/Require.cs index af5bacfed..077f792ca 100644 --- a/RestSharp/Validation/Require.cs +++ b/RestSharp/Validation/Require.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; diff --git a/RestSharp/Validation/Validate.cs b/RestSharp/Validation/Validate.cs index 908831bc2..d6ee14ae7 100644 --- a/RestSharp/Validation/Validate.cs +++ b/RestSharp/Validation/Validate.cs @@ -1,4 +1,5 @@ #region License + // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + #endregion using System; @@ -45,7 +47,9 @@ public static void IsBetween(int value, int min, int max) public static void IsValidLength(string value, int maxSize) { if (value == null) + { return; + } if (value.Length > maxSize) { diff --git a/RestSharp/packages.config b/RestSharp/packages.config index e25ef8502..9ef0f3e1c 100644 --- a/RestSharp/packages.config +++ b/RestSharp/packages.config @@ -1,4 +1,5 @@  + - + \ No newline at end of file diff --git a/Tools/NuGet.exe b/Tools/NuGet.exe index 9ca66594f..324daa842 100644 Binary files a/Tools/NuGet.exe and b/Tools/NuGet.exe differ