REST client API: Silverlight and Windows Phone support (SPRNET-1345)
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 10.00
|
||||
# Visual Studio 2008
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.HttpMessageConverterQuickStart", "src\Spring.HttpMessageConverterQuickStart\Spring.HttpMessageConverterQuickStart.csproj", "{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2008", "..\..\..\src\Spring\Spring.Http\Spring.Http.2008.csproj", "{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2008", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2008.csproj", "{F04CEE18-3897-A399-46BF-459437475B21}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Spring.Http;
|
||||
using Spring.Http.Converters;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Spring.HttpMessageConverterQuickStart.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can read and write JSON
|
||||
/// using the Json.NET (Newtonsoft.Json) library.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This implementation supports getting/setting values from JSON directly,
|
||||
/// without the need to deserialize/serialize to a .NET class.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// By default, this converter supports 'application/json' media type.
|
||||
/// This can be overridden by setting the <see cref="P:SupportedMediaTypes"/> property.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class NJsonHttpMessageConverter : IHttpMessageConverter
|
||||
{
|
||||
private IList<MediaType> supportedMediaTypes;
|
||||
|
||||
public NJsonHttpMessageConverter()
|
||||
{
|
||||
this.supportedMediaTypes = new List<MediaType>(1);
|
||||
this.supportedMediaTypes.Add(MediaType.APPLICATION_JSON);
|
||||
}
|
||||
|
||||
#region IHttpMessageConverter Membres
|
||||
|
||||
public bool CanRead(Type type, MediaType mediaType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool CanWrite(Type type, MediaType mediaType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public IList<MediaType> SupportedMediaTypes
|
||||
{
|
||||
get { return this.supportedMediaTypes; }
|
||||
}
|
||||
|
||||
public T Read<T>(IHttpInputMessage message) where T : class
|
||||
{
|
||||
// Read from the message stream
|
||||
using (StreamReader reader = new StreamReader(message.Body))
|
||||
using (JsonTextReader jsonReader = new JsonTextReader(reader))
|
||||
{
|
||||
JsonSerializer jsonSerializer = new JsonSerializer();
|
||||
return jsonSerializer.Deserialize<T>(jsonReader);
|
||||
}
|
||||
}
|
||||
|
||||
public void Write(object content, MediaType contentType, IHttpOutputMessage message)
|
||||
{
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
using (StreamWriter writer = new StreamWriter(stream))
|
||||
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
|
||||
{
|
||||
JsonSerializer jsonSerializer = new JsonSerializer();
|
||||
jsonSerializer.Serialize(jsonWriter, content);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
|
||||
using Spring.Http;
|
||||
using Spring.Http.Client;
|
||||
using Spring.Http.Rest;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
using Spring.HttpMessageConverterQuickStart.Converters;
|
||||
|
||||
namespace Spring.HttpMessageConverterQuickStart
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
RestTemplate rt = new RestTemplate("http://twitter.com");
|
||||
rt.MessageConverters.Add(new NJsonHttpMessageConverter());
|
||||
|
||||
rt.GetForObjectAsync<JArray>("/statuses/user_timeline.json?screen_name={name}&count={count}", new string[] { "SpringForNet", "10" },
|
||||
r =>
|
||||
{
|
||||
if (r.Error == null)
|
||||
{
|
||||
var tweets = from el in r.Response.Children()
|
||||
select el.Value<string>("text");
|
||||
foreach (string tweet in tweets)
|
||||
{
|
||||
Console.WriteLine(String.Format("* {0}", tweet));
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(r.Error);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.WriteLine("--- hit <return> to quit ---");
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>9.0.30729</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{FAD4F098-21BF-4FDC-85CE-7DB6A27D6179}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.HttpMessageConverterQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.HttpMessageConverterQuickStart</AssemblyName>
|
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\lib\net-3.5\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core">
|
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Converters\NJsonHttpMessageConverter.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Spring\Spring.Http\Spring.Http.2008.csproj">
|
||||
<Project>{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}</Project>
|
||||
<Name>Spring.Http.2008</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -4,7 +4,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2005", "..\..\.
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2005", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2005.csproj", "{9437475B-3897-A399-46BF-45F04CEE1821}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestQuickStart.2005", "src\Spring.RestQuickStart\Spring.RestQuickStart.2005.csproj", "{5B47D309-31C9-4282-86E2-11FC63DFF55B}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestQuickStart.2005", "src\Spring.RestQuickStart.2005\Spring.RestQuickStart.2005.csproj", "{5B47D309-31C9-4282-86E2-11FC63DFF55B}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
|
||||
@@ -2,10 +2,10 @@ Microsoft Visual Studio Solution File, Format Version 10.00
|
||||
# Visual Studio 2008
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2008", "..\..\..\src\Spring\Spring.Http\Spring.Http.2008.csproj", "{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2008", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2008.csproj", "{F04CEE18-3897-A399-46BF-459437475B21}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestQuickStart.2008", "src\Spring.RestQuickStart\Spring.RestQuickStart.2008.csproj", "{5B47D309-31C9-4282-86E2-11FC63DFF55B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2008", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2008.csproj", "{F04CEE18-3897-A399-46BF-459437475B21}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -16,14 +16,14 @@ Global
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FAC04F79-4B1F-1D13-B30F-00EE04EC0FBC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F04CEE18-3897-A399-46BF-459437475B21}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -2,10 +2,10 @@ Microsoft Visual Studio Solution File, Format Version 11.00
|
||||
# Visual Studio 2010
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2010", "..\..\..\src\Spring\Spring.Http\Spring.Http.2010.csproj", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2010", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2010.csproj", "{4594CEE7-3897-A3BF-9946-5B4374F01821}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestQuickStart.2010", "src\Spring.RestQuickStart\Spring.RestQuickStart.2010.csproj", "{5B47D309-31C9-4282-86E2-11FC63DFF55B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2010", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2010.csproj", "{4594CEE7-3897-A3BF-9946-5B4374F01821}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -16,14 +16,14 @@ Global
|
||||
{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5B47D309-31C9-4282-86E2-11FC63DFF55B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4594CEE7-3897-A3BF-9946-5B4374F01821}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
using Spring.Http;
|
||||
using Spring.Http.Rest;
|
||||
|
||||
namespace Spring.RestQuickStart
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
RestTemplate rt = new RestTemplate("http://twitter.com");
|
||||
|
||||
// Exemple sync call
|
||||
Console.WriteLine("Allowed methods : ");
|
||||
foreach (HttpMethod method in rt.OptionsForAllow("/statuses/"))
|
||||
{
|
||||
Console.WriteLine(method);
|
||||
}
|
||||
|
||||
// Exemple async call
|
||||
rt.GetForObjectAsync<string>("/statuses/user_timeline.xml?screen_name={name}&count={count}", new string[] { "SpringForNet", "5" },
|
||||
delegate(MethodCompletedEventArgs<string> eventArgs)
|
||||
{
|
||||
if (eventArgs.Error != null)
|
||||
{
|
||||
Console.WriteLine(eventArgs.Error);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(eventArgs.Response);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.WriteLine("--- hit <return> to quit ---");
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>TRACE;DEBUG;NET_2_0</DefineConstants>
|
||||
<DefineConstants>TRACE;DEBUG</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
@@ -25,7 +25,7 @@
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;NET_2_0</DefineConstants>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
@@ -1,9 +1,9 @@
|
||||
using System;
|
||||
#if NET_3_5
|
||||
using System.Net;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
#endif
|
||||
|
||||
using Spring.Http;
|
||||
using Spring.Http.Rest;
|
||||
|
||||
namespace Spring.RestQuickStart
|
||||
@@ -16,30 +16,44 @@ namespace Spring.RestQuickStart
|
||||
{
|
||||
RestTemplate rt = new RestTemplate("http://twitter.com");
|
||||
|
||||
#if NET_3_5
|
||||
XElement result = rt.GetForObject<XElement>("/statuses/user_timeline.xml?id={id}&count={2}", "SpringForNet", "10");
|
||||
var tweets = from el in result.Elements("status")
|
||||
select el.Element("text").Value;
|
||||
foreach (string tweet in tweets)
|
||||
// Exemple sync call
|
||||
Console.WriteLine("Resource headers : ");
|
||||
HttpHeaders headers = rt.HeadForHeaders("/statuses/");
|
||||
foreach (string header in headers)
|
||||
{
|
||||
Console.WriteLine(String.Format("* {0}", tweet));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(String.Format("{0}: {1}", header, headers[header]));
|
||||
}
|
||||
#else
|
||||
string result = rt.GetForObject<string>("/statuses/user_timeline.xml?id={id}&count={2}", "SpringForNet", "10");
|
||||
Console.WriteLine(result);
|
||||
#endif
|
||||
|
||||
// Exemple async call
|
||||
rt.GetForObjectAsync<XElement>("/statuses/user_timeline.xml?screen_name={name}", new string[] { "SpringForNet" },
|
||||
r =>
|
||||
{
|
||||
if (r.Error != null)
|
||||
{
|
||||
Console.WriteLine(r.Error);
|
||||
}
|
||||
else
|
||||
{
|
||||
var tweets = from el in r.Response.Elements("status")
|
||||
select el.Element("text").Value;
|
||||
foreach (string tweet in tweets)
|
||||
{
|
||||
Console.WriteLine(String.Format("* {0}", tweet));
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.WriteLine("--- hit <return> to quit ---");
|
||||
Console.ReadLine();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.WriteLine("--- hit <return> to quit ---");
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 10.00
|
||||
# Visual Studio 2008
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestSilverlightQuickStart.2008", "src\Spring.RestSilverlightQuickStart\Spring.RestSilverlightQuickStart.2008.csproj", "{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2008-SL", "..\..\..\src\Spring\Spring.Http\Spring.Http.2008-SL.csproj", "{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestSilverlightQuickStart.Web.2008", "src\Spring.RestSilverlightQuickStart.Web.2008\Spring.RestSilverlightQuickStart.Web.2008.csproj", "{AFE006E7-F67F-45F9-826C-1273791D1574}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2008-SL", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2008-SL.csproj", "{AEA0D437-A442-4381-B682-5873D66DB72C}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AFE006E7-F67F-45F9-826C-1273791D1574}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AFE006E7-F67F-45F9-826C-1273791D1574}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AFE006E7-F67F-45F9-826C-1273791D1574}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AFE006E7-F67F-45F9-826C-1273791D1574}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AEA0D437-A442-4381-B682-5873D66DB72C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AEA0D437-A442-4381-B682-5873D66DB72C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AEA0D437-A442-4381-B682-5873D66DB72C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AEA0D437-A442-4381-B682-5873D66DB72C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,38 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 11.00
|
||||
# Visual Studio 2010
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2010-SL", "..\..\..\src\Spring\Spring.Http\Spring.Http.2010-SL.csproj", "{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestSilverlightQuickStart.2010", "src\Spring.RestSilverlightQuickStart\Spring.RestSilverlightQuickStart.2010.csproj", "{C11BD449-683C-44CA-B394-CC126DC49EF1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestSilverlightQuickStart.Web.2010", "src\Spring.RestSilverlightQuickStart.Web.2010\Spring.RestSilverlightQuickStart.Web.2010.csproj", "{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2010-SL", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2010-SL.csproj", "{5964F3BF-D3E0-4890-955A-BD287B834B36}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C11BD449-683C-44CA-B394-CC126DC49EF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C11BD449-683C-44CA-B394-CC126DC49EF1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C11BD449-683C-44CA-B394-CC126DC49EF1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C11BD449-683C-44CA-B394-CC126DC49EF1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5964F3BF-D3E0-4890-955A-BD287B834B36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5964F3BF-D3E0-4890-955A-BD287B834B36}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5964F3BF-D3E0-4890-955A-BD287B834B36}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5964F3BF-D3E0-4890-955A-BD287B834B36}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,74 @@
|
||||
<%@ Page Language="C#" AutoEventWireup="true" %>
|
||||
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" >
|
||||
<head runat="server">
|
||||
<title>Spring.RestSilverlightQuickStart</title>
|
||||
<style type="text/css">
|
||||
html, body {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#silverlightControlHost {
|
||||
height: 100%;
|
||||
text-align:center;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript" src="Silverlight.js"></script>
|
||||
<script type="text/javascript">
|
||||
function onSilverlightError(sender, args) {
|
||||
var appSource = "";
|
||||
if (sender != null && sender != 0) {
|
||||
appSource = sender.getHost().Source;
|
||||
}
|
||||
|
||||
var errorType = args.ErrorType;
|
||||
var iErrorCode = args.ErrorCode;
|
||||
|
||||
if (errorType == "ImageError" || errorType == "MediaError") {
|
||||
return;
|
||||
}
|
||||
|
||||
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
|
||||
|
||||
errMsg += "Code: "+ iErrorCode + " \n";
|
||||
errMsg += "Category: " + errorType + " \n";
|
||||
errMsg += "Message: " + args.ErrorMessage + " \n";
|
||||
|
||||
if (errorType == "ParserError") {
|
||||
errMsg += "File: " + args.xamlFile + " \n";
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
else if (errorType == "RuntimeError") {
|
||||
if (args.lineNumber != 0) {
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
errMsg += "MethodName: " + args.methodName + " \n";
|
||||
}
|
||||
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form1" runat="server" style="height:100%">
|
||||
<div id="silverlightControlHost">
|
||||
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
|
||||
<param name="source" value="ClientBin/Spring.RestSilverlightQuickStart.xap"/>
|
||||
<param name="onError" value="onSilverlightError" />
|
||||
<param name="background" value="white" />
|
||||
<param name="minRuntimeVersion" value="3.0.40624.0" />
|
||||
<param name="autoUpgrade" value="true" />
|
||||
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
|
||||
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
|
||||
</a>
|
||||
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,73 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" >
|
||||
|
||||
<head>
|
||||
<title>Spring.RestSilverlightQuickStart</title>
|
||||
<style type="text/css">
|
||||
html, body {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#silverlightControlHost {
|
||||
height: 100%;
|
||||
text-align:center;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript" src="Silverlight.js"></script>
|
||||
<script type="text/javascript">
|
||||
function onSilverlightError(sender, args) {
|
||||
var appSource = "";
|
||||
if (sender != null && sender != 0) {
|
||||
appSource = sender.getHost().Source;
|
||||
}
|
||||
|
||||
var errorType = args.ErrorType;
|
||||
var iErrorCode = args.ErrorCode;
|
||||
|
||||
if (errorType == "ImageError" || errorType == "MediaError") {
|
||||
return;
|
||||
}
|
||||
|
||||
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
|
||||
|
||||
errMsg += "Code: "+ iErrorCode + " \n";
|
||||
errMsg += "Category: " + errorType + " \n";
|
||||
errMsg += "Message: " + args.ErrorMessage + " \n";
|
||||
|
||||
if (errorType == "ParserError") {
|
||||
errMsg += "File: " + args.xamlFile + " \n";
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
else if (errorType == "RuntimeError") {
|
||||
if (args.lineNumber != 0) {
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
errMsg += "MethodName: " + args.methodName + " \n";
|
||||
}
|
||||
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form1" runat="server" style="height:100%">
|
||||
<div id="silverlightControlHost">
|
||||
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
|
||||
<param name="source" value="ClientBin/Spring.RestSilverlightQuickStart.xap"/>
|
||||
<param name="onError" value="onSilverlightError" />
|
||||
<param name="background" value="white" />
|
||||
<param name="minRuntimeVersion" value="3.0.40624.0" />
|
||||
<param name="autoUpgrade" value="true" />
|
||||
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
|
||||
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
|
||||
</a>
|
||||
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
<%@ ServiceHost Language="C#" Debug="true" Service="Spring.RestSilverlightQuickStart.Services.Service" CodeBehind="Service.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using System.ServiceModel;
|
||||
using System.ServiceModel.Web;
|
||||
using System.ServiceModel.Activation;
|
||||
|
||||
namespace Spring.RestSilverlightQuickStart.Services
|
||||
{
|
||||
[ServiceContract]
|
||||
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
|
||||
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
|
||||
public class Service
|
||||
{
|
||||
private IDictionary<string, string> users;
|
||||
|
||||
public Service()
|
||||
{
|
||||
users = new Dictionary<string, string>();
|
||||
users.Add("1", "Bruno Baïa");
|
||||
users.Add("2", "Marie Baia");
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebGet(UriTemplate = "user/{id}")]
|
||||
public string GetUser(string id)
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
if (!users.ContainsKey(id))
|
||||
{
|
||||
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
|
||||
return null;
|
||||
}
|
||||
|
||||
return users[id];
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebGet(UriTemplate = "users")]
|
||||
public string GetUsersCount()
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
return users.Count.ToString();
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(UriTemplate = "user", Method = "POST")]
|
||||
public string Post(Stream stream)
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
|
||||
UriTemplate template = new UriTemplate("/user/{id}");
|
||||
|
||||
string id = (users.Count + 1).ToString(); // generate new ID
|
||||
string name;
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
name = reader.ReadToEnd();
|
||||
}
|
||||
|
||||
if (String.IsNullOrEmpty(name))
|
||||
{
|
||||
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
|
||||
context.OutgoingResponse.StatusDescription = "Content cannot be null or empty";
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
users.Add(id, name);
|
||||
|
||||
Uri uri = template.BindByPosition(match.BaseUri, id);
|
||||
context.OutgoingResponse.SetStatusAsCreated(uri);
|
||||
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", id, name);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(UriTemplate = "user/{id}", Method = "PUT")]
|
||||
public void Update(string id, Stream stream)
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
if (!users.ContainsKey(id))
|
||||
{
|
||||
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
|
||||
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' does not exist", id);
|
||||
return;
|
||||
}
|
||||
|
||||
string name;
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
name = reader.ReadToEnd();
|
||||
}
|
||||
users[id] = name;
|
||||
|
||||
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
|
||||
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' updated with '{1}'", id, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,84 @@
|
||||
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>9.0.30729</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{AFE006E7-F67F-45F9-826C-1273791D1574}</ProjectGuid>
|
||||
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.RestSilverlightQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.RestSilverlightQuickStart.Web</AssemblyName>
|
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
|
||||
<SilverlightApplicationList>{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}|..\Spring.RestSilverlightQuickStart\Spring.RestSilverlightQuickStart.csproj|ClientBin|False</SilverlightApplicationList>
|
||||
<TargetFrameworkSubset>Full</TargetFrameworkSubset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="ClientBin\Spring.RestSilverlightQuickStart.xap" />
|
||||
<Content Include="Services\Service.svc" />
|
||||
<Content Include="Silverlight.js" />
|
||||
<Content Include="Default.aspx" />
|
||||
<Content Include="Default.html" />
|
||||
<Content Include="Web.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Services\Service.svc.cs">
|
||||
<DependentUpon>Service.svc</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.ServiceModel">
|
||||
<RequiredTargetFramework>3.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="System.ServiceModel.Web">
|
||||
<RequiredTargetFramework>3.5</RequiredTargetFramework>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<UseIIS>False</UseIIS>
|
||||
<AutoAssignPort>False</AutoAssignPort>
|
||||
<DevelopmentServerPort>12345</DevelopmentServerPort>
|
||||
<DevelopmentServerVPath>/</DevelopmentServerVPath>
|
||||
<IISUrl>
|
||||
</IISUrl>
|
||||
<NTLMAuthentication>False</NTLMAuthentication>
|
||||
<UseCustomServer>False</UseCustomServer>
|
||||
<CustomServerUrl>
|
||||
</CustomServerUrl>
|
||||
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,38 @@
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ProjectView>ProjectFiles</ProjectView>
|
||||
</PropertyGroup>
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<StartPageUrl>Default.aspx</StartPageUrl>
|
||||
<StartAction>SpecificPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<SilverlightDebugging>True</SilverlightDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<PublishCopyOption>RunFiles</PublishCopyOption>
|
||||
<PublishTargetLocation>
|
||||
</PublishTargetLocation>
|
||||
<PublishDeleteAllFiles>False</PublishDeleteAllFiles>
|
||||
<PublishCopyAppData>True</PublishCopyAppData>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<EnableENC>False</EnableENC>
|
||||
<AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
|
||||
<EnableWcfTestClientForSVC>False</EnableWcfTestClientForSVC>
|
||||
<ProjectOutputReferences>
|
||||
<Ref Project="{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}" Folder="ClientBin">Spring.RestSilverlightQuickStart.xap</Ref>
|
||||
</ProjectOutputReferences>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,126 @@
|
||||
<?xml version="1.0"?>
|
||||
<configuration>
|
||||
<configSections>
|
||||
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
|
||||
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
|
||||
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
|
||||
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
|
||||
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
|
||||
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
|
||||
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
|
||||
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
|
||||
</sectionGroup>
|
||||
</sectionGroup>
|
||||
</sectionGroup>
|
||||
</configSections>
|
||||
<appSettings/>
|
||||
<connectionStrings/>
|
||||
<system.web>
|
||||
<!--
|
||||
Définissez compilation debug="true" pour insérer des symboles
|
||||
de débogage dans la page compilée. Comme ceci
|
||||
affecte les performances, définissez cette valeur à true uniquement
|
||||
lors du développement.
|
||||
-->
|
||||
<compilation debug="true">
|
||||
<assemblies>
|
||||
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
|
||||
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
|
||||
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
|
||||
</assemblies>
|
||||
</compilation>
|
||||
<!--
|
||||
La section <authentication> permet la configuration
|
||||
du mode d'authentification de sécurité utilisé par
|
||||
ASP.NET pour identifier un utilisateur entrant.
|
||||
-->
|
||||
<authentication mode="Windows"/>
|
||||
<!--
|
||||
La section <customErrors> permet de configurer
|
||||
les actions à exécuter si/quand une erreur non gérée se produit
|
||||
lors de l'exécution d'une demande. Plus précisément,
|
||||
elle permet aux développeurs de configurer les pages d'erreur html
|
||||
pour qu'elles s'affichent à la place d'une trace de la pile d'erreur.
|
||||
|
||||
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
|
||||
<error statusCode="403" redirect="NoAccess.htm" />
|
||||
<error statusCode="404" redirect="FileNotFound.htm" />
|
||||
</customErrors>
|
||||
-->
|
||||
<pages>
|
||||
<controls>
|
||||
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
</controls>
|
||||
</pages>
|
||||
<httpHandlers>
|
||||
<remove verb="*" path="*.asmx"/>
|
||||
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
|
||||
</httpHandlers>
|
||||
<httpModules>
|
||||
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
</httpModules>
|
||||
</system.web>
|
||||
<system.codedom>
|
||||
<compilers>
|
||||
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
|
||||
<providerOption name="CompilerVersion" value="v3.5"/>
|
||||
<providerOption name="WarnAsError" value="false"/>
|
||||
</compiler>
|
||||
</compilers>
|
||||
</system.codedom>
|
||||
<!--
|
||||
La section system.webServer est requise pour exécuter ASP.NET AJAX sur Internet
|
||||
Information Services 7.0. Elle n'est pas nécessaire pour les versions précédentes d'IIS.
|
||||
-->
|
||||
<system.webServer>
|
||||
<validation validateIntegratedModeConfiguration="false"/>
|
||||
<modules>
|
||||
<remove name="ScriptModule"/>
|
||||
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
</modules>
|
||||
<handlers>
|
||||
<remove name="WebServiceHandlerFactory-Integrated"/>
|
||||
<remove name="ScriptHandlerFactory"/>
|
||||
<remove name="ScriptHandlerFactoryAppServices"/>
|
||||
<remove name="ScriptResource"/>
|
||||
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
|
||||
</handlers>
|
||||
</system.webServer>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
|
||||
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
|
||||
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<!--<system.serviceModel>
|
||||
<services>
|
||||
<service behaviorConfiguration="Default" name="Spring.RestSilverlightQuickStart.Services.Service">
|
||||
<endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="Spring.RestSilverlightQuickStart.Services.IService" />
|
||||
</service>
|
||||
</services>
|
||||
<behaviors>
|
||||
<endpointBehaviors>
|
||||
<behavior name="webBehavior">
|
||||
<webHttp />
|
||||
</behavior>
|
||||
</endpointBehaviors>
|
||||
<serviceBehaviors>
|
||||
<behavior name="Default">
|
||||
<serviceMetadata httpGetEnabled="true"/>
|
||||
</behavior>
|
||||
</serviceBehaviors>
|
||||
</behaviors>
|
||||
</system.serviceModel>-->
|
||||
</configuration>
|
||||
@@ -0,0 +1,74 @@
|
||||
<%@ Page Language="C#" AutoEventWireup="true" %>
|
||||
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" >
|
||||
<head runat="server">
|
||||
<title>Spring.RestSilverlightQuickStart</title>
|
||||
<style type="text/css">
|
||||
html, body {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#silverlightControlHost {
|
||||
height: 100%;
|
||||
text-align:center;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript" src="Silverlight.js"></script>
|
||||
<script type="text/javascript">
|
||||
function onSilverlightError(sender, args) {
|
||||
var appSource = "";
|
||||
if (sender != null && sender != 0) {
|
||||
appSource = sender.getHost().Source;
|
||||
}
|
||||
|
||||
var errorType = args.ErrorType;
|
||||
var iErrorCode = args.ErrorCode;
|
||||
|
||||
if (errorType == "ImageError" || errorType == "MediaError") {
|
||||
return;
|
||||
}
|
||||
|
||||
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
|
||||
|
||||
errMsg += "Code: "+ iErrorCode + " \n";
|
||||
errMsg += "Category: " + errorType + " \n";
|
||||
errMsg += "Message: " + args.ErrorMessage + " \n";
|
||||
|
||||
if (errorType == "ParserError") {
|
||||
errMsg += "File: " + args.xamlFile + " \n";
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
else if (errorType == "RuntimeError") {
|
||||
if (args.lineNumber != 0) {
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
errMsg += "MethodName: " + args.methodName + " \n";
|
||||
}
|
||||
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form1" runat="server" style="height:100%">
|
||||
<div id="silverlightControlHost">
|
||||
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
|
||||
<param name="source" value="ClientBin/Spring.RestSilverlightQuickStart.xap"/>
|
||||
<param name="onError" value="onSilverlightError" />
|
||||
<param name="background" value="white" />
|
||||
<param name="minRuntimeVersion" value="4.0.50826.0" />
|
||||
<param name="autoUpgrade" value="true" />
|
||||
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
|
||||
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
|
||||
</a>
|
||||
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,73 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" >
|
||||
|
||||
<head>
|
||||
<title>Spring.RestSilverlightQuickStart</title>
|
||||
<style type="text/css">
|
||||
html, body {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
#silverlightControlHost {
|
||||
height: 100%;
|
||||
text-align:center;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript" src="Silverlight.js"></script>
|
||||
<script type="text/javascript">
|
||||
function onSilverlightError(sender, args) {
|
||||
var appSource = "";
|
||||
if (sender != null && sender != 0) {
|
||||
appSource = sender.getHost().Source;
|
||||
}
|
||||
|
||||
var errorType = args.ErrorType;
|
||||
var iErrorCode = args.ErrorCode;
|
||||
|
||||
if (errorType == "ImageError" || errorType == "MediaError") {
|
||||
return;
|
||||
}
|
||||
|
||||
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
|
||||
|
||||
errMsg += "Code: "+ iErrorCode + " \n";
|
||||
errMsg += "Category: " + errorType + " \n";
|
||||
errMsg += "Message: " + args.ErrorMessage + " \n";
|
||||
|
||||
if (errorType == "ParserError") {
|
||||
errMsg += "File: " + args.xamlFile + " \n";
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
else if (errorType == "RuntimeError") {
|
||||
if (args.lineNumber != 0) {
|
||||
errMsg += "Line: " + args.lineNumber + " \n";
|
||||
errMsg += "Position: " + args.charPosition + " \n";
|
||||
}
|
||||
errMsg += "MethodName: " + args.methodName + " \n";
|
||||
}
|
||||
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form1" runat="server" style="height:100%">
|
||||
<div id="silverlightControlHost">
|
||||
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
|
||||
<param name="source" value="ClientBin/Spring.RestSilverlightQuickStart.xap"/>
|
||||
<param name="onError" value="onSilverlightError" />
|
||||
<param name="background" value="white" />
|
||||
<param name="minRuntimeVersion" value="4.0.50826.0" />
|
||||
<param name="autoUpgrade" value="true" />
|
||||
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
|
||||
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
|
||||
</a>
|
||||
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
<%@ ServiceHost Language="C#" Debug="true" Service="Spring.RestSilverlightQuickStart.Services.Service" CodeBehind="Service.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Collections.Generic;
|
||||
using System.ServiceModel;
|
||||
using System.ServiceModel.Web;
|
||||
using System.ServiceModel.Channels;
|
||||
using System.ServiceModel.Activation;
|
||||
|
||||
namespace Spring.RestSilverlightQuickStart.Services
|
||||
{
|
||||
[ServiceContract]
|
||||
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
|
||||
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
|
||||
public class Service // : IService
|
||||
{
|
||||
private IDictionary<string, string> users;
|
||||
|
||||
public Service()
|
||||
{
|
||||
users = new Dictionary<string, string>();
|
||||
users.Add("1", "Bruno Baïa");
|
||||
users.Add("2", "Marie Baia");
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebGet(UriTemplate = "user/{id}")]
|
||||
public Message GetUser(string id)
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
if (!users.ContainsKey(id))
|
||||
{
|
||||
context.OutgoingResponse.SetStatusAsNotFound(String.Format("User with id '{0}' not found", id));
|
||||
return context.CreateTextResponse(null);
|
||||
}
|
||||
|
||||
return context.CreateTextResponse(users[id]);
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebGet(UriTemplate = "users")]
|
||||
public Message GetUsersCount()
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
return context.CreateTextResponse(users.Count.ToString());
|
||||
}
|
||||
|
||||
[OperationContract]
|
||||
[WebInvoke(UriTemplate = "user", Method = "POST")]
|
||||
public Message Post(Stream stream)
|
||||
{
|
||||
WebOperationContext context = WebOperationContext.Current;
|
||||
|
||||
UriTemplateMatch match = context.IncomingRequest.UriTemplateMatch;
|
||||
UriTemplate template = new UriTemplate("/user/{id}");
|
||||
|
||||
string id = (users.Count + 1).ToString(); // generate new ID
|
||||
string name;
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
name = reader.ReadToEnd();
|
||||
}
|
||||
|
||||
if (String.IsNullOrEmpty(name))
|
||||
{
|
||||
context.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
|
||||
context.OutgoingResponse.StatusDescription = "Content cannot be null or empty";
|
||||
return WebOperationContext.Current.CreateTextResponse("");
|
||||
}
|
||||
|
||||
users.Add(id, name);
|
||||
|
||||
Uri uri = template.BindByPosition(match.BaseUri, id);
|
||||
context.OutgoingResponse.SetStatusAsCreated(uri);
|
||||
context.OutgoingResponse.StatusDescription = String.Format("User id '{0}' created with '{1}'", id, name);
|
||||
|
||||
return WebOperationContext.Current.CreateTextResponse(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,87 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>
|
||||
</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{2B40C3B9-E032-417A-9B6F-8AD4ECEE0397}</ProjectGuid>
|
||||
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.RestSilverlightQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.RestSilverlightQuickStart.Web</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<SilverlightApplicationList>{C11BD449-683C-44CA-B394-CC126DC49EF1}|..\Spring.RestSilverlightQuickStart\Spring.RestSilverlightQuickStart.csproj|ClientBin|False</SilverlightApplicationList>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="ClientBin\Spring.RestSilverlightQuickStart.xap" />
|
||||
<Content Include="Services\Service.svc" />
|
||||
<Content Include="Silverlight.js" />
|
||||
<Content Include="Default.aspx" />
|
||||
<Content Include="Default.html" />
|
||||
<Content Include="Web.config" />
|
||||
<Content Include="Web.Debug.config">
|
||||
<DependentUpon>Web.config</DependentUpon>
|
||||
</Content>
|
||||
<Content Include="Web.Release.config">
|
||||
<DependentUpon>Web.config</DependentUpon>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Services\Service.svc.cs">
|
||||
<DependentUpon>Service.svc</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.ServiceModel" />
|
||||
<Reference Include="System.ServiceModel.Web" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<UseIIS>False</UseIIS>
|
||||
<AutoAssignPort>False</AutoAssignPort>
|
||||
<DevelopmentServerPort>12345</DevelopmentServerPort>
|
||||
<DevelopmentServerVPath>/</DevelopmentServerVPath>
|
||||
<IISUrl>
|
||||
</IISUrl>
|
||||
<NTLMAuthentication>False</NTLMAuthentication>
|
||||
<UseCustomServer>False</UseCustomServer>
|
||||
<CustomServerUrl>
|
||||
</CustomServerUrl>
|
||||
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ProjectView>ProjectFiles</ProjectView>
|
||||
</PropertyGroup>
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<StartPageUrl>Default.aspx</StartPageUrl>
|
||||
<StartAction>SpecificPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<SilverlightDebugging>True</SilverlightDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<EnableENC>False</EnableENC>
|
||||
<AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
|
||||
<ProjectOutputReferences>
|
||||
<Ref Project="{C11BD449-683C-44CA-B394-CC126DC49EF1}" Folder="ClientBin">Spring.RestSilverlightQuickStart.xap</Ref>
|
||||
</ProjectOutputReferences>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
In the example below, the "SetAttributes" transform will change the value of
|
||||
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
|
||||
finds an atrribute "name" that has a value of "MyDB".
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<!--
|
||||
In the example below, the "Replace" transform will replace the entire
|
||||
<customErrors> section of your web.config file.
|
||||
Note that because there is only one customErrors section under the
|
||||
<system.web> node, there is no need to use the "xdt:Locator" attribute.
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
In the example below, the "SetAttributes" transform will change the value of
|
||||
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
|
||||
finds an atrribute "name" that has a value of "MyDB".
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<compilation xdt:Transform="RemoveAttributes(debug)" />
|
||||
<!--
|
||||
In the example below, the "Replace" transform will replace the entire
|
||||
<customErrors> section of your web.config file.
|
||||
Note that because there is only one customErrors section under the
|
||||
<system.web> node, there is no need to use the "xdt:Locator" attribute.
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<!--
|
||||
For more information on how to configure your ASP.NET application, please visit
|
||||
http://go.microsoft.com/fwlink/?LinkId=169433
|
||||
-->
|
||||
|
||||
<configuration>
|
||||
<system.web>
|
||||
<compilation debug="true" targetFramework="4.0" />
|
||||
</system.web>
|
||||
|
||||
<system.serviceModel>
|
||||
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
|
||||
<standardEndpoints>
|
||||
<webHttpEndpoint>
|
||||
<!--
|
||||
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
|
||||
via the attributes on the <standardEndpoint> element below
|
||||
-->
|
||||
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
|
||||
</webHttpEndpoint>
|
||||
</standardEndpoints>
|
||||
</system.serviceModel>
|
||||
|
||||
</configuration>
|
||||
@@ -0,0 +1,8 @@
|
||||
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="Spring.RestSilverlightQuickStart.App"
|
||||
>
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace Spring.RestSilverlightQuickStart
|
||||
{
|
||||
public partial class App : Application
|
||||
{
|
||||
|
||||
public App()
|
||||
{
|
||||
this.Startup += this.Application_Startup;
|
||||
this.Exit += this.Application_Exit;
|
||||
this.UnhandledException += this.Application_UnhandledException;
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void Application_Startup(object sender, StartupEventArgs e)
|
||||
{
|
||||
this.RootVisual = new MainPage();
|
||||
}
|
||||
|
||||
private void Application_Exit(object sender, EventArgs e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
|
||||
{
|
||||
// If the app is running outside of the debugger then report the exception using
|
||||
// the browser's exception mechanism. On IE this will display it a yellow alert
|
||||
// icon in the status bar and Firefox will display a script error.
|
||||
if (!System.Diagnostics.Debugger.IsAttached)
|
||||
{
|
||||
|
||||
// NOTE: This will allow the application to continue running after an exception has been thrown
|
||||
// but not handled.
|
||||
// For production applications this error handling should be replaced with something that will
|
||||
// report the error to the website and stop the application.
|
||||
e.Handled = true;
|
||||
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
|
||||
}
|
||||
}
|
||||
|
||||
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
|
||||
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
|
||||
|
||||
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<UserControl x:Class="Spring.RestSilverlightQuickStart.MainPage"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="600">
|
||||
<Grid x:Name="LayoutRoot" Background="White">
|
||||
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal" VerticalAlignment="Top">
|
||||
<TextBox Name="TwitterNameTextBox" Width="120" />
|
||||
<Button Name="Button" Width="50" Content="GET" Click="Button_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock Height="570" HorizontalAlignment="Left" Margin="0,30,0,0" Name="TextBlock" VerticalAlignment="Top" Width="800" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Net.Browser;
|
||||
|
||||
using Spring.Http.Rest;
|
||||
|
||||
namespace Spring.RestSilverlightQuickStart
|
||||
{
|
||||
public partial class MainPage : UserControl
|
||||
{
|
||||
public MainPage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void Button_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
RestTemplate rt = new RestTemplate("http://localhost:12345/Services/Service.svc/");
|
||||
|
||||
rt.PostForMessageAsync<string>("user", "Lisa Baia", new string[] { },
|
||||
r =>
|
||||
{
|
||||
if (r.Error != null)
|
||||
{
|
||||
TextBlock.Text = r.Error.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
TextBlock.Text = String.Format("{0}; {1}; {2}; {3}",
|
||||
r.Response.Body, r.Response.Headers.Location, r.Response.StatusCode, r.Response.StatusDescription);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
>
|
||||
<Deployment.Parts>
|
||||
</Deployment.Parts>
|
||||
</Deployment>
|
||||
@@ -0,0 +1,103 @@
|
||||
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>9.0.30729</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{0B34E41F-8D4E-427A-A7C4-A3F9ADEE8EB3}</ProjectGuid>
|
||||
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.RestSilverlightQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.RestSilverlightQuickStart</AssemblyName>
|
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
|
||||
<SilverlightApplication>true</SilverlightApplication>
|
||||
<SupportedCultures>fr</SupportedCultures>
|
||||
<XapOutputs>true</XapOutputs>
|
||||
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
|
||||
<XapFilename>Spring.RestSilverlightQuickStart.xap</XapFilename>
|
||||
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
|
||||
<SilverlightAppEntry>Spring.RestSilverlightQuickStart.App</SilverlightAppEntry>
|
||||
<TestPageFileName>TestPage.html</TestPageFileName>
|
||||
<CreateTestPage>true</CreateTestPage>
|
||||
<ValidateXaml>true</ValidateXaml>
|
||||
<EnableOutOfBrowser>false</EnableOutOfBrowser>
|
||||
<OutOfBrowserSettingsFile>Properties\OutOfBrowserSettings.xml</OutOfBrowserSettingsFile>
|
||||
<UsePlatformExtensions>false</UsePlatformExtensions>
|
||||
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
|
||||
<LinkedServerProject>
|
||||
</LinkedServerProject>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>Bin\Debug</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;SILVERLIGHT</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>Bin\Release</OutputPath>
|
||||
<DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Windows" />
|
||||
<Reference Include="mscorlib" />
|
||||
<Reference Include="system" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Net" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Windows.Browser" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="MainPage.xaml.cs">
|
||||
<DependentUpon>MainPage.xaml</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:MarkupCompilePass1</Generator>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="MainPage.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:MarkupCompilePass1</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Properties\AppManifest.xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Spring\Spring.Http\Spring.Http.2008-SL.csproj">
|
||||
<Project>{5A955F0B-EEC7-427C-9E6B-A26B8B51558D}</Project>
|
||||
<Name>Spring.Http.2008-SL</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
|
||||
<SilverlightProjectProperties />
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ProjectView>ProjectFiles</ProjectView>
|
||||
</PropertyGroup>
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
|
||||
<SilverlightProjectProperties>
|
||||
<StartPageUrl>
|
||||
</StartPageUrl>
|
||||
<StartAction>DynamicPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<ShowWebRefOnDebugPrompt>True</ShowWebRefOnDebugPrompt>
|
||||
<OutOfBrowserProjectToDebug>Spring.RestSilverlightQuickStart.Web.2008</OutOfBrowserProjectToDebug>
|
||||
<ShowRiaSvcsOnDebugPrompt>True</ShowRiaSvcsOnDebugPrompt>
|
||||
</SilverlightProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.50727</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{C11BD449-683C-44CA-B394-CC126DC49EF1}</ProjectGuid>
|
||||
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.RestSilverlightQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.RestSilverlightQuickStart</AssemblyName>
|
||||
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
|
||||
<SilverlightApplication>true</SilverlightApplication>
|
||||
<SupportedCultures>
|
||||
</SupportedCultures>
|
||||
<XapOutputs>true</XapOutputs>
|
||||
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
|
||||
<XapFilename>Spring.RestSilverlightQuickStart.xap</XapFilename>
|
||||
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
|
||||
<SilverlightAppEntry>Spring.RestSilverlightQuickStart.App</SilverlightAppEntry>
|
||||
<TestPageFileName>Spring.RestSilverlightQuickStartTestPage.html</TestPageFileName>
|
||||
<CreateTestPage>true</CreateTestPage>
|
||||
<ValidateXaml>true</ValidateXaml>
|
||||
<EnableOutOfBrowser>false</EnableOutOfBrowser>
|
||||
<OutOfBrowserSettingsFile>Properties\OutOfBrowserSettings.xml</OutOfBrowserSettingsFile>
|
||||
<UsePlatformExtensions>false</UsePlatformExtensions>
|
||||
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
|
||||
<LinkedServerProject>
|
||||
</LinkedServerProject>
|
||||
</PropertyGroup>
|
||||
<!-- This property group is only here to support building this project using the
|
||||
MSBuild 3.5 toolset. In order to work correctly with this older toolset, it needs
|
||||
to set the TargetFrameworkVersion to v3.5 -->
|
||||
<PropertyGroup Condition="'$(MSBuildToolsVersion)' == '3.5'">
|
||||
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>Bin\Debug</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;SILVERLIGHT</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>Bin\Release</OutputPath>
|
||||
<DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="mscorlib" />
|
||||
<Reference Include="System.Windows" />
|
||||
<Reference Include="system" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Net" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Windows.Browser" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="MainPage.xaml.cs">
|
||||
<DependentUpon>MainPage.xaml</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="MainPage.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Properties\AppManifest.xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Spring\Spring.Http\Spring.Http.2010-SL.csproj">
|
||||
<Project>{01FA5AEB-20A3-42FF-B2E9-A2FE9A7236D1}</Project>
|
||||
<Name>Spring.Http.2010-SL</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\$(SilverlightVersion)\Microsoft.Silverlight.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
|
||||
<SilverlightProjectProperties />
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
|
||||
<SilverlightProjectProperties>
|
||||
<StartPageUrl>
|
||||
</StartPageUrl>
|
||||
<StartAction>DynamicPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<ShowWebRefOnDebugPrompt>True</ShowWebRefOnDebugPrompt>
|
||||
<OutOfBrowserProjectToDebug>
|
||||
</OutOfBrowserProjectToDebug>
|
||||
<ShowRiaSvcsOnDebugPrompt>True</ShowRiaSvcsOnDebugPrompt>
|
||||
</SilverlightProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 11.00
|
||||
# Visual Studio 2010 Express for Windows Phone
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.RestWindowsPhoneQuickStart.2010", "src\Spring.RestWindowsPhoneQuickStart.2010.csproj", "{0D706C31-4D8C-468A-A49F-073AC3E23D3F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.2010-WP", "..\..\..\src\Spring\Spring.Http\Spring.Http.2010-WP.csproj", "{36227431-B822-461E-A7AF-651E34F23A8C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spring.Http.Tests.2010-WP", "..\..\..\test\Spring\Spring.Http.Tests\Spring.Http.Tests.2010-WP.csproj", "{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0D706C31-4D8C-468A-A49F-073AC3E23D3F}.Release|Any CPU.Deploy.0 = Release|Any CPU
|
||||
{36227431-B822-461E-A7AF-651E34F23A8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{36227431-B822-461E-A7AF-651E34F23A8C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{36227431-B822-461E-A7AF-651E34F23A8C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{36227431-B822-461E-A7AF-651E34F23A8C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{83D8AF31-6DF1-4D2F-BFD2-865E91E6976E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,19 @@
|
||||
<Application
|
||||
x:Class="Spring.RestWindowsPhoneQuickStart.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
|
||||
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
|
||||
|
||||
<!--Application Resources-->
|
||||
<Application.Resources>
|
||||
</Application.Resources>
|
||||
|
||||
<Application.ApplicationLifetimeObjects>
|
||||
<!--Required object that handles lifetime events for the application-->
|
||||
<shell:PhoneApplicationService
|
||||
Launching="Application_Launching" Closing="Application_Closing"
|
||||
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
|
||||
</Application.ApplicationLifetimeObjects>
|
||||
|
||||
</Application>
|
||||
@@ -0,0 +1,135 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
using Microsoft.Phone.Controls;
|
||||
using Microsoft.Phone.Shell;
|
||||
|
||||
namespace Spring.RestWindowsPhoneQuickStart
|
||||
{
|
||||
public partial class App : Application
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides easy access to the root frame of the Phone Application.
|
||||
/// </summary>
|
||||
/// <returns>The root frame of the Phone Application.</returns>
|
||||
public PhoneApplicationFrame RootFrame { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for the Application object.
|
||||
/// </summary>
|
||||
public App()
|
||||
{
|
||||
// Global handler for uncaught exceptions.
|
||||
UnhandledException += Application_UnhandledException;
|
||||
|
||||
// Show graphics profiling information while debugging.
|
||||
if (System.Diagnostics.Debugger.IsAttached)
|
||||
{
|
||||
// Display the current frame rate counters.
|
||||
Application.Current.Host.Settings.EnableFrameRateCounter = true;
|
||||
|
||||
// Show the areas of the app that are being redrawn in each frame.
|
||||
//Application.Current.Host.Settings.EnableRedrawRegions = true;
|
||||
|
||||
// Enable non-production analysis visualization mode,
|
||||
// which shows areas of a page that are being GPU accelerated with a colored overlay.
|
||||
//Application.Current.Host.Settings.EnableCacheVisualization = true;
|
||||
}
|
||||
|
||||
// Standard Silverlight initialization
|
||||
InitializeComponent();
|
||||
|
||||
// Phone-specific initialization
|
||||
InitializePhoneApplication();
|
||||
}
|
||||
|
||||
// Code to execute when the application is launching (eg, from Start)
|
||||
// This code will not execute when the application is reactivated
|
||||
private void Application_Launching(object sender, LaunchingEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
// Code to execute when the application is activated (brought to foreground)
|
||||
// This code will not execute when the application is first launched
|
||||
private void Application_Activated(object sender, ActivatedEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
// Code to execute when the application is deactivated (sent to background)
|
||||
// This code will not execute when the application is closing
|
||||
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
// Code to execute when the application is closing (eg, user hit Back)
|
||||
// This code will not execute when the application is deactivated
|
||||
private void Application_Closing(object sender, ClosingEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
// Code to execute if a navigation fails
|
||||
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
|
||||
{
|
||||
if (System.Diagnostics.Debugger.IsAttached)
|
||||
{
|
||||
// A navigation has failed; break into the debugger
|
||||
System.Diagnostics.Debugger.Break();
|
||||
}
|
||||
}
|
||||
|
||||
// Code to execute on Unhandled Exceptions
|
||||
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
|
||||
{
|
||||
if (System.Diagnostics.Debugger.IsAttached)
|
||||
{
|
||||
// An unhandled exception has occurred; break into the debugger
|
||||
System.Diagnostics.Debugger.Break();
|
||||
}
|
||||
}
|
||||
|
||||
#region Phone application initialization
|
||||
|
||||
// Avoid double-initialization
|
||||
private bool phoneApplicationInitialized = false;
|
||||
|
||||
// Do not add any additional code to this method
|
||||
private void InitializePhoneApplication()
|
||||
{
|
||||
if (phoneApplicationInitialized)
|
||||
return;
|
||||
|
||||
// Create the frame but don't set it as RootVisual yet; this allows the splash
|
||||
// screen to remain active until the application is ready to render.
|
||||
RootFrame = new PhoneApplicationFrame();
|
||||
RootFrame.Navigated += CompleteInitializePhoneApplication;
|
||||
|
||||
// Handle navigation failures
|
||||
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
|
||||
|
||||
// Ensure we don't initialize again
|
||||
phoneApplicationInitialized = true;
|
||||
}
|
||||
|
||||
// Do not add any additional code to this method
|
||||
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
|
||||
{
|
||||
// Set the root visual to allow the application to render
|
||||
if (RootVisual != RootFrame)
|
||||
RootVisual = RootFrame;
|
||||
|
||||
// Remove this handler since it is no longer needed
|
||||
RootFrame.Navigated -= CompleteInitializePhoneApplication;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,60 @@
|
||||
<phone:PhoneApplicationPage
|
||||
x:Class="Spring.RestWindowsPhoneQuickStart.MainPage"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
|
||||
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
|
||||
FontFamily="{StaticResource PhoneFontFamilyNormal}"
|
||||
FontSize="{StaticResource PhoneFontSizeNormal}"
|
||||
Foreground="{StaticResource PhoneForegroundBrush}"
|
||||
SupportedOrientations="Portrait" Orientation="Portrait"
|
||||
shell:SystemTray.IsVisible="True">
|
||||
|
||||
<!--LayoutRoot is the root grid where all page content is placed-->
|
||||
<Grid x:Name="LayoutRoot" Background="Transparent">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!--TitlePanel contains the name of the application and page title-->
|
||||
<StackPanel x:Name="TitlePanel" Grid.Row="0">
|
||||
<TextBlock x:Name="ApplicationTitle" Text="TWITTER" HorizontalAlignment="Center" Style="{StaticResource PhoneTextNormalStyle}"/>
|
||||
</StackPanel>
|
||||
|
||||
<!--ContentPanel - place additional content here-->
|
||||
<StackPanel x:Name="ContentPanel" Grid.Row="1" Orientation="Vertical">
|
||||
<TextBox Name="TwitterAccountTextBox" Text="SpringForNet" />
|
||||
<Button Content="GET" Name="GetButton" Width="200" HorizontalAlignment="Center" Click="GetButton_Click" />
|
||||
<ListBox Name="StatusesListBox" Height="450">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal" Height="132">
|
||||
<Image Source="{Binding Path='User.ImageUrl'}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
|
||||
<StackPanel Width="370">
|
||||
<TextBlock Text="{Binding Path='User.ScreenName'}" Foreground="#FFC8AB14" FontSize="28" />
|
||||
<TextBlock Text="{Binding Text}" TextWrapping="Wrap" FontSize="24" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!--Sample code showing usage of ApplicationBar-->
|
||||
<!--<phone:PhoneApplicationPage.ApplicationBar>
|
||||
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
|
||||
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
|
||||
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
|
||||
<shell:ApplicationBar.MenuItems>
|
||||
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
|
||||
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
|
||||
</shell:ApplicationBar.MenuItems>
|
||||
</shell:ApplicationBar>
|
||||
</phone:PhoneApplicationPage.ApplicationBar>-->
|
||||
|
||||
</phone:PhoneApplicationPage>
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization;
|
||||
using Microsoft.Phone.Controls;
|
||||
|
||||
using Spring.Http.Client;
|
||||
using Spring.Http.Rest;
|
||||
|
||||
namespace Spring.RestWindowsPhoneQuickStart
|
||||
{
|
||||
public partial class MainPage : PhoneApplicationPage
|
||||
{
|
||||
// Constructor
|
||||
public MainPage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void GetButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
RestTemplate rt = new RestTemplate("http://twitter.com");
|
||||
|
||||
rt.GetForObjectAsync<TwitterStatuses>("/statuses/user_timeline.xml?screen_name={name}", new string[] { this.TwitterAccountTextBox.Text },
|
||||
args =>
|
||||
{
|
||||
if (args.Error == null)
|
||||
{
|
||||
this.StatusesListBox.ItemsSource = args.Response;
|
||||
}
|
||||
});
|
||||
|
||||
//rt.GetForObjectAsync<XElement>("/1/statuses/user_timeline.xml?screen_name={name}", new string[] { this.TwitterAccountTextBox.Text },
|
||||
// args =>
|
||||
// {
|
||||
// if (args.Error == null)
|
||||
// {
|
||||
// this.StatusesListBox.ItemsSource = from tweet in args.Response.Descendants("status")
|
||||
// select new TwitterItem
|
||||
// {
|
||||
// ImageSource = tweet.Element("user").Element("profile_image_url").Value,
|
||||
// Message = tweet.Element("text").Value,
|
||||
// UserName = tweet.Element("user").Element("screen_name").Value
|
||||
// };
|
||||
// }
|
||||
// });
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDataContract(Name="statuses", ItemName="status", Namespace="")]
|
||||
public class TwitterStatuses : List<TwitterStatus>
|
||||
{
|
||||
}
|
||||
|
||||
[DataContract(Name = "status", Namespace = "")]
|
||||
public class TwitterStatus
|
||||
{
|
||||
[DataMember(Name="text")]
|
||||
public string Text { get; set; }
|
||||
|
||||
[DataMember(Name = "user")]
|
||||
public TwitterUser User { get; set; }
|
||||
}
|
||||
|
||||
[DataContract(Name="user", Namespace="")]
|
||||
public class TwitterUser
|
||||
{
|
||||
[DataMember(Name = "screen_name")]
|
||||
public string ScreenName { get; set; }
|
||||
|
||||
[DataMember(Name = "profile_image_url")]
|
||||
public string ImageUrl { get; set; }
|
||||
}
|
||||
|
||||
public class TwitterItem
|
||||
{
|
||||
public string UserName { get; set; }
|
||||
public string Message { get; set; }
|
||||
public string ImageSource { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
>
|
||||
<Deployment.Parts>
|
||||
</Deployment.Parts>
|
||||
</Deployment>
|
||||
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
|
||||
<App xmlns="" ProductID="{159b8a28-8643-4320-9978-b2fba126b989}" Title="Spring.RestWindowsPhoneQuickStart" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="Spring.RestWindowsPhoneQuickStart author" Description="Sample description" Publisher="Spring.RestWindowsPhoneQuickStart">
|
||||
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
|
||||
<Capabilities>
|
||||
<Capability Name="ID_CAP_GAMERSERVICES"/>
|
||||
<Capability Name="ID_CAP_IDENTITY_DEVICE"/>
|
||||
<Capability Name="ID_CAP_IDENTITY_USER"/>
|
||||
<Capability Name="ID_CAP_LOCATION"/>
|
||||
<Capability Name="ID_CAP_MEDIALIB"/>
|
||||
<Capability Name="ID_CAP_MICROPHONE"/>
|
||||
<Capability Name="ID_CAP_NETWORKING"/>
|
||||
<Capability Name="ID_CAP_PHONEDIALER"/>
|
||||
<Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
|
||||
<Capability Name="ID_CAP_SENSORS"/>
|
||||
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
|
||||
</Capabilities>
|
||||
<Tasks>
|
||||
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/>
|
||||
</Tasks>
|
||||
<Tokens>
|
||||
<PrimaryToken TokenID="Spring.RestWindowsPhoneQuickStartToken" TaskName="_default">
|
||||
<TemplateType5>
|
||||
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
|
||||
<Count>0</Count>
|
||||
<Title>Spring.RestWindowsPhoneQuickStart</Title>
|
||||
</TemplateType5>
|
||||
</PrimaryToken>
|
||||
</Tokens>
|
||||
</App>
|
||||
</Deployment>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.2 KiB |
@@ -0,0 +1,108 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>10.0.20506</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{0D706C31-4D8C-468A-A49F-073AC3E23D3F}</ProjectGuid>
|
||||
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Spring.RestWindowsPhoneQuickStart</RootNamespace>
|
||||
<AssemblyName>Spring.RestWindowsPhoneQuickStart</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
|
||||
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
|
||||
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
|
||||
<SilverlightApplication>true</SilverlightApplication>
|
||||
<SupportedCultures>
|
||||
</SupportedCultures>
|
||||
<XapOutputs>true</XapOutputs>
|
||||
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
|
||||
<XapFilename>Spring.RestWindowsPhoneQuickStart.xap</XapFilename>
|
||||
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
|
||||
<SilverlightAppEntry>Spring.RestWindowsPhoneQuickStart.App</SilverlightAppEntry>
|
||||
<ValidateXaml>true</ValidateXaml>
|
||||
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>Bin\Debug</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>Bin\Release</OutputPath>
|
||||
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
|
||||
<NoStdLib>true</NoStdLib>
|
||||
<NoConfig>true</NoConfig>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Phone" />
|
||||
<Reference Include="Microsoft.Phone.Interop" />
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.Windows" />
|
||||
<Reference Include="system" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Net" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="MainPage.xaml.cs">
|
||||
<DependentUpon>MainPage.xaml</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</ApplicationDefinition>
|
||||
<Page Include="MainPage.xaml">
|
||||
<SubType>Designer</SubType>
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Properties\AppManifest.xml" />
|
||||
<None Include="Properties\WMAppManifest.xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="ApplicationIcon.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<Content Include="Background.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<Content Include="SplashScreenImage.jpg" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Spring\Spring.Http\Spring.Http.2010-WP.csproj">
|
||||
<Project>{36227431-B822-461E-A7AF-651E34F23A8C}</Project>
|
||||
<Name>Spring.Http.2010-WP</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
|
||||
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
<ProjectExtensions />
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<FullDeploy>false</FullDeploy>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,160 @@
|
||||
#if SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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;
|
||||
|
||||
namespace Spring.Collections.Specialized
|
||||
{
|
||||
public class NameValueCollection : IEnumerable<string>
|
||||
{
|
||||
private Dictionary<string, List<string>> innerCollection;
|
||||
|
||||
public NameValueCollection()
|
||||
{
|
||||
innerCollection = new Dictionary<string, List<string>>();
|
||||
}
|
||||
|
||||
public NameValueCollection(int capacity)
|
||||
{
|
||||
innerCollection = new Dictionary<string, List<string>>(capacity);
|
||||
}
|
||||
|
||||
public NameValueCollection(IEqualityComparer<string> comparer)
|
||||
{
|
||||
innerCollection = new Dictionary<string, List<string>>(comparer);
|
||||
}
|
||||
|
||||
public NameValueCollection(int capacity, IEqualityComparer<string> comparer)
|
||||
{
|
||||
innerCollection = new Dictionary<string, List<string>>(capacity, comparer);
|
||||
}
|
||||
|
||||
public virtual void Add(string name, string value)
|
||||
{
|
||||
List<string> list;
|
||||
if (!this.innerCollection.TryGetValue(name, out list))
|
||||
{
|
||||
list = new List<string>();
|
||||
}
|
||||
list.Add(value);
|
||||
this.innerCollection[name] = list;
|
||||
}
|
||||
|
||||
public virtual string Get(string name)
|
||||
{
|
||||
string str = null;
|
||||
List<string> list;
|
||||
if (this.innerCollection.TryGetValue(name, out list))
|
||||
{
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
str = list[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
str = str + list[i];
|
||||
}
|
||||
if (i != (list.Count - 1))
|
||||
{
|
||||
str = str + ",";
|
||||
}
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public virtual string[] GetValues(string name)
|
||||
{
|
||||
List<string> list;
|
||||
if (this.innerCollection.TryGetValue(name, out list))
|
||||
{
|
||||
return list.ToArray();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public virtual void Set(string key, string value)
|
||||
{
|
||||
List<string> list = new List<string>();
|
||||
list.Add(value);
|
||||
this.innerCollection[key] = list;
|
||||
}
|
||||
|
||||
public virtual bool Remove(string key)
|
||||
{
|
||||
return this.innerCollection.Remove(key);
|
||||
}
|
||||
|
||||
public virtual string[] AllKeys
|
||||
{
|
||||
get
|
||||
{
|
||||
int count = this.innerCollection.Count;
|
||||
string[] array = new string[count];
|
||||
this.innerCollection.Keys.CopyTo(array, 0);
|
||||
return array;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.innerCollection.Count;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual string this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Get(name);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
#region IEnumerable<string> Membres
|
||||
|
||||
IEnumerator<string> IEnumerable<string>.GetEnumerator()
|
||||
{
|
||||
return this.innerCollection.Keys.GetEnumerator();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IEnumerable Membres
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return this.innerCollection.Keys.GetEnumerator();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,50 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.ComponentModel;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
public class ExecuteCompletedEventArgs : AsyncCompletedEventArgs
|
||||
{
|
||||
private IClientHttpResponse response;
|
||||
|
||||
public IClientHttpResponse Response
|
||||
{
|
||||
get
|
||||
{
|
||||
// Raise an exception if the operation failed or
|
||||
// was canceled.
|
||||
base.RaiseExceptionIfNecessary();
|
||||
|
||||
// If the operation was successful, return the
|
||||
// property value.
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
public ExecuteCompletedEventArgs(IClientHttpResponse response, Exception exception, bool cancelled, object userState)
|
||||
: base(exception, cancelled, userState)
|
||||
{
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
}
|
||||
66
src/Spring/Spring.Http/Http/Client/IClientHttpRequest.cs
Normal file
66
src/Spring/Spring.Http/Http/Client/IClientHttpRequest.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a client-side HTTP request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Created via an implementation of the <see cref="IClientHttpRequestFactory"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A client HTTP request can be executed,
|
||||
/// getting an <see cref="IClientHttpResponse"/> which can be read from.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <seealso cref="IClientHttpRequestFactory"/>
|
||||
/// <seealso cref="IClientHttpResponse"/>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public interface IClientHttpRequest : IHttpOutputMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the HTTP method of the request.
|
||||
/// </summary>
|
||||
HttpMethod Method { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI of the request.
|
||||
/// </summary>
|
||||
Uri Uri { get; }
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Execute this request, resulting in a <see cref="IClientHttpResponse" /> that can be read.
|
||||
/// </summary>
|
||||
/// <returns>The response result of the execution</returns>
|
||||
IClientHttpResponse Execute();
|
||||
#endif
|
||||
|
||||
void ExecuteAsync(object state, Action<ExecuteCompletedEventArgs> executeCompleted);
|
||||
|
||||
void CancelAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,20 +21,22 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace Spring.Http
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// Factory for <see cref="HttpWebRequest"/> objects. Requests are created by the <see cref="M:CreateRequest"/> method.
|
||||
/// Factory for <see cref="IClientHttpRequest"/> objects.
|
||||
/// Requests are created by the <see cref="M:CreateRequest"/> method.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public interface IHttpWebRequestFactory
|
||||
public interface IClientHttpRequestFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a new <see cref="HttpWebRequest"/> for the specified URI.
|
||||
/// Create a new <see cref="IClientHttpRequest"/> for the specified URI and HTTP method.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to create a request for.</param>
|
||||
/// <param name="method">The HTTP method to execute.</param>
|
||||
/// <returns>The created request</returns>
|
||||
HttpWebRequest CreateRequest(Uri uri);
|
||||
IClientHttpRequest CreateRequest(Uri uri, HttpMethod method);
|
||||
}
|
||||
}
|
||||
59
src/Spring/Spring.Http/Http/Client/IClientHttpResponse.cs
Normal file
59
src/Spring/Spring.Http/Http/Client/IClientHttpResponse.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a client-side HTTP response.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Obtained via an 'execution' of the <see cref="IClientHttpRequest"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A client HTTP response must be <see cref="M:Close">closed</see>,
|
||||
/// typically in a <code>finally</code> or via an <code>using</code> block.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <seealso cref="IClientHttpRequest"/>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public interface IClientHttpResponse : IHttpInputMessage, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the HTTP status code of the response.
|
||||
/// </summary>
|
||||
HttpStatusCode StatusCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status description of the response.
|
||||
/// </summary>
|
||||
string StatusDescription { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Closes this response, freeing any resources created.
|
||||
/// </summary>
|
||||
void Close();
|
||||
}
|
||||
}
|
||||
457
src/Spring/Spring.Http/Http/Client/WebClientHttpRequest.cs
Normal file
457
src/Spring/Spring.Http/Http/Client/WebClientHttpRequest.cs
Normal file
@@ -0,0 +1,457 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="IClientHttpRequest"/> implementation that uses
|
||||
/// .NET <see cref="HttpWebRequest"/>'s class to execute requests.
|
||||
/// </summary>
|
||||
/// <seealso cref="WebClientHttpRequestFactory"/>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class WebClientHttpRequest : IClientHttpRequest
|
||||
{
|
||||
private HttpHeaders headers;
|
||||
private Action<Stream> body;
|
||||
private HttpWebRequest httpWebRequest;
|
||||
|
||||
private bool isExecuted;
|
||||
private bool isCancelled;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="HttpWebRequest"/> instance used.
|
||||
/// </summary>
|
||||
public HttpWebRequest HttpWebRequest
|
||||
{
|
||||
get { return this.httpWebRequest; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="WebClientHttpRequest"/>
|
||||
/// with the given <see cref="HttpWebRequest"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="request">The <see cref="HttpWebRequest"/> instance to use.</param>
|
||||
public WebClientHttpRequest(HttpWebRequest request)
|
||||
{
|
||||
AssertUtils.ArgumentNotNull(request, "HttpWebRequest");
|
||||
|
||||
this.httpWebRequest = request;
|
||||
this.headers = new HttpHeaders();
|
||||
}
|
||||
|
||||
#region IClientHttpRequest Members
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP method of the request.
|
||||
/// </summary>
|
||||
public HttpMethod Method
|
||||
{
|
||||
get
|
||||
{
|
||||
return (HttpMethod)Enum.Parse(typeof(HttpMethod), this.httpWebRequest.Method, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI of the request.
|
||||
/// </summary>
|
||||
public Uri Uri
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.httpWebRequest.RequestUri;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the message headers.
|
||||
/// </summary>
|
||||
public HttpHeaders Headers
|
||||
{
|
||||
get { return headers; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the delegate that writes the body message as a stream.
|
||||
/// </summary>
|
||||
public Action<Stream> Body
|
||||
{
|
||||
get { return this.body; }
|
||||
set { this.body = value; }
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Execute this request, resulting in a <see cref="IClientHttpResponse" /> that can be read.
|
||||
/// </summary>
|
||||
/// <returns>The response result of the execution</returns>
|
||||
public IClientHttpResponse Execute()
|
||||
{
|
||||
this.EnsureNotExecuted();
|
||||
|
||||
try
|
||||
{
|
||||
// Prepare
|
||||
this.PrepareRequest();
|
||||
|
||||
// Write
|
||||
if (this.body != null)
|
||||
{
|
||||
using (Stream stream = this.httpWebRequest.GetRequestStream())
|
||||
{
|
||||
this.body(stream);
|
||||
}
|
||||
}
|
||||
|
||||
// Read
|
||||
HttpWebResponse httpWebResponse = this.httpWebRequest.GetResponse() as HttpWebResponse;
|
||||
if (this.httpWebRequest.HaveResponse && httpWebResponse != null)
|
||||
{
|
||||
return new WebClientHttpResponse(httpWebResponse);
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
// This exception will be raised if the server didn't return 200 - OK
|
||||
// Try to retrieve more information about the network error
|
||||
HttpWebResponse httpWebResponse = ex.Response as HttpWebResponse;
|
||||
if (httpWebResponse != null)
|
||||
{
|
||||
this.isExecuted = true;
|
||||
return new WebClientHttpResponse(httpWebResponse);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
this.isExecuted = true;
|
||||
return null;
|
||||
}
|
||||
#endif
|
||||
|
||||
public void ExecuteAsync(object state, Action<ExecuteCompletedEventArgs> executeCompleted)
|
||||
{
|
||||
this.EnsureNotExecuted();
|
||||
|
||||
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(state);
|
||||
ExecuteState executeState = new ExecuteState(executeCompleted, asyncOperation);
|
||||
|
||||
try
|
||||
{
|
||||
// Prepare
|
||||
this.PrepareRequest();
|
||||
|
||||
// Post request
|
||||
if (this.body != null)
|
||||
{
|
||||
this.httpWebRequest.BeginGetRequestStream(new AsyncCallback(ExecuteRequestCallback), executeState);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Get request
|
||||
this.HttpWebRequest.BeginGetResponse(new AsyncCallback(ExecuteResponseCallback), executeState);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
ExecuteAsyncCallback(executeState, null, ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.isExecuted = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void CancelAsync()
|
||||
{
|
||||
this.isCancelled = true;
|
||||
try
|
||||
{
|
||||
if (this.httpWebRequest != null)
|
||||
{
|
||||
this.httpWebRequest.Abort();
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (((exception is OutOfMemoryException) || (exception is StackOverflowException)) || (exception is ThreadAbortException))
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Async methods/classes
|
||||
|
||||
private void ExecuteRequestCallback(IAsyncResult result)
|
||||
{
|
||||
ExecuteState state = (ExecuteState)result.AsyncState;
|
||||
|
||||
try
|
||||
{
|
||||
// Write
|
||||
using (Stream stream = this.httpWebRequest.EndGetRequestStream(result))
|
||||
{
|
||||
this.body(stream);
|
||||
}
|
||||
|
||||
// Read
|
||||
this.httpWebRequest.BeginGetResponse(new AsyncCallback(ExecuteResponseCallback), state);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
ExecuteAsyncCallback(state, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void ExecuteResponseCallback(IAsyncResult result)
|
||||
{
|
||||
ExecuteState state = (ExecuteState)result.AsyncState;
|
||||
|
||||
IClientHttpResponse response = null;
|
||||
Exception exception = null;
|
||||
try
|
||||
{
|
||||
HttpWebResponse httpWebResponse = this.httpWebRequest.EndGetResponse(result) as HttpWebResponse;
|
||||
if (this.httpWebRequest.HaveResponse == true && httpWebResponse != null)
|
||||
{
|
||||
response = new WebClientHttpResponse(httpWebResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
exception = ex;
|
||||
// This exception will be raised if the server didn't return 200 - OK
|
||||
// Try to retrieve more information about the network error
|
||||
if (ex is WebException)
|
||||
{
|
||||
HttpWebResponse httpWebResponse = ((WebException)ex).Response as HttpWebResponse;
|
||||
if (httpWebResponse != null)
|
||||
{
|
||||
exception = null;
|
||||
response = new WebClientHttpResponse(httpWebResponse);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ExecuteAsyncCallback(state, response, exception);
|
||||
}
|
||||
|
||||
// This is the method that the underlying, free-threaded asynchronous behavior will invoke.
|
||||
// This will happen on an arbitrary thread.
|
||||
private void ExecuteAsyncCallback(ExecuteState state, IClientHttpResponse response, Exception exception)
|
||||
{
|
||||
// Package the results of the operation
|
||||
ExecuteCompletedEventArgs eventArgs = new ExecuteCompletedEventArgs(response, exception, this.isCancelled, state.AsyncOperation.UserSuppliedState);
|
||||
ExecuteCallbackArgs<ExecuteCompletedEventArgs> callbackArgs = new ExecuteCallbackArgs<ExecuteCompletedEventArgs>(eventArgs, state.ExecuteCompleted);
|
||||
SendOrPostCallback callback = new SendOrPostCallback(ExecuteResponseReceived);
|
||||
|
||||
// End the task. The asyncOp object is responsible for marshaling the call.
|
||||
state.AsyncOperation.PostOperationCompleted(callback, callbackArgs);
|
||||
}
|
||||
|
||||
private static void ExecuteResponseReceived(object arg)
|
||||
{
|
||||
ExecuteCallbackArgs<ExecuteCompletedEventArgs> callbackArgs = (ExecuteCallbackArgs<ExecuteCompletedEventArgs>)arg;
|
||||
if (callbackArgs.Callback != null)
|
||||
{
|
||||
callbackArgs.Callback(callbackArgs.EventArgs);
|
||||
}
|
||||
}
|
||||
|
||||
private class ExecuteCallbackArgs<T> where T : class
|
||||
{
|
||||
public T EventArgs;
|
||||
public Action<T> Callback;
|
||||
|
||||
public ExecuteCallbackArgs(T eventArgs,
|
||||
Action<T> callback)
|
||||
{
|
||||
this.EventArgs = eventArgs;
|
||||
this.Callback = callback;
|
||||
}
|
||||
}
|
||||
|
||||
private class ExecuteState
|
||||
{
|
||||
public Action<ExecuteCompletedEventArgs> ExecuteCompleted;
|
||||
public AsyncOperation AsyncOperation;
|
||||
|
||||
public ExecuteState(
|
||||
Action<ExecuteCompletedEventArgs> executeCompleted,
|
||||
AsyncOperation asyncOperation)
|
||||
{
|
||||
this.ExecuteCompleted = executeCompleted;
|
||||
this.AsyncOperation = asyncOperation;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected void EnsureNotExecuted()
|
||||
{
|
||||
if (this.isExecuted)
|
||||
{
|
||||
throw new InvalidOperationException("Client HTTP request already executed or is currently executing.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepare the request for execution.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Default implementation copies headers to the request. Can be overridden in subclasses.
|
||||
/// </remarks>
|
||||
protected virtual void PrepareRequest()
|
||||
{
|
||||
// Copy headers
|
||||
foreach (string header in this.headers)
|
||||
{
|
||||
// Special headers
|
||||
switch (header.ToUpper(CultureInfo.InvariantCulture))
|
||||
{
|
||||
case "ACCEPT":
|
||||
{
|
||||
this.httpWebRequest.Accept = this.headers[header];
|
||||
break;
|
||||
}
|
||||
#if !SILVERLIGHT_3 && !WINDOWS_PHONE
|
||||
case "CONTENT-LENGTH":
|
||||
{
|
||||
this.httpWebRequest.ContentLength = this.headers.ContentLength;
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
case "CONTENT-TYPE":
|
||||
{
|
||||
this.httpWebRequest.ContentType = this.headers[header];
|
||||
break;
|
||||
}
|
||||
#if NET_4_0
|
||||
case "DATE" :
|
||||
{
|
||||
DateTime? date = this.headers.Date;
|
||||
if (date.HasValue)
|
||||
{
|
||||
this.httpWebRequest.Date = date.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.httpWebRequest.Date = DateTime.MinValue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "HOST" :
|
||||
{
|
||||
this.httpWebRequest.Host = this.headers[header];
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
#if !SILVERLIGHT
|
||||
case "CONNECTION":
|
||||
{
|
||||
string headerValue = this.headers[header];
|
||||
if (headerValue.Equals("Keep-Alive", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
this.httpWebRequest.KeepAlive = true;
|
||||
}
|
||||
else if (!headerValue.Equals("Close", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
this.httpWebRequest.Connection = headerValue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "EXPECT":
|
||||
{
|
||||
this.httpWebRequest.Expect = this.headers[header];
|
||||
break;
|
||||
}
|
||||
case "IF-MODIFIED-SINCE":
|
||||
{
|
||||
DateTime? date = this.headers.IfModifiedSince;
|
||||
if (date.HasValue)
|
||||
{
|
||||
this.httpWebRequest.IfModifiedSince = date.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.httpWebRequest.IfModifiedSince = DateTime.MinValue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
//case "RANGE":
|
||||
// {
|
||||
// break;
|
||||
// }
|
||||
case "REFERER":
|
||||
{
|
||||
this.httpWebRequest.Referer = this.headers[header];
|
||||
break;
|
||||
}
|
||||
case "TRANSFER-ENCODING":
|
||||
{
|
||||
this.httpWebRequest.SendChunked = true;
|
||||
string headerValue = this.headers[header];
|
||||
if (!headerValue.Equals("Chunked", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
this.httpWebRequest.TransferEncoding = headerValue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
#if !SILVERLIGHT_3
|
||||
case "USER-AGENT":
|
||||
{
|
||||
this.httpWebRequest.UserAgent = this.headers[header];
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
default:
|
||||
{
|
||||
// Other headers
|
||||
this.httpWebRequest.Headers[header] = this.headers[header];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="IClientHttpRequestFactory"/> implementation that uses
|
||||
/// .NET <see cref="HttpWebRequest"/>'s class to create requests.
|
||||
/// </summary>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class WebClientHttpRequestFactory : IClientHttpRequestFactory
|
||||
{
|
||||
#region Properties
|
||||
|
||||
#if !SILVERLIGHT_3
|
||||
private bool? _useDefaultCredentials;
|
||||
/// <summary>
|
||||
/// Gets or sets a boolean value that controls whether default credentials are sent with this request.
|
||||
/// </summary>
|
||||
public bool? UseDefaultCredentials
|
||||
{
|
||||
get { return this._useDefaultCredentials; }
|
||||
set { this._useDefaultCredentials = value; }
|
||||
}
|
||||
#endif
|
||||
|
||||
private ICredentials _credentials;
|
||||
/// <summary>
|
||||
/// Gets or sets authentication information for the request.
|
||||
/// </summary>
|
||||
public ICredentials Credentials
|
||||
{
|
||||
get { return this._credentials; }
|
||||
set { this._credentials = value; }
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
private X509CertificateCollection _clientCertificates;
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of security certificates that are associated with this request.
|
||||
/// </summary>
|
||||
public X509CertificateCollection ClientCertificates
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this._clientCertificates == null)
|
||||
{
|
||||
this._clientCertificates = new X509CertificateCollection();
|
||||
}
|
||||
return this._clientCertificates;
|
||||
}
|
||||
}
|
||||
|
||||
private IWebProxy _proxy;
|
||||
/// <summary>
|
||||
/// Gets or sets proxy information for the request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default value is set by calling the <see cref="P:System.Net.GlobalProxySelection.Select"/> property.
|
||||
/// </remarks>
|
||||
public IWebProxy Proxy
|
||||
{
|
||||
get { return this._proxy; }
|
||||
set { this._proxy = value; }
|
||||
}
|
||||
|
||||
private int? _timeout;
|
||||
/// <summary>
|
||||
/// Gets or sets the time-out value in milliseconds for the <see cref="M:System.Net.HttpWebRequest.GetResponse()"/>
|
||||
/// and <see cref="M:System.Net.HttpWebRequest.GetRequestStream()"/> methods.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default is 100,000 milliseconds (100 seconds).
|
||||
/// </remarks>
|
||||
public int? Timeout
|
||||
{
|
||||
get { return this._timeout; }
|
||||
set { this._timeout = value; }
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SILVERLIGHT && !WINDOWS_PHONE
|
||||
private WebRequestCreatorType _webRequestCreator;
|
||||
public WebRequestCreatorType WebRequestCreator
|
||||
{
|
||||
get { return this._webRequestCreator; }
|
||||
set { this._webRequestCreator = value; }
|
||||
}
|
||||
#endif
|
||||
|
||||
private HttpWebRequest httpWebRequest;
|
||||
/// <summary>
|
||||
/// Gets the .NET <see cref="HttpWebRequest"/> used by this factory
|
||||
/// or <see langword="null"/> if not created.
|
||||
/// </summary>
|
||||
public HttpWebRequest HttpWebRequest
|
||||
{
|
||||
get { return this.httpWebRequest; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="WebClientHttpRequestFactory"/>.
|
||||
/// </summary>
|
||||
public WebClientHttpRequestFactory()
|
||||
{
|
||||
#if SILVERLIGHT && !WINDOWS_PHONE
|
||||
this._webRequestCreator = WebRequestCreatorType.Default;
|
||||
#endif
|
||||
}
|
||||
|
||||
#region IClientHttpRequestFactory Membres
|
||||
|
||||
/// <summary>
|
||||
/// Create a new <see cref="IClientHttpRequest"/> for the specified URI and HTTP method.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to create a request for.</param>
|
||||
/// <param name="method">The HTTP method to execute.</param>
|
||||
/// <returns>The created request</returns>
|
||||
public virtual IClientHttpRequest CreateRequest(Uri uri, HttpMethod method)
|
||||
{
|
||||
#if SILVERLIGHT && !WINDOWS_PHONE
|
||||
switch (this._webRequestCreator)
|
||||
{
|
||||
case WebRequestCreatorType.ClientHttp:
|
||||
this.httpWebRequest = (HttpWebRequest)System.Net.Browser.WebRequestCreator.ClientHttp.Create(uri);
|
||||
break;
|
||||
case WebRequestCreatorType.BrowserHttp:
|
||||
this.httpWebRequest = (HttpWebRequest)System.Net.Browser.WebRequestCreator.BrowserHttp.Create(uri);
|
||||
break;
|
||||
case WebRequestCreatorType.Default:
|
||||
if (method == HttpMethod.GET || method == HttpMethod.POST)
|
||||
{
|
||||
this.httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Force Client HTTP stack
|
||||
this.httpWebRequest = (HttpWebRequest)System.Net.Browser.WebRequestCreator.ClientHttp.Create(uri);
|
||||
}
|
||||
break;
|
||||
}
|
||||
#else
|
||||
this.httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
|
||||
#endif
|
||||
|
||||
this.httpWebRequest.Method = method.ToString();
|
||||
|
||||
#if !SILVERLIGHT_3
|
||||
if (this._useDefaultCredentials.HasValue)
|
||||
{
|
||||
this.httpWebRequest.UseDefaultCredentials = this._useDefaultCredentials.Value;
|
||||
}
|
||||
#endif
|
||||
if (this._credentials != null)
|
||||
{
|
||||
this.httpWebRequest.Credentials = this._credentials;
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
if (this._clientCertificates != null)
|
||||
{
|
||||
foreach (X509Certificate2 certificate in this._clientCertificates)
|
||||
{
|
||||
this.httpWebRequest.ClientCertificates.Add(certificate);
|
||||
}
|
||||
}
|
||||
if (this._proxy != null)
|
||||
{
|
||||
this.httpWebRequest.Proxy = this._proxy;
|
||||
}
|
||||
if (this._timeout != null)
|
||||
{
|
||||
this.httpWebRequest.Timeout = this._timeout.Value;
|
||||
}
|
||||
#endif
|
||||
|
||||
return new WebClientHttpRequest(this.httpWebRequest);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
#if SILVERLIGHT && !WINDOWS_PHONE
|
||||
public enum WebRequestCreatorType
|
||||
{
|
||||
Default,
|
||||
BrowserHttp,
|
||||
ClientHttp
|
||||
}
|
||||
#endif
|
||||
}
|
||||
152
src/Spring/Spring.Http/Http/Client/WebClientHttpResponse.cs
Normal file
152
src/Spring/Spring.Http/Http/Client/WebClientHttpResponse.cs
Normal file
@@ -0,0 +1,152 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Client
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="IClientHttpResponse"/> implementation that uses
|
||||
/// .NET <see cref="HttpWebResponse"/>'s class to read responses.
|
||||
/// </summary>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class WebClientHttpResponse : IClientHttpResponse
|
||||
{
|
||||
private HttpHeaders headers;
|
||||
private HttpWebResponse httpWebResponse;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="HttpWebResponse"/> instance used.
|
||||
/// </summary>
|
||||
public HttpWebResponse HttpWebResponse
|
||||
{
|
||||
get { return this.httpWebResponse; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="WebClientHttpResponse"/>
|
||||
/// with the given <see cref="HttpWebResponse"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="response">The <see cref="HttpWebResponse"/> instance to use.</param>
|
||||
public WebClientHttpResponse(HttpWebResponse response)
|
||||
{
|
||||
AssertUtils.ArgumentNotNull(response, "HttpWebResponse");
|
||||
|
||||
this.httpWebResponse = response;
|
||||
this.headers = new HttpHeaders();
|
||||
|
||||
#if NET_2_0 || WINDOWS_PHONE
|
||||
foreach (string header in this.httpWebResponse.Headers)
|
||||
{
|
||||
this.headers[header] = this.httpWebResponse.Headers[header];
|
||||
}
|
||||
#endif
|
||||
#if SILVERLIGHT_3
|
||||
try
|
||||
{
|
||||
foreach (string header in this.httpWebResponse.Headers)
|
||||
{
|
||||
this.headers[header] = this.httpWebResponse.Headers[header];
|
||||
}
|
||||
}
|
||||
catch(NotImplementedException)
|
||||
{
|
||||
this.headers.ContentLength = this.httpWebResponse.ContentLength;
|
||||
this.headers["Content-Type"] = this.httpWebResponse.ContentType;
|
||||
}
|
||||
#elif SILVERLIGHT
|
||||
if (this.httpWebResponse.SupportsHeaders)
|
||||
{
|
||||
foreach (string header in this.httpWebResponse.Headers)
|
||||
{
|
||||
this.headers[header] = this.httpWebResponse.Headers[header];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.headers.ContentLength = this.httpWebResponse.ContentLength;
|
||||
this.headers["Content-Type"] = this.httpWebResponse.ContentType;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#region IClientHttpResponse Membres
|
||||
|
||||
/// <summary>
|
||||
/// Gets the message headers.
|
||||
/// </summary>
|
||||
public HttpHeaders Headers
|
||||
{
|
||||
get { return this.headers; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the body of the message as a stream.
|
||||
/// </summary>
|
||||
public Stream Body
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.httpWebResponse.GetResponseStream();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status code of the response.
|
||||
/// </summary>
|
||||
public HttpStatusCode StatusCode
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.httpWebResponse.StatusCode;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status description of the response.
|
||||
/// </summary>
|
||||
public string StatusDescription
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.httpWebResponse.StatusDescription;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes this response, freeing any resources created.
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
this.httpWebResponse.Close();
|
||||
}
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
((IDisposable)this.httpWebResponse).Dispose();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,12 +19,8 @@
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
@@ -33,7 +29,7 @@ namespace Spring.Http.Converters
|
||||
/// <remarks>
|
||||
/// This base class adds support for setting supported <see cref="MediaType"/>s, through the
|
||||
/// <see cref="P:SupportedMediaTypes"/> property.
|
||||
/// It also adds support for 'Content-Type' when writing to the HTTP request.
|
||||
/// It also adds support for 'Content-Type' when writing to the HTTP message.
|
||||
/// </remarks>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Juergen Hoeller</author>
|
||||
@@ -41,22 +37,13 @@ namespace Spring.Http.Converters
|
||||
public abstract class AbstractHttpMessageConverter : IHttpMessageConverter
|
||||
{
|
||||
#region Logging
|
||||
|
||||
#if !SILVERLIGHT
|
||||
private static readonly Common.Logging.ILog LOG = Common.Logging.LogManager.GetLogger(typeof(AbstractHttpMessageConverter));
|
||||
|
||||
#endif
|
||||
#endregion
|
||||
|
||||
private IList<MediaType> _supportedMediaTypes = new List<MediaType>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of <see cref="MediaType"/> objects supported by this converter.
|
||||
/// </summary>
|
||||
public IList<MediaType> SupportedMediaTypes
|
||||
{
|
||||
get { return _supportedMediaTypes; }
|
||||
set { _supportedMediaTypes = value; }
|
||||
}
|
||||
|
||||
#region Constructor(s)
|
||||
|
||||
/// <summary>
|
||||
@@ -118,7 +105,16 @@ namespace Spring.Http.Converters
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read an object of the given type form the given HTTP response, and returns it.
|
||||
/// Gets or sets the list of <see cref="MediaType"/> objects supported by this converter.
|
||||
/// </summary>
|
||||
public IList<MediaType> SupportedMediaTypes
|
||||
{
|
||||
get { return _supportedMediaTypes; }
|
||||
set { _supportedMediaTypes = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read an object of the given type form the given HTTP message, and returns it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This implementation simple delegates to <see cre="ReadInternal"/> method.
|
||||
@@ -128,44 +124,47 @@ namespace Spring.Http.Converters
|
||||
/// The type of object to return. This type must have previously been passed to the
|
||||
/// <see cref="M:CanRead"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
public T Read<T>(HttpWebResponse response) where T : class
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
public T Read<T>(IHttpInputMessage message) where T : class
|
||||
{
|
||||
return ReadInternal<T>(response);
|
||||
return ReadInternal<T>(message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write an given object to the given HTTP request.
|
||||
/// Write an given object to the given HTTP message.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This implementation delegates to <see cref="M:GetDefaultContentType"/> method if a content
|
||||
/// type was not provided, and calls <see cref="M:WriteInternal"/>.
|
||||
/// </remarks>
|
||||
/// <param name="content">
|
||||
/// The object to write to the HTTP request. The type of this object must have previously been
|
||||
/// The object to write to the HTTP message. The type of this object must have previously been
|
||||
/// passed to the <see cref="M:CanWrite"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="mediaType">
|
||||
/// <param name="contentType">
|
||||
/// The content type to use when writing. May be null to indicate that the default content type of the converter must be used.
|
||||
/// If not null, this media type must have previously been passed to the <see cref="M:CanWrite"/> method of this interface,
|
||||
/// which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
public void Write(object content, MediaType mediaType, HttpWebRequest request)
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
public void Write(object content, MediaType contentType, IHttpOutputMessage message)
|
||||
{
|
||||
if (!StringUtils.HasText(request.ContentType))
|
||||
HttpHeaders headers = message.Headers;
|
||||
if (headers.ContentType == null)
|
||||
{
|
||||
if (mediaType == null || mediaType.IsWildcardType || mediaType.IsWildcardSubtype)
|
||||
if (contentType == null || contentType.IsWildcardType || contentType.IsWildcardSubtype)
|
||||
{
|
||||
mediaType = GetDefaultContentType(content.GetType());
|
||||
contentType = GetDefaultContentType(content.GetType());
|
||||
}
|
||||
if (mediaType != null)
|
||||
if (contentType != null)
|
||||
{
|
||||
request.ContentType = mediaType.ToString();
|
||||
headers.ContentType = contentType;
|
||||
}
|
||||
}
|
||||
WriteInternal(content, request);
|
||||
WriteInternal(content, message);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -245,51 +244,17 @@ namespace Spring.Http.Converters
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected abstract T ReadInternal<T>(HttpWebResponse response) where T : class;
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected abstract T ReadInternal<T>(IHttpInputMessage message) where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected abstract void WriteInternal(object content, HttpWebRequest request);
|
||||
|
||||
#region Inner class definitions
|
||||
|
||||
// TODO : Move this class ?
|
||||
internal class IgnoreCloseMemoryStream : MemoryStream
|
||||
{
|
||||
public IgnoreCloseMemoryStream()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
public override void Close()
|
||||
{
|
||||
}
|
||||
|
||||
public void CopyToAndClose(Stream destination)
|
||||
{
|
||||
this.Position = 0;
|
||||
|
||||
#if NET_4_0
|
||||
this.CopyTo(destination);
|
||||
#else
|
||||
// From .NET 4.0 Stream.CopyTo method
|
||||
int bytesCount;
|
||||
byte[] buffer = new byte[0x1000];
|
||||
while ((bytesCount = this.Read(buffer, 0, buffer.Length)) != 0)
|
||||
{
|
||||
destination.Write(buffer, 0, bytesCount);
|
||||
}
|
||||
#endif
|
||||
|
||||
base.Close();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected abstract void WriteInternal(object content, IHttpOutputMessage message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -59,35 +59,39 @@ namespace Spring.Http.Converters
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadInternal<T>(HttpWebResponse response)
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected override T ReadInternal<T>(IHttpInputMessage message)
|
||||
{
|
||||
// Get the response stream
|
||||
using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
|
||||
// Read from the message stream
|
||||
using (BinaryReader reader = new BinaryReader(message.Body))
|
||||
{
|
||||
return reader.ReadBytes((int)response.ContentLength) as T;
|
||||
return reader.ReadBytes((int)message.Headers.ContentLength) as T;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteInternal(object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected override void WriteInternal(object content, IHttpOutputMessage message)
|
||||
{
|
||||
// Create a byte array of the data we want to send
|
||||
byte[] byteData = content as byte[];
|
||||
|
||||
// Set the content length in the request headers
|
||||
request.ContentLength = byteData.Length;
|
||||
//#if !SILVERLIGHT
|
||||
// // Set the content length in the message headers
|
||||
// message.Headers.ContentLength = byteData.Length;
|
||||
//#endif
|
||||
|
||||
// Write to the request
|
||||
using (Stream postStream = request.GetRequestStream())
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
postStream.Write(byteData, 0, byteData.Length);
|
||||
}
|
||||
stream.Write(byteData, 0, byteData.Length);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_5
|
||||
#if NET_3_5 && !SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -60,9 +60,8 @@ namespace Spring.Http.Converters.Feed
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response)
|
||||
protected override T ReadXml<T>(XmlReader xmlReader)
|
||||
{
|
||||
if (typeof(SyndicationFeed).Equals(typeof(T)))
|
||||
{
|
||||
@@ -76,16 +75,16 @@ namespace Spring.Http.Converters.Feed
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default <see cref="XmlReaderSettings">XmlReader settings</see>
|
||||
/// used by this converter to read from the HTTP response.
|
||||
/// Returns the <see cref="XmlReaderSettings">XmlReader settings</see>
|
||||
/// used by this converter to read from the HTTP message.
|
||||
/// </summary>
|
||||
/// <returns>The XmlReader settings.</returns>
|
||||
protected override XmlReaderSettings GetDefaultXmlReaderSettings()
|
||||
protected override XmlReaderSettings GetXmlReaderSettings()
|
||||
{
|
||||
XmlReaderSettings settings = new XmlReaderSettings();
|
||||
settings.CloseInput = true;
|
||||
settings.IgnoreProcessingInstructions = true;
|
||||
#if NET_4_0
|
||||
#if NET_4_0 || SILVERLIGHT
|
||||
settings.DtdProcessing = DtdProcessing.Ignore;
|
||||
#else
|
||||
settings.ProhibitDtd = false;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_5
|
||||
#if NET_3_5 && !SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -49,9 +49,8 @@ namespace Spring.Http.Converters.Feed
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
if (content is SyndicationFeed)
|
||||
{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_5
|
||||
#if NET_3_5 && !SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -49,9 +49,8 @@ namespace Spring.Http.Converters.Feed
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
if (content is SyndicationFeed)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <author>Bruno Baia</author>
|
||||
public class FileInfoHttpMessageConverter : AbstractHttpMessageConverter
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="ByteArrayHttpMessageConverter"/>
|
||||
/// with 'text/plain; charset=ISO-8859-1', and '*/*' media types.
|
||||
/// </summary>
|
||||
public FileInfoHttpMessageConverter() :
|
||||
base(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the given class is supported by this converter.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to test for support.</param>
|
||||
/// <returns><see langword="true"/> if supported; otherwise <see langword="false"/></returns>
|
||||
protected override bool Supports(Type type)
|
||||
{
|
||||
return type.Equals(typeof(FileInfo));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected override T ReadInternal<T>(IHttpInputMessage message)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected override void WriteInternal(object content, IHttpOutputMessage message)
|
||||
{
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
using (FileStream fs = ((FileInfo)content).OpenRead())
|
||||
{
|
||||
IoUtils.CopyStream(fs, stream);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
#if SILVERLIGHT
|
||||
using Spring.Collections.Specialized;
|
||||
#else
|
||||
using System.Collections.Specialized;
|
||||
#endif
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can handle form data,
|
||||
/// including multipart form data (i.e. file uploads).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This converter supports the 'application/x-www-form-urlencoded' and 'multipart/form-data' media
|
||||
/// types, and read the 'application/x-www-form-urlencoded' media type (but not 'multipart/form-data').
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// In other words, this converter can read and write 'normal' HTML forms (as <see cref="NameValueCollection"/>),
|
||||
/// and it can write multipart form (as <see cref="IDictionary{String,Object}"/>).
|
||||
/// When writing multipart, this converter uses other <see cref="IHttpMessageConverter"/> to write the respective MIME parts.
|
||||
/// By default, basic converters are registered (supporting <see cref="String"/> and <see cref="FileInfo"/>, for instance);
|
||||
/// these can be overridden by setting <see cref="P:PartConverters"/> property.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// For example, the following snippet shows how to submit an HTML form:
|
||||
/// <code>
|
||||
/// RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default
|
||||
/// NameValueCollection form = new NameValueCollection();
|
||||
/// form.Add("field 1", "value 1");
|
||||
/// form.Add("field 2", "value 2");
|
||||
/// form.Add("field 2", "value 3");
|
||||
/// template.PostForLocation("http://example.com/myForm", form);
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The following snippet shows how to do a file upload:
|
||||
/// <code>
|
||||
/// RestTemplate template = new RestTemplate();
|
||||
/// IDictionary<string, object> parts = new Dictionary<string, object>();
|
||||
/// parts.Add("field 1", "value 1");
|
||||
/// parts.Add("file", new FileInfo(@"C:\myFile.jpg"));
|
||||
/// template.PostForLocation("http://example.com/myFileUpload", parts);
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public class FormHttpMessageConverter : IHttpMessageConverter
|
||||
{
|
||||
private static char[] BOUNDARY_CHARS =
|
||||
new char[]{'-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
|
||||
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
|
||||
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
|
||||
'V', 'W', 'X', 'Y', 'Z'};
|
||||
|
||||
private Random random;
|
||||
private Encoding _charset;
|
||||
private IList<MediaType> _supportedMediaTypes;
|
||||
private IList<IHttpMessageConverter> _partConverters;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the message body converters to use.
|
||||
/// These converters are used to convert objects to MIME parts.
|
||||
/// </summary>
|
||||
public IList<IHttpMessageConverter> PartConverters
|
||||
{
|
||||
get { return _partConverters; }
|
||||
set { _partConverters = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the encoding used for writing form data.
|
||||
/// </summary>
|
||||
public Encoding Charset
|
||||
{
|
||||
get { return this._charset; }
|
||||
set { _charset = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FormHttpMessageConverter"/>.
|
||||
/// </summary>
|
||||
public FormHttpMessageConverter()
|
||||
{
|
||||
this.random = new Random();
|
||||
#if SILVERLIGHT
|
||||
this._charset = new UTF8Encoding(false); // Remove byte Order Mask (BOM)
|
||||
#else
|
||||
this._charset = Encoding.GetEncoding("ISO-8859-1");
|
||||
#endif
|
||||
this._supportedMediaTypes = new List<MediaType>(2);
|
||||
this._supportedMediaTypes.Add(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
this._supportedMediaTypes.Add(MediaType.MULTIPART_FORM_DATA);
|
||||
|
||||
this._partConverters = new List<IHttpMessageConverter>(3);
|
||||
this._partConverters.Add(new ByteArrayHttpMessageConverter());
|
||||
this._partConverters.Add(new StringHttpMessageConverter());
|
||||
this._partConverters.Add(new FileInfoHttpMessageConverter());
|
||||
//this._partConverters.Add(new ResourceHttpMessageConverter());
|
||||
}
|
||||
|
||||
#region IHttpMessageConverter Membres
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the given class can be read by this converter.
|
||||
/// </summary>
|
||||
/// <param name="type">The class to test for readability</param>
|
||||
/// <param name="mediaType">
|
||||
/// The media type to read, can be null if not specified. Typically the value of a 'Content-Type' header.
|
||||
/// </param>
|
||||
/// <returns><see langword="true"/> if readable; otherwise <see langword="false"/></returns>
|
||||
public bool CanRead(Type type, MediaType mediaType)
|
||||
{
|
||||
if (!typeof(NameValueCollection).IsAssignableFrom(type))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (mediaType != null)
|
||||
{
|
||||
return MediaType.APPLICATION_FORM_URLENCODED.Includes(mediaType);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the given class can be written by this converter.
|
||||
/// </summary>
|
||||
/// <param name="type">The class to test for writability</param>
|
||||
/// <param name="mediaType">
|
||||
/// The media type to write, can be null if not specified. Typically the value of an 'Accept' header.
|
||||
/// </param>
|
||||
/// <returns><see langword="true"/> if writable; otherwise <see langword="false"/></returns>
|
||||
public bool CanWrite(Type type, MediaType mediaType)
|
||||
{
|
||||
if (!typeof(NameValueCollection).IsAssignableFrom(type) &&
|
||||
!typeof(IDictionary<string, object>).IsAssignableFrom(type))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (mediaType != null)
|
||||
{
|
||||
return MediaType.APPLICATION_FORM_URLENCODED.IsCompatibleWith(mediaType) ||
|
||||
MediaType.MULTIPART_FORM_DATA.IsCompatibleWith(mediaType);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of <see cref="MediaType"/> objects supported by this converter.
|
||||
/// </summary>
|
||||
public IList<MediaType> SupportedMediaTypes
|
||||
{
|
||||
get { return _supportedMediaTypes; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read an object of the given type form the given HTTP message, and returns it.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">
|
||||
/// The type of object to return. This type must have previously been passed to the
|
||||
/// <see cref="M:CanRead"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </typeparam>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
public T Read<T>(IHttpInputMessage message) where T : class
|
||||
{
|
||||
// Get the message encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = message.Headers.ContentType;
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = this._charset;
|
||||
}
|
||||
else
|
||||
{
|
||||
encoding = Encoding.GetEncoding(mediaType.CharSet);
|
||||
}
|
||||
|
||||
// Read from the message stream
|
||||
string body;
|
||||
using (StreamReader reader = new StreamReader(message.Body, encoding))
|
||||
{
|
||||
body = reader.ReadToEnd();
|
||||
}
|
||||
|
||||
string[] pairs = body.Split('&');
|
||||
NameValueCollection result = new NameValueCollection(pairs.Length);
|
||||
foreach (string pair in pairs)
|
||||
{
|
||||
int idx = pair.IndexOf('=');
|
||||
if (idx == -1)
|
||||
{
|
||||
result.Add(UrlDecode(pair, this._charset), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
string name = UrlDecode(pair.Substring(0, idx), this._charset);
|
||||
string value = UrlDecode(pair.Substring(idx + 1), this._charset);
|
||||
result.Add(name, value);
|
||||
}
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write an given object to the given HTTP message.
|
||||
/// </summary>
|
||||
/// <param name="content">
|
||||
/// The object to write to the HTTP message. The type of this object must have previously been
|
||||
/// passed to the <see cref="M:CanWrite"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="contentType">
|
||||
/// The content type to use when writing. May be null to indicate that the default content type of the converter must be used.
|
||||
/// If not null, this media type must have previously been passed to the <see cref="M:CanWrite"/> method of this interface,
|
||||
/// which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
public void Write(object content, MediaType contentType, IHttpOutputMessage message)
|
||||
{
|
||||
if (content is NameValueCollection)
|
||||
{
|
||||
this.WriteForm((NameValueCollection) content, message);
|
||||
}
|
||||
else if (content is IDictionary<string, object>)
|
||||
{
|
||||
this.WriteMultipart((IDictionary<string, object>) content, message);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Write Form
|
||||
|
||||
private void WriteForm(NameValueCollection form, IHttpOutputMessage message)
|
||||
{
|
||||
message.Headers.ContentType = MediaType.APPLICATION_FORM_URLENCODED;
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (int i = 0; i < form.AllKeys.Length; i++)
|
||||
{
|
||||
string name = form.AllKeys[i];
|
||||
string[] values = form.GetValues(name);
|
||||
if (values == null)
|
||||
{
|
||||
builder.Append(UrlEncode(name, this._charset));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int j = 0; j < values.Length; j++)
|
||||
{
|
||||
string value = values[j];
|
||||
builder.Append(UrlEncode(name, this._charset));
|
||||
builder.Append('=');
|
||||
builder.Append(UrlEncode(value, this._charset));
|
||||
if (j != (values.Length - 1))
|
||||
{
|
||||
builder.Append('&');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i != (form.AllKeys.Length - 1))
|
||||
{
|
||||
builder.Append('&');
|
||||
}
|
||||
}
|
||||
|
||||
// Create a byte array of the data we want to send
|
||||
byte[] byteData = this._charset.GetBytes(builder.ToString());
|
||||
|
||||
//#if !SILVERLIGHT
|
||||
// // Set the content length in the message headers
|
||||
// message.Headers.ContentLength = byteData.Length;
|
||||
//#endif
|
||||
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
stream.Write(byteData, 0, byteData.Length);
|
||||
};
|
||||
}
|
||||
|
||||
private static string UrlDecode(string url, Encoding charset)
|
||||
{
|
||||
#if WINDOWS_PHONE
|
||||
return System.Net.HttpUtility.UrlDecode(url);
|
||||
#elif SILVERLIGHT
|
||||
return System.Windows.Browser.HttpUtility.UrlDecode(url);
|
||||
#else
|
||||
return System.Web.HttpUtility.UrlDecode(url, charset);
|
||||
#endif
|
||||
}
|
||||
|
||||
private static string UrlEncode(string url, Encoding charset)
|
||||
{
|
||||
#if WINDOWS_PHONE
|
||||
return System.Net.HttpUtility.UrlEncode(url);
|
||||
#elif SILVERLIGHT
|
||||
return System.Windows.Browser.HttpUtility.UrlEncode(url);
|
||||
#else
|
||||
return System.Web.HttpUtility.UrlEncode(url, charset);
|
||||
#endif
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Write Multipart
|
||||
|
||||
private void WriteMultipart(IDictionary<string, object> parts, IHttpOutputMessage message)
|
||||
{
|
||||
string boundary = this.GenerateMultipartBoundary();
|
||||
|
||||
IDictionary<string, string> parameters = new Dictionary<string, string>(1);
|
||||
parameters.Add("boundary", boundary);
|
||||
MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
|
||||
message.Headers.ContentType = contentType;
|
||||
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
using (StreamWriter streamWriter = new StreamWriter(stream))
|
||||
{
|
||||
streamWriter.NewLine = "\r\n";
|
||||
this.WriteParts(boundary, parts, streamWriter);
|
||||
this.WriteEnd(boundary, streamWriter);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a multipart boundary.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Default implementation returns a random boundary. Can be overridden in subclasses.
|
||||
/// </remarks>
|
||||
/// <returns>A multipart boundary</returns>
|
||||
protected virtual string GenerateMultipartBoundary()
|
||||
{
|
||||
char[] boundary = new char[random.Next(11) + 30];
|
||||
for (int i = 0; i < boundary.Length; i++)
|
||||
{
|
||||
boundary[i] = BOUNDARY_CHARS[random.Next(BOUNDARY_CHARS.Length)];
|
||||
}
|
||||
return new String(boundary);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the filename of the given multipart part
|
||||
/// to be used for the 'Content-Disposition' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Default implementation returns <see cref="P:FileInfo.FullName"/> if the part is a <see cref="FileInfo"/>,
|
||||
/// and <see langword="null"/> in other cases. Can be overridden in subclasses.
|
||||
/// </remarks>
|
||||
/// <param name="part">The part to determine the file name for</param>
|
||||
/// <returns>The filename, or <see langword="null"/> if not known</returns>
|
||||
protected virtual string GetMultipartFilename(object part)
|
||||
{
|
||||
if (part is FileInfo)
|
||||
{
|
||||
return ((FileInfo)part).FullName;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void WriteParts(string boundary, IDictionary<string, object> parts, StreamWriter streamWriter)
|
||||
{
|
||||
foreach(KeyValuePair<string, object> entry in parts)
|
||||
{
|
||||
this.WriteBoundary(boundary, streamWriter);
|
||||
HttpEntity entity = this.GetEntity(entry.Value);
|
||||
this.WritePart(entry.Key, entity, streamWriter);
|
||||
streamWriter.WriteLine();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteBoundary(string boundary, StreamWriter streamWriter)
|
||||
{
|
||||
streamWriter.Write("--");
|
||||
streamWriter.Write(boundary);
|
||||
streamWriter.WriteLine();
|
||||
}
|
||||
|
||||
private void WritePart(String name, HttpEntity partEntity, StreamWriter streamWriter)
|
||||
{
|
||||
object partBody = partEntity.Body;
|
||||
Type partType = partBody.GetType();
|
||||
HttpHeaders partHeaders = partEntity.Headers;
|
||||
MediaType partContentType = partHeaders.ContentType;
|
||||
foreach (IHttpMessageConverter messageConverter in this._partConverters)
|
||||
{
|
||||
if (messageConverter.CanWrite(partType, partContentType))
|
||||
{
|
||||
IHttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(streamWriter);
|
||||
multipartMessage.Headers["Content-Disposition"] = this.GetContentDispositionFormData(name, this.GetMultipartFilename(partBody));
|
||||
foreach (string header in partHeaders)
|
||||
{
|
||||
multipartMessage.Headers[header] = partHeaders[header];
|
||||
}
|
||||
messageConverter.Write(partBody, partContentType, multipartMessage);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new HttpMessageNotWritableException(String.Format(
|
||||
"Could not write request: no suitable HttpMessageConverter found for part type [{0}]", partType));
|
||||
}
|
||||
|
||||
private void WriteEnd(string boundary, StreamWriter streamWriter)
|
||||
{
|
||||
streamWriter.Write("--");
|
||||
streamWriter.Write(boundary);
|
||||
streamWriter.Write("--");
|
||||
streamWriter.WriteLine();
|
||||
}
|
||||
|
||||
private HttpEntity GetEntity(object part)
|
||||
{
|
||||
if (part is HttpEntity)
|
||||
{
|
||||
return (HttpEntity)part;
|
||||
}
|
||||
return new HttpEntity(part);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the value of the 'Content-Disposition' header for 'form-data'.
|
||||
/// </summary>
|
||||
/// <param name="name">The field name</param>
|
||||
/// <param name="filename">The filename, may be <see langwrod="null"/></param>
|
||||
/// <returns>The value of the 'Content-Disposition' header</returns>
|
||||
private string GetContentDispositionFormData(string name, string filename)
|
||||
{
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.AppendFormat("form-data; name=\"{0}\"", name);
|
||||
if (filename != null)
|
||||
{
|
||||
builder.AppendFormat("; filename=\"{0}\"", filename);
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpOutputMessage"/> used for writing multipart data.
|
||||
/// </summary>
|
||||
private sealed class MultipartHttpOutputMessage : IHttpOutputMessage
|
||||
{
|
||||
private HttpHeaders headers;
|
||||
|
||||
private StreamWriter bodyWriter;
|
||||
|
||||
public MultipartHttpOutputMessage(StreamWriter bodyWriter)
|
||||
{
|
||||
this.headers = new HttpHeaders();
|
||||
this.bodyWriter = bodyWriter;
|
||||
}
|
||||
|
||||
#region IHttpMessage Membres
|
||||
|
||||
public HttpHeaders Headers
|
||||
{
|
||||
get { return this.headers; }
|
||||
}
|
||||
|
||||
public Action<Stream> Body
|
||||
{
|
||||
get { throw new InvalidOperationException(); }
|
||||
set { this.WritePartBody(value); }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void WritePartBody(Action<Stream> body)
|
||||
{
|
||||
foreach (string header in this.headers)
|
||||
{
|
||||
bodyWriter.Write(header);
|
||||
bodyWriter.Write(": ");
|
||||
bodyWriter.Write(this.headers[header]);
|
||||
bodyWriter.WriteLine();
|
||||
}
|
||||
bodyWriter.WriteLine();
|
||||
bodyWriter.Flush();
|
||||
Stream stream = bodyWriter.BaseStream;
|
||||
stream.Flush();
|
||||
body(stream);
|
||||
stream.Flush();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception thrown by <see cref="IHttpMessageConverter"/> implementations when the conversion fails.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpMessageConversionException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageConversionException"/> class.
|
||||
/// </summary>
|
||||
public HttpMessageConversionException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageConversionException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
public HttpMessageConversionException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageConversionException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
/// <param name="rootCause">
|
||||
/// The root exception that is being wrapped.
|
||||
/// </param>
|
||||
public HttpMessageConversionException(string message, Exception rootCause)
|
||||
: base(message, rootCause)
|
||||
{
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageConversionException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpMessageConversionException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception thrown by <see cref="IHttpMessageConverter"/> implementations
|
||||
/// when reading from HTTP message fails.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpMessageNotReadableException : HttpMessageConversionException
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotReadableException"/> class.
|
||||
/// </summary>
|
||||
public HttpMessageNotReadableException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotReadableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
public HttpMessageNotReadableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotReadableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
/// <param name="rootCause">
|
||||
/// The root exception that is being wrapped.
|
||||
/// </param>
|
||||
public HttpMessageNotReadableException(string message, Exception rootCause)
|
||||
: base(message, rootCause)
|
||||
{
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotReadableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpMessageNotReadableException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception thrown by <see cref="IHttpMessageConverter"/> implementations
|
||||
/// when writing to HTTP message fails.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpMessageNotWritableException : HttpMessageConversionException
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotWritableException"/> class.
|
||||
/// </summary>
|
||||
public HttpMessageNotWritableException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotWritableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
public HttpMessageNotWritableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotWritableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">
|
||||
/// A message about the exception.
|
||||
/// </param>
|
||||
/// <param name="rootCause">
|
||||
/// The root exception that is being wrapped.
|
||||
/// </param>
|
||||
public HttpMessageNotWritableException(string message, Exception rootCause)
|
||||
: base(message, rootCause)
|
||||
{
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpMessageNotWritableException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpMessageNotWritableException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,13 +21,12 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
// TODO: HttpMessageNotReadableException & HttpMessageNotWritableException exceptions ?
|
||||
|
||||
/// <summary>
|
||||
/// Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
|
||||
/// Strategy interface that specifies a converter that can convert from and to HTTP messages.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Juergen Hoeller</author>
|
||||
@@ -60,29 +59,31 @@ namespace Spring.Http.Converters
|
||||
IList<MediaType> SupportedMediaTypes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Read an object of the given type form the given HTTP response, and returns it.
|
||||
/// Read an object of the given type form the given HTTP message, and returns it.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">
|
||||
/// The type of object to return. This type must have previously been passed to the
|
||||
/// <see cref="M:CanRead"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
T Read<T>(HttpWebResponse response) where T : class;
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
T Read<T>(IHttpInputMessage message) where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Write an given object to the given HTTP request.
|
||||
/// Write an given object to the given HTTP message.
|
||||
/// </summary>
|
||||
/// <param name="content">
|
||||
/// The object to write to the HTTP request. The type of this object must have previously been
|
||||
/// The object to write to the HTTP message. The type of this object must have previously been
|
||||
/// passed to the <see cref="M:CanWrite"/> method of this interface, which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="mediaType">
|
||||
/// <param name="contentType">
|
||||
/// The content type to use when writing. May be null to indicate that the default content type of the converter must be used.
|
||||
/// If not null, this media type must have previously been passed to the <see cref="M:CanWrite"/> method of this interface,
|
||||
/// which must have returned <see langword="true"/>.
|
||||
/// </param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
void Write(object content, MediaType mediaType, HttpWebRequest request);
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
void Write(object content, MediaType contentType, IHttpOutputMessage message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_5
|
||||
#if NET_3_5 || WINDOWS_PHONE
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,18 +20,17 @@
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Xml;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Xml;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Serialization.Json;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Converters.Json
|
||||
{
|
||||
// TODO : Support for known types, etc...
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can read and write JSON.
|
||||
/// </summary>
|
||||
@@ -45,7 +44,18 @@ namespace Spring.Http.Converters.Json
|
||||
/// <summary>
|
||||
/// Default encoding for JSON.
|
||||
/// </summary>
|
||||
public static readonly Encoding DEFAULT_CHARSET = Encoding.UTF8;
|
||||
public static readonly Encoding DEFAULT_CHARSET = new UTF8Encoding(false); // Remove byte Order Mask (BOM)
|
||||
|
||||
private IEnumerable<Type> _knownTypes;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets types that may be present in the object graph.
|
||||
/// </summary>
|
||||
public IEnumerable<Type> KnownTypes
|
||||
{
|
||||
get { return _knownTypes; }
|
||||
set { _knownTypes = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="JsonHttpMessageConverter"/>
|
||||
@@ -70,27 +80,34 @@ namespace Spring.Http.Converters.Json
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadInternal<T>(HttpWebResponse response)
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected override T ReadInternal<T>(IHttpInputMessage message)
|
||||
{
|
||||
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
|
||||
using (Stream stream = response.GetResponseStream())
|
||||
{
|
||||
return (T)serializer.ReadObject(stream) as T;
|
||||
}
|
||||
DataContractJsonSerializer serializer = this.GetSerializer(typeof(T));
|
||||
return (T)serializer.ReadObject(message.Body) as T;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteInternal(object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected override void WriteInternal(object content, IHttpOutputMessage message)
|
||||
{
|
||||
// Get the request encoding
|
||||
#if SILVERLIGHT
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
DataContractJsonSerializer serializer = this.GetSerializer(content.GetType());
|
||||
serializer.WriteObject(stream, content);
|
||||
};
|
||||
#else
|
||||
// Get the message encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = MediaType.ParseMediaType(request.ContentType);
|
||||
MediaType mediaType = message.Headers.ContentType;
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = DEFAULT_CHARSET;
|
||||
@@ -100,23 +117,35 @@ namespace Spring.Http.Converters.Json
|
||||
encoding = Encoding.GetEncoding(mediaType.CharSet);
|
||||
}
|
||||
|
||||
DataContractJsonSerializer serializer = new DataContractJsonSerializer(content.GetType());
|
||||
DataContractJsonSerializer serializer = this.GetSerializer(content.GetType());
|
||||
|
||||
// Write to the request
|
||||
using (IgnoreCloseMemoryStream requestStream = new IgnoreCloseMemoryStream())
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(requestStream, encoding, false))
|
||||
// Using JsonReaderWriterFactory directly to set encoding
|
||||
using (XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding, false))
|
||||
{
|
||||
serializer.WriteObject(jsonWriter, content);
|
||||
}
|
||||
};
|
||||
#endif
|
||||
}
|
||||
|
||||
// Set the content length in the request headers
|
||||
request.ContentLength = requestStream.Length;
|
||||
|
||||
using (Stream postStream = request.GetRequestStream())
|
||||
{
|
||||
requestStream.CopyToAndClose(postStream);
|
||||
}
|
||||
/// <summary>
|
||||
/// Creates an instance of <see cref="DataContractJsonSerializer"/> to
|
||||
/// serialize or deserialize an object of the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of instances to serialize or deserialize.</param>
|
||||
/// <returns>The serializer to use.</returns>
|
||||
protected virtual DataContractJsonSerializer GetSerializer(Type type)
|
||||
{
|
||||
if (this._knownTypes == null)
|
||||
{
|
||||
return new DataContractJsonSerializer(type);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new DataContractJsonSerializer(type, this._knownTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,14 +42,22 @@ namespace Spring.Http.Converters
|
||||
/// <summary>
|
||||
/// Default encoding for strings.
|
||||
/// </summary>
|
||||
#if SILVERLIGHT
|
||||
public static readonly Encoding DEFAULT_CHARSET = new UTF8Encoding(false); // Remove byte Order Mask (BOM)
|
||||
#else
|
||||
public static readonly Encoding DEFAULT_CHARSET = Encoding.GetEncoding("ISO-8859-1");
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="ByteArrayHttpMessageConverter"/>
|
||||
/// with 'text/plain; charset=ISO-8859-1', and '*/*' media types.
|
||||
/// </summary>
|
||||
public StringHttpMessageConverter() :
|
||||
#if SILVERLIGHT
|
||||
base(new MediaType("text", "plain", "UTF-8"), MediaType.ALL)
|
||||
#else
|
||||
base(new MediaType("text", "plain", "ISO-8859-1"), MediaType.ALL)
|
||||
#endif
|
||||
{
|
||||
}
|
||||
|
||||
@@ -67,13 +75,14 @@ namespace Spring.Http.Converters
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadInternal<T>(HttpWebResponse response)
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected override T ReadInternal<T>(IHttpInputMessage message)
|
||||
{
|
||||
// Get the response encoding
|
||||
// Get the message encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = MediaType.ParseMediaType(response.ContentType);
|
||||
MediaType mediaType = message.Headers.ContentType;
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = DEFAULT_CHARSET;
|
||||
@@ -83,8 +92,8 @@ namespace Spring.Http.Converters
|
||||
encoding = Encoding.GetEncoding(mediaType.CharSet);
|
||||
}
|
||||
|
||||
// Get the response stream
|
||||
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
|
||||
// Read from the message stream
|
||||
using (StreamReader reader = new StreamReader(message.Body, encoding))
|
||||
{
|
||||
return reader.ReadToEnd() as T;
|
||||
}
|
||||
@@ -93,13 +102,14 @@ namespace Spring.Http.Converters
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteInternal(object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected override void WriteInternal(object content, IHttpOutputMessage message)
|
||||
{
|
||||
// Get the request encoding
|
||||
// Get the message encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = MediaType.ParseMediaType(request.ContentType);
|
||||
MediaType mediaType = message.Headers.ContentType;
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = DEFAULT_CHARSET;
|
||||
@@ -112,14 +122,16 @@ namespace Spring.Http.Converters
|
||||
// Create a byte array of the data we want to send
|
||||
byte[] byteData = encoding.GetBytes(content as string);
|
||||
|
||||
// Set the content length in the request headers
|
||||
request.ContentLength = byteData.Length;
|
||||
//#if !SILVERLIGHT
|
||||
// // Set the content length in the message headers
|
||||
// message.Headers.ContentLength = byteData.Length;
|
||||
//#endif
|
||||
|
||||
// Write to the request
|
||||
using (Stream postStream = request.GetRequestStream())
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
postStream.Write(byteData, 0, byteData.Length);
|
||||
}
|
||||
stream.Write(byteData, 0, byteData.Length);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
using System.Net;
|
||||
using System.Web;
|
||||
using System.Text;
|
||||
using System.Collections.Specialized;
|
||||
|
||||
using Spring.Util;
|
||||
|
||||
namespace Spring.Http.Converters
|
||||
{
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can handle form data,
|
||||
/// including multipart form data (i.e. file uploads).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This converter supports the 'application/x-www-form-urlencoded' media type.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// For example, the following snippet shows how to submit an HTML form:
|
||||
/// <code>
|
||||
/// RestTemplate template = new RestTemplate(); // UrlEncodedFormHttpMessageConverter is configured by default
|
||||
/// NameValueCollection form = new NameValueCollection();
|
||||
/// form.Add("field 1", "value 1");
|
||||
/// form.Add("field 2", "value 2");
|
||||
/// form.Add("field 2", "value 3");
|
||||
/// template.PostForLocation("http://example.com/myForm", form);
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public class UrlEncodedFormHttpMessageConverter : AbstractHttpMessageConverter
|
||||
{
|
||||
private Encoding charset = Encoding.GetEncoding("ISO-8859-1");
|
||||
|
||||
/// <summary>
|
||||
/// Sets the encoding used for writing form data.
|
||||
/// </summary>
|
||||
public Encoding Charset
|
||||
{
|
||||
set { charset = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UrlEncodedFormHttpMessageConverter"/>
|
||||
/// with 'application/x-www-form-urlencoded' media type.
|
||||
/// </summary>
|
||||
public UrlEncodedFormHttpMessageConverter() :
|
||||
base(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the given class is supported by this converter.
|
||||
/// </summary>
|
||||
/// <param name="type">The type to test for support.</param>
|
||||
/// <returns><see langword="true"/> if supported; otherwise <see langword="false"/></returns>
|
||||
protected override bool Supports(Type type)
|
||||
{
|
||||
return type.Equals(typeof(NameValueCollection));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadInternal<T>(HttpWebResponse response)
|
||||
{
|
||||
// Get the response encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = MediaType.ParseMediaType(response.ContentType);
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = this.charset;
|
||||
}
|
||||
else
|
||||
{
|
||||
encoding = Encoding.GetEncoding(mediaType.CharSet);
|
||||
}
|
||||
|
||||
// Get the response stream
|
||||
string body;
|
||||
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
|
||||
{
|
||||
body = reader.ReadToEnd();
|
||||
}
|
||||
|
||||
string[] pairs = body.Split('&');
|
||||
NameValueCollection result = new NameValueCollection(pairs.Length);
|
||||
foreach (string pair in pairs)
|
||||
{
|
||||
int idx = pair.IndexOf('=');
|
||||
if (idx == -1)
|
||||
{
|
||||
result.Add(HttpUtility.UrlDecode(pair, this.charset), null);
|
||||
}
|
||||
else
|
||||
{
|
||||
string name = HttpUtility.UrlDecode(pair.Substring(0, idx), this.charset);
|
||||
string value = HttpUtility.UrlDecode(pair.Substring(idx + 1), this.charset);
|
||||
result.Add(name, value);
|
||||
}
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteInternal(object content, HttpWebRequest request)
|
||||
{
|
||||
StringBuilder builder = new StringBuilder();
|
||||
NameValueCollection form = content as NameValueCollection;
|
||||
for(int i=0; i < form.AllKeys.Length; i++)
|
||||
{
|
||||
string name = form.GetKey(i);
|
||||
string[] values = form.GetValues(name);
|
||||
if (values == null)
|
||||
{
|
||||
builder.Append(HttpUtility.UrlEncode(name, this.charset));
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int j = 0; j < values.Length; j++)
|
||||
{
|
||||
string value = values[j];
|
||||
builder.Append(HttpUtility.UrlEncode(name, this.charset));
|
||||
builder.Append('=');
|
||||
builder.Append(HttpUtility.UrlEncode(value, this.charset));
|
||||
if (j != (values.Length - 1))
|
||||
{
|
||||
builder.Append('&');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i != (form.AllKeys.Length - 1))
|
||||
{
|
||||
builder.Append('&');
|
||||
}
|
||||
}
|
||||
|
||||
// Create a byte array of the data we want to send
|
||||
byte[] byteData = this.charset.GetBytes(builder.ToString());
|
||||
|
||||
// Set the content length in the request headers
|
||||
request.ContentLength = byteData.Length;
|
||||
|
||||
// Write to the request
|
||||
using (Stream postStream = request.GetRequestStream())
|
||||
{
|
||||
postStream.Write(byteData, 0, byteData.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -40,26 +40,7 @@ namespace Spring.Http.Converters.Xml
|
||||
/// <summary>
|
||||
/// Default encoding for XML.
|
||||
/// </summary>
|
||||
public static readonly Encoding DEFAULT_CHARSET = new UTF8Encoding(false); // Remove byte Order Mask (BOM) when using XmlTextWriter
|
||||
|
||||
private XmlReaderSettings _xmlReaderSettings;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="XmlReaderSettings">XmlReader settings</see>
|
||||
/// used by this converter to read from the HTTP response.
|
||||
/// </summary>
|
||||
public XmlReaderSettings XmlReaderSettings
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_xmlReaderSettings == null)
|
||||
{
|
||||
_xmlReaderSettings = this.GetDefaultXmlReaderSettings();
|
||||
}
|
||||
return _xmlReaderSettings;
|
||||
}
|
||||
set { _xmlReaderSettings = value; }
|
||||
}
|
||||
public static readonly Encoding DEFAULT_CHARSET = new UTF8Encoding(false); // Remove byte Order Mask (BOM)
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="AbstractHttpMessageConverter"/>
|
||||
@@ -84,29 +65,31 @@ namespace Spring.Http.Converters.Xml
|
||||
/// Abstract template method that reads the actualy object. Invoked from <see cref="M:Read"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <param name="message">The HTTP message to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadInternal<T>(HttpWebResponse response)
|
||||
/// <exception cref="HttpMessageNotReadableException">In case of conversion errors</exception>
|
||||
protected override T ReadInternal<T>(IHttpInputMessage message)
|
||||
{
|
||||
using (Stream stream = response.GetResponseStream())
|
||||
XmlReaderSettings settings = this.GetXmlReaderSettings();
|
||||
|
||||
// Read from the message stream
|
||||
using (XmlReader xmlReader = XmlReader.Create(message.Body, settings))
|
||||
{
|
||||
using (XmlReader xmlReader = XmlReader.Create(stream, this.XmlReaderSettings))
|
||||
{
|
||||
return ReadXml<T>(xmlReader, response);
|
||||
}
|
||||
return ReadXml<T>(xmlReader);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body. Invoked from <see cref="M:Write"/>.
|
||||
/// </summary>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteInternal(object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
/// <param name="message">The HTTP message to write to.</param>
|
||||
/// <exception cref="HttpMessageNotWritableException">In case of conversion errors</exception>
|
||||
protected override void WriteInternal(object content, IHttpOutputMessage message)
|
||||
{
|
||||
// Get the request encoding
|
||||
// Get the message encoding
|
||||
Encoding encoding;
|
||||
MediaType mediaType = MediaType.ParseMediaType(request.ContentType);
|
||||
MediaType mediaType = message.Headers.ContentType;
|
||||
if (mediaType == null || !StringUtils.HasText(mediaType.CharSet))
|
||||
{
|
||||
encoding = DEFAULT_CHARSET;
|
||||
@@ -116,22 +99,17 @@ namespace Spring.Http.Converters.Xml
|
||||
encoding = Encoding.GetEncoding(mediaType.CharSet);
|
||||
}
|
||||
|
||||
// Write to the request
|
||||
using (IgnoreCloseMemoryStream requestStream = new IgnoreCloseMemoryStream())
|
||||
XmlWriterSettings settings = this.GetXmlWriterSettings();
|
||||
settings.Encoding = encoding;
|
||||
|
||||
// Write to the message stream
|
||||
message.Body = delegate(Stream stream)
|
||||
{
|
||||
using (XmlTextWriter xmlWriter = new XmlTextWriter(requestStream, encoding))
|
||||
using (XmlWriter xmlWriter = XmlWriter.Create(stream, settings))
|
||||
{
|
||||
WriteXml(xmlWriter, content, request);
|
||||
WriteXml(xmlWriter, content);
|
||||
}
|
||||
|
||||
// Set the content length in the request headers
|
||||
request.ContentLength = requestStream.Length;
|
||||
|
||||
using (Stream postStream = request.GetRequestStream())
|
||||
{
|
||||
requestStream.CopyToAndClose(postStream);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -139,24 +117,22 @@ namespace Spring.Http.Converters.Xml
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected abstract T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response) where T : class;
|
||||
protected abstract T ReadXml<T>(XmlReader xmlReader) where T : class;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected abstract void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request);
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected abstract void WriteXml(XmlWriter xmlWriter, object content);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default <see cref="XmlReaderSettings">XmlReader settings</see>
|
||||
/// used by this converter to read from the HTTP response.
|
||||
/// Returns the <see cref="XmlReaderSettings">XmlReader settings</see>
|
||||
/// used by this converter to read from the HTTP message.
|
||||
/// </summary>
|
||||
/// <returns>The XmlReader settings.</returns>
|
||||
protected virtual XmlReaderSettings GetDefaultXmlReaderSettings()
|
||||
protected virtual XmlReaderSettings GetXmlReaderSettings()
|
||||
{
|
||||
XmlReaderSettings settings = new XmlReaderSettings();
|
||||
settings.ConformanceLevel = ConformanceLevel.Auto;
|
||||
@@ -165,5 +141,20 @@ namespace Spring.Http.Converters.Xml
|
||||
settings.IgnoreWhitespace = true;
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the <see cref="XmlWriterSettings">XmlWriter settings</see>
|
||||
/// used by this converter to write to the HTTP message.
|
||||
/// </summary>
|
||||
/// <returns>The XmlWriter settings.</returns>
|
||||
protected virtual XmlWriterSettings GetXmlWriterSettings()
|
||||
{
|
||||
XmlWriterSettings settings = new XmlWriterSettings();
|
||||
settings.CloseOutput = false;
|
||||
settings.NewLineHandling = NewLineHandling.Entitize;
|
||||
settings.OmitXmlDeclaration = true;
|
||||
settings.CheckCharacters = false;
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_0
|
||||
#if NET_3_0 || SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,11 +23,10 @@ using System;
|
||||
using System.Net;
|
||||
using System.Xml;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Spring.Http.Converters.Xml
|
||||
{
|
||||
// TODO : Support for known types, etc...
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can read and write XML
|
||||
/// using <see cref="DataContractSerializer"/>.
|
||||
@@ -45,6 +44,17 @@ namespace Spring.Http.Converters.Xml
|
||||
/// <author>Bruno Baia</author>
|
||||
public class DataContractHttpMessageConverter : AbstractXmlHttpMessageConverter
|
||||
{
|
||||
private IEnumerable<Type> _knownTypes;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets types that may be present in the object graph.
|
||||
/// </summary>
|
||||
public IEnumerable<Type> KnownTypes
|
||||
{
|
||||
get { return _knownTypes; }
|
||||
set { _knownTypes = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="DataContractHttpMessageConverter"/>
|
||||
/// with 'text/xml', 'application/xml', and 'application/*-xml' media types.
|
||||
@@ -72,11 +82,10 @@ namespace Spring.Http.Converters.Xml
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response)
|
||||
protected override T ReadXml<T>(XmlReader xmlReader)
|
||||
{
|
||||
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
|
||||
DataContractSerializer serializer = this.GetSerializer(typeof(T));
|
||||
return serializer.ReadObject(xmlReader) as T;
|
||||
}
|
||||
|
||||
@@ -84,13 +93,30 @@ namespace Spring.Http.Converters.Xml
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
DataContractSerializer serializer = new DataContractSerializer(content.GetType());
|
||||
DataContractSerializer serializer = this.GetSerializer(content.GetType());
|
||||
serializer.WriteObject(xmlWriter, content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of <see cref="DataContractSerializer"/> to
|
||||
/// serialize or deserialize an object of the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of instances to serialize or deserialize.</param>
|
||||
/// <returns>The serializer to use.</returns>
|
||||
protected virtual DataContractSerializer GetSerializer(Type type)
|
||||
{
|
||||
if (this._knownTypes == null)
|
||||
{
|
||||
return new DataContractSerializer(type);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new DataContractSerializer(type, this._knownTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,8 +1,8 @@
|
||||
#if NET_3_5
|
||||
#if NET_3_5 || WINDOWS_PHONE
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -26,8 +26,6 @@ using System.Xml.Linq;
|
||||
|
||||
namespace Spring.Http.Converters.Xml
|
||||
{
|
||||
// TODO : Support XElement.Load options
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can read and write XML
|
||||
/// from a <see cref="XElement"/> (Linq to XML).
|
||||
@@ -63,9 +61,8 @@ namespace Spring.Http.Converters.Xml
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response)
|
||||
protected override T ReadXml<T>(XmlReader xmlReader)
|
||||
{
|
||||
return XElement.Load(xmlReader) as T;
|
||||
}
|
||||
@@ -74,9 +71,8 @@ namespace Spring.Http.Converters.Xml
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
XElement xElement = content as XElement;
|
||||
xElement.WriteTo(xmlWriter);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#region License
|
||||
#if !SILVERLIGHT
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -59,9 +60,8 @@ namespace Spring.Http.Converters.Xml
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response)
|
||||
protected override T ReadXml<T>(XmlReader xmlReader)
|
||||
{
|
||||
XmlDocument document = new XmlDocument();
|
||||
document.Load(xmlReader);
|
||||
@@ -72,12 +72,12 @@ namespace Spring.Http.Converters.Xml
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
XmlDocument document = content as XmlDocument;
|
||||
document.WriteTo(xmlWriter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,7 +1,8 @@
|
||||
#region License
|
||||
#if !SILVERLIGHT || WINDOWS_PHONE
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,14 +20,12 @@
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Xml;
|
||||
using System.Net;
|
||||
using System.Xml;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace Spring.Http.Converters.Xml
|
||||
{
|
||||
// TODO : Support for known types, etc...
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of <see cref="IHttpMessageConverter"/> that can read and write XML
|
||||
/// using <see cref="XmlSerializer"/>.
|
||||
@@ -38,6 +37,17 @@ namespace Spring.Http.Converters.Xml
|
||||
/// <author>Bruno Baia</author>
|
||||
public class XmlSerializableHttpMessageConverter : AbstractXmlHttpMessageConverter
|
||||
{
|
||||
private Type[] _knownTypes;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets types that may be present in the object graph.
|
||||
/// </summary>
|
||||
public Type[] KnownTypes
|
||||
{
|
||||
get { return _knownTypes; }
|
||||
set { _knownTypes = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="XmlSerializableHttpMessageConverter"/>
|
||||
/// with 'text/xml', 'application/xml', and 'application/*-xml' media types.
|
||||
@@ -65,11 +75,10 @@ namespace Spring.Http.Converters.Xml
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of object to return.</typeparam>
|
||||
/// <param name="xmlReader">The XmlReader to use.</param>
|
||||
/// <param name="response">The HTTP response to read from.</param>
|
||||
/// <returns>The converted object.</returns>
|
||||
protected override T ReadXml<T>(XmlReader xmlReader, HttpWebResponse response)
|
||||
protected override T ReadXml<T>(XmlReader xmlReader)
|
||||
{
|
||||
XmlSerializer serializer = new XmlSerializer(typeof(T));
|
||||
XmlSerializer serializer = this.GetSerializer(typeof(T));
|
||||
return serializer.Deserialize(xmlReader) as T;
|
||||
}
|
||||
|
||||
@@ -77,12 +86,30 @@ namespace Spring.Http.Converters.Xml
|
||||
/// Abstract template method that writes the actual body using a <see cref="XmlWriter"/>. Invoked from <see cref="M:WriteInternal"/>.
|
||||
/// </summary>
|
||||
/// <param name="xmlWriter">The XmlWriter to use.</param>
|
||||
/// <param name="content">The object to write to the HTTP request.</param>
|
||||
/// <param name="request">The HTTP request to write to.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content, HttpWebRequest request)
|
||||
/// <param name="content">The object to write to the HTTP message.</param>
|
||||
protected override void WriteXml(XmlWriter xmlWriter, object content)
|
||||
{
|
||||
XmlSerializer serializer = new XmlSerializer(content.GetType());
|
||||
XmlSerializer serializer = this.GetSerializer(content.GetType());
|
||||
serializer.Serialize(xmlWriter, content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of <see cref="XmlSerializer"/> to
|
||||
/// serialize or deserialize an object of the specified type.
|
||||
/// </summary>
|
||||
/// <param name="type">The type of instances to serialize or deserialize.</param>
|
||||
/// <returns>The serializer to use.</returns>
|
||||
protected virtual XmlSerializer GetSerializer(Type type)
|
||||
{
|
||||
if (this._knownTypes == null)
|
||||
{
|
||||
return new XmlSerializer(type);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new XmlSerializer(type, this._knownTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,129 +0,0 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Security.Cryptography.X509Certificates;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Factory for <see cref="HttpWebRequest"/> objects. Requests are created by the <see cref="M:CreateRequest"/> method.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public class DefaultHttpWebRequestFactory : IHttpWebRequestFactory
|
||||
{
|
||||
// TODO : Add other properties
|
||||
|
||||
private X509CertificateCollection _clientCertificates;
|
||||
private ICredentials _credentials;
|
||||
private IWebProxy _proxy;
|
||||
private int? _timeout;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of security certificates that are associated with this request.
|
||||
/// </summary>
|
||||
public X509CertificateCollection ClientCertificates
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this._clientCertificates == null)
|
||||
{
|
||||
this._clientCertificates = new X509CertificateCollection();
|
||||
}
|
||||
return this._clientCertificates;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets authentication information for the request.
|
||||
/// </summary>
|
||||
public ICredentials Credentials
|
||||
{
|
||||
get { return _credentials; }
|
||||
set { _credentials = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets proxy information for the request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default value is set by calling the <see cref="P:System.Net.GlobalProxySelection.Select"/> property.
|
||||
/// </remarks>
|
||||
public IWebProxy Proxy
|
||||
{
|
||||
get { return _proxy; }
|
||||
set { _proxy = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time-out value in milliseconds for the <see cref="M:System.Net.HttpWebRequest.GetResponse()"/>
|
||||
/// and <see cref="M:System.Net.HttpWebRequest.GetRequestStream()"/> methods.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default is 100,000 milliseconds (100 seconds).
|
||||
/// </remarks>
|
||||
public int? Timeout
|
||||
{
|
||||
get { return _timeout; }
|
||||
set { _timeout = value; }
|
||||
}
|
||||
|
||||
#region IHttpWebRequestFactory Membres
|
||||
|
||||
/// <summary>
|
||||
/// Create a new <see cref="HttpWebRequest"/> for the specified URI.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to create a request for.</param>
|
||||
/// <returns>The created request</returns>
|
||||
public HttpWebRequest CreateRequest(Uri uri)
|
||||
{
|
||||
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
|
||||
|
||||
if (this._clientCertificates != null)
|
||||
{
|
||||
foreach (X509Certificate2 certificate in this._clientCertificates)
|
||||
{
|
||||
request.ClientCertificates.Add(certificate);
|
||||
}
|
||||
}
|
||||
|
||||
if (this._credentials != null)
|
||||
{
|
||||
request.Credentials = this._credentials;
|
||||
}
|
||||
|
||||
if (this._proxy != null)
|
||||
{
|
||||
request.Proxy = this._proxy;
|
||||
}
|
||||
|
||||
if (this._timeout != null)
|
||||
{
|
||||
request.Timeout = this._timeout.Value;
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
60
src/Spring/Spring.Http/Http/HttpEntity.cs
Normal file
60
src/Spring/Spring.Http/Http/HttpEntity.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Net;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a HTTP entity message, as defined in the HTTP specification.
|
||||
/// <a href="http://tools.ietf.org/html/rfc2616#section-7">HTTP 1.1, section 7</a>
|
||||
/// </summary>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class HttpEntity : HttpEntity<object>
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity"/> with the given body.
|
||||
/// </summary>
|
||||
/// <param name="body">The entity body.</param>
|
||||
public HttpEntity(object body) :
|
||||
base(body)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity"/> with the given headers.
|
||||
/// </summary>
|
||||
/// <param name="headers">The entity headers.</param>
|
||||
public HttpEntity(HttpHeaders headers) :
|
||||
base(headers)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity"/> with the given body and headers.
|
||||
/// </summary>
|
||||
/// <param name="body">The entity body.</param>
|
||||
/// <param name="headers">The entity headers.</param>
|
||||
public HttpEntity(object body, HttpHeaders headers) :
|
||||
base(body, headers)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
91
src/Spring/Spring.Http/Http/HttpEntity`1.cs
Normal file
91
src/Spring/Spring.Http/Http/HttpEntity`1.cs
Normal file
@@ -0,0 +1,91 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Net;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a HTTP entity message, as defined in the HTTP specification.
|
||||
/// <a href="http://tools.ietf.org/html/rfc2616#section-7">HTTP 1.1, section 7</a>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the entity body.</typeparam>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public class HttpEntity<T> where T : class
|
||||
{
|
||||
private HttpHeaders headers;
|
||||
private T body;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entity headers.
|
||||
/// </summary>
|
||||
public HttpHeaders Headers
|
||||
{
|
||||
get { return this.headers; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entity body. May be null.
|
||||
/// </summary>
|
||||
public T Body
|
||||
{
|
||||
get { return this.body; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether this entity has a body.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool HasBody
|
||||
{
|
||||
get { return (this.body != null); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity{T}"/> with the given body.
|
||||
/// </summary>
|
||||
/// <param name="body">The entity body.</param>
|
||||
public HttpEntity(T body)
|
||||
: this(body, new HttpHeaders())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity{T}"/> with the given headers.
|
||||
/// </summary>
|
||||
/// <param name="headers">The entity headers.</param>
|
||||
public HttpEntity(HttpHeaders headers)
|
||||
: this(null, headers)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpEntity{T}"/> with the given body and headers.
|
||||
/// </summary>
|
||||
/// <param name="body">The entity body.</param>
|
||||
/// <param name="headers">The entity headers.</param>
|
||||
public HttpEntity(T body, HttpHeaders headers)
|
||||
{
|
||||
this.body = body;
|
||||
this.headers = headers;
|
||||
}
|
||||
}
|
||||
}
|
||||
503
src/Spring/Spring.Http/Http/HttpHeaders.cs
Normal file
503
src/Spring/Spring.Http/Http/HttpHeaders.cs
Normal file
@@ -0,0 +1,503 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Collections.Generic;
|
||||
|
||||
using Spring.Util;
|
||||
#if SILVERLIGHT
|
||||
using Spring.Collections.Specialized;
|
||||
#else
|
||||
using System.Collections.Specialized;
|
||||
#endif
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents HTTP request and response headers, mapping string header names to list of string values.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public class HttpHeaders : NameValueCollection
|
||||
{
|
||||
private const string ACCEPT = "Accept";
|
||||
private const string ACCEPT_CHARSET = "Accept-Charset";
|
||||
private const string ALLOW = "Allow";
|
||||
private const string CACHE_CONTROL = "Cache-Control";
|
||||
private const string CONTENT_LENGTH = "Content-Length";
|
||||
private const string CONTENT_TYPE = "Content-Type";
|
||||
private const string DATE = "Date";
|
||||
private const string ETAG = "ETag";
|
||||
private const string EXPIRES = "Expires";
|
||||
private const string IF_MODIFIED_SINCE = "If-Modified-Since";
|
||||
private const string IF_NONE_MATCH = "If-None-Match";
|
||||
private const string LAST_MODIFIED = "Last-Modified";
|
||||
private const string LOCATION = "Location";
|
||||
private const string PRAGMA = "Pragma";
|
||||
|
||||
private static readonly DateTimeFormatInfo DateTimeFormatInfo = new DateTimeFormatInfo();
|
||||
|
||||
#region Constructor(s)
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new, empty instance of the <see cref="HttpHeaders"/> object.
|
||||
/// </summary>
|
||||
public HttpHeaders() :
|
||||
base(8, StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the array of acceptable <see cref="MediaType">media types</see>,
|
||||
/// as specified by the 'Accept' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns an empty array when the acceptable media types are unspecified.
|
||||
/// </remarks>
|
||||
public MediaType[] Accept
|
||||
{
|
||||
get
|
||||
{
|
||||
string[] values = this.GetMultiValues(ACCEPT);
|
||||
if (values == null || values.Length == 0)
|
||||
{
|
||||
return new MediaType[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
MediaType[] result = new MediaType[values.Length];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
result[i] = MediaType.Parse(values[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
foreach (MediaType mediaType in value)
|
||||
{
|
||||
this.Add(ACCEPT, mediaType.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//**
|
||||
// * Set the list of acceptable {@linkplain Charset charsets}, as specified by the {@code Accept-Charset} header.
|
||||
// * @param acceptableCharsets the acceptable charsets
|
||||
// */
|
||||
//public void setAcceptCharset(List<Charset> acceptableCharsets) {
|
||||
// StringBuilder builder = new StringBuilder();
|
||||
// for (Iterator<Charset> iterator = acceptableCharsets.iterator(); iterator.hasNext();) {
|
||||
// Charset charset = iterator.next();
|
||||
// builder.append(charset.name().toLowerCase(Locale.ENGLISH));
|
||||
// if (iterator.hasNext()) {
|
||||
// builder.append(", ");
|
||||
// }
|
||||
// }
|
||||
// set(ACCEPT_CHARSET, builder.toString());
|
||||
//}
|
||||
|
||||
//**
|
||||
// * Return the list of acceptable {@linkplain Charset charsets}, as specified by the {@code Accept-Charset}
|
||||
// * header.
|
||||
// * @return the acceptable charsets
|
||||
// */
|
||||
//public List<Charset> getAcceptCharset() {
|
||||
// List<Charset> result = new ArrayList<Charset>();
|
||||
// String value = getFirst(ACCEPT_CHARSET);
|
||||
// if (value != null) {
|
||||
// String[] tokens = value.split(",\\s*");
|
||||
// for (String token : tokens) {
|
||||
// int paramIdx = token.indexOf(';');
|
||||
// if (paramIdx == -1) {
|
||||
// result.add(Charset.forName(token));
|
||||
// }
|
||||
// else {
|
||||
// result.add(Charset.forName(token.substring(0, paramIdx)));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return result;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the array of allowed <see cref="HttpMethod">HTTP methods</see>,
|
||||
/// as specified by the 'Allow' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns an empty array when the allowed methods are unspecified.
|
||||
/// </remarks>
|
||||
public HttpMethod[] Allow
|
||||
{
|
||||
get
|
||||
{
|
||||
string[] values = this.GetMultiValues(ALLOW);
|
||||
if (values == null || values.Length == 0)
|
||||
{
|
||||
return new HttpMethod[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
HttpMethod[] result = new HttpMethod[values.Length];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
result[i] = (HttpMethod)Enum.Parse(typeof(HttpMethod), values[i], true);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
foreach (HttpMethod method in value)
|
||||
{
|
||||
this.Add(ALLOW, method.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'Cache-Control' header.
|
||||
/// </summary>
|
||||
public string CacheControl
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Get(CACHE_CONTROL);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(CACHE_CONTROL, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the length of the body in bytes,
|
||||
/// as specified by the 'Content-Length' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns -1 when the content-length is unknown.
|
||||
/// </remarks>
|
||||
public long ContentLength
|
||||
{
|
||||
get
|
||||
{
|
||||
string value = this.GetSingleValue(CONTENT_LENGTH);
|
||||
return (value != null ? long.Parse(value) : -1);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(CONTENT_LENGTH, value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="MediaType">media type</see> of the body,
|
||||
/// as specified by the 'Content-Type' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns <see langword="null"/> when the content type is unknown.
|
||||
/// </remarks>
|
||||
public MediaType ContentType
|
||||
{
|
||||
get
|
||||
{
|
||||
string value = this.GetSingleValue(CONTENT_TYPE);
|
||||
return (value != null ? MediaType.Parse(value) : null);
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value.IsWildcardType)
|
||||
{
|
||||
throw new ArgumentException("'Content-Type' header cannot contain wildcard type '*'", "Content-Type");
|
||||
}
|
||||
if (value.IsWildcardSubtype)
|
||||
{
|
||||
throw new ArgumentException("'Content-Type' header cannot contain wildcard subtype '*'", "Content-Type");
|
||||
}
|
||||
this.Set(CONTENT_TYPE, value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
//**
|
||||
// * Returns the date and time at which the message was created, as specified by the {@code Date} header.
|
||||
// * <p>The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
|
||||
// * @return the creation date/time
|
||||
// * @throws IllegalArgumentException if the value can't be converted to a date
|
||||
// */
|
||||
//**
|
||||
// * Sets the date and time at which the message was created, as specified by the {@code Date} header.
|
||||
// * <p>The date should be specified as the number of milliseconds since January 1, 1970 GMT.
|
||||
// * @param date the date
|
||||
// */
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time at which the message was created,
|
||||
/// as specified by the 'Date' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns <see langword="null"/> when the date is unknown.
|
||||
/// </remarks>
|
||||
public DateTime? Date
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.GetSingleDate(DATE);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.SetDate(DATE, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the entity tag of the body, as specified by the 'ETag' header.
|
||||
/// </summary>
|
||||
public string ETag
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Unquote(this.Get(ETAG));
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(ETAG, this.Quote(value));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time at which the message is no longer valid,
|
||||
/// as specified by the 'Expires' header.
|
||||
/// </summary>
|
||||
public string Expires
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Get(EXPIRES);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(EXPIRES, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time as specified by the 'If-Modified-Since' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns <see langword="null"/> when the date is unknown.
|
||||
/// </remarks>
|
||||
public DateTime? IfModifiedSince
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.GetSingleDate(IF_MODIFIED_SINCE);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.SetDate(IF_MODIFIED_SINCE, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'If-None-Match' header.
|
||||
/// </summary>
|
||||
public string[] IfNoneMatch
|
||||
{
|
||||
get
|
||||
{
|
||||
string[] values = this.GetMultiValues(IF_NONE_MATCH);
|
||||
if (values == null || values.Length == 0)
|
||||
{
|
||||
return new string[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] result = new string[values.Length];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
result[i] = Unquote(values[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
foreach (string str in value)
|
||||
{
|
||||
this.Add(IF_NONE_MATCH, this.Quote(str));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time the resource was last changed,
|
||||
/// as specified by the 'Last-Modified' header.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns <see langword="null"/> when the date is unknown.
|
||||
/// </remarks>
|
||||
public DateTime? LastModified
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.GetSingleDate(LAST_MODIFIED);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.SetDate(LAST_MODIFIED, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the (new) location of a resource,
|
||||
/// as specified by the 'Location' header.
|
||||
/// </summary>
|
||||
public Uri Location
|
||||
{
|
||||
get
|
||||
{
|
||||
string value = this.GetSingleValue(LOCATION);
|
||||
return (value != null ? new Uri(value, UriKind.RelativeOrAbsolute) : null);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(LOCATION, value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the value of the 'Pragma' header.
|
||||
/// </summary>
|
||||
public string Pragma
|
||||
{
|
||||
get
|
||||
{
|
||||
return this.Get(PRAGMA);
|
||||
}
|
||||
set
|
||||
{
|
||||
this.Set(PRAGMA, value);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private methods
|
||||
|
||||
private string Quote(string s)
|
||||
{
|
||||
if (s == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (!s.StartsWith("\"") && !s.EndsWith("\""))
|
||||
{
|
||||
s = "\"" + s + "\"";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private string Unquote(string s)
|
||||
{
|
||||
if (s == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (s.StartsWith("\"") && s.EndsWith("\""))
|
||||
{
|
||||
s = s.Substring(1, s.Length - 2);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private DateTime? GetSingleDate(string headerName)
|
||||
{
|
||||
string headerValue = GetSingleValue(headerName);
|
||||
if (headerValue != null)
|
||||
{
|
||||
return DateTime.Parse(headerValue, DateTimeFormatInfo).ToUniversalTime();
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetDate(string headerName, DateTime? date)
|
||||
{
|
||||
if (date.HasValue)
|
||||
{
|
||||
this.Set(headerName, date.Value.ToUniversalTime().ToString("R", DateTimeFormatInfo));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Remove(headerName);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Return the header value for the given header name, if any.
|
||||
/// </summary>
|
||||
/// <param name="headerName">The header name</param>
|
||||
/// <returns>The first header value; or <see langword="null"/></returns>
|
||||
/// <exception cref="NotSupportedException">
|
||||
/// If multiple values are stored for the given header name.
|
||||
/// </exception>
|
||||
public string GetSingleValue(string headerName)
|
||||
{
|
||||
string[] headerValues = this.GetValues(headerName);
|
||||
if (headerValues == null || headerValues.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (headerValues.Length == 1)
|
||||
{
|
||||
return headerValues[0];
|
||||
}
|
||||
throw new NotSupportedException(String.Format(
|
||||
"Multiple values not supported for header '{0}'", headerName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return an array of header values for the given header name, if any.
|
||||
/// </summary>
|
||||
/// <param name="headerName">The header name</param>
|
||||
/// <returns>The array of header values; or <see langword="null"/></returns>
|
||||
public string[] GetMultiValues(string headerName)
|
||||
{
|
||||
string headerValue = this.Get(headerName);
|
||||
if (headerValue == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
return headerValue.Split(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,7 +25,7 @@ namespace Spring.Http
|
||||
/// <a href="http://tools.ietf.org/html/rfc2616#section-5.1.1">HTTP 1.1, section 6</a>
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public enum HttpMethod
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,7 +23,7 @@ using System.Net;
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a HTTP response message with no entity.
|
||||
/// Represents a HTTP response message with no body.
|
||||
/// </summary>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class HttpResponseMessage : HttpResponseMessage<object>
|
||||
@@ -44,7 +44,7 @@ namespace Spring.Http
|
||||
/// <param name="headers">The response headers.</param>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpResponseMessage(WebHeaderCollection headers, HttpStatusCode statusCode, string statusDescription) :
|
||||
public HttpResponseMessage(HttpHeaders headers, HttpStatusCode statusCode, string statusDescription) :
|
||||
base(null, headers, statusCode, statusDescription)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -28,29 +28,11 @@ namespace Spring.Http
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the response body.</typeparam>
|
||||
/// <author>Bruno Baia</author>
|
||||
public class HttpResponseMessage<T> where T : class
|
||||
public class HttpResponseMessage<T> : HttpEntity<T> where T : class
|
||||
{
|
||||
private WebHeaderCollection headers;
|
||||
private T body;
|
||||
private HttpStatusCode statusCode;
|
||||
private string statusDescription;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the response headers.
|
||||
/// </summary>
|
||||
public WebHeaderCollection Headers
|
||||
{
|
||||
get { return this.headers; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the response body. May be null.
|
||||
/// </summary>
|
||||
public T Body
|
||||
{
|
||||
get { return this.body; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status code of the response.
|
||||
/// </summary>
|
||||
@@ -94,7 +76,7 @@ namespace Spring.Http
|
||||
/// <param name="headers">The response headers.</param>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpResponseMessage(WebHeaderCollection headers, HttpStatusCode statusCode, string statusDescription) :
|
||||
public HttpResponseMessage(HttpHeaders headers, HttpStatusCode statusCode, string statusDescription) :
|
||||
this(null, headers, statusCode, statusDescription)
|
||||
{
|
||||
}
|
||||
@@ -106,12 +88,11 @@ namespace Spring.Http
|
||||
/// <param name="headers">The response headers.</param>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpResponseMessage(T body, WebHeaderCollection headers, HttpStatusCode statusCode, string statusDescription)
|
||||
public HttpResponseMessage(T body, HttpHeaders headers, HttpStatusCode statusCode, string statusDescription) :
|
||||
base(body, headers)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.statusDescription = statusDescription;
|
||||
this.body = body;
|
||||
this.headers = headers;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
47
src/Spring/Spring.Http/Http/IHttpInputMessage.cs
Normal file
47
src/Spring/Spring.Http/Http/IHttpInputMessage.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents an HTTP message, consisting of <see cref="P:Headers">headers</see>
|
||||
/// and a readable <see cref="P:Body">body</see>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Typically implemented by an HTTP request on the server-side, or a response on the client-side.
|
||||
/// </remarks>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public interface IHttpInputMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the message headers.
|
||||
/// </summary>
|
||||
HttpHeaders Headers { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the body of the message as a stream.
|
||||
/// </summary>
|
||||
Stream Body { get; }
|
||||
}
|
||||
}
|
||||
47
src/Spring/Spring.Http/Http/IHttpOutputMessage.cs
Normal file
47
src/Spring/Spring.Http/Http/IHttpOutputMessage.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.IO;
|
||||
|
||||
namespace Spring.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents an HTTP message, consisting of <see cref="P:Headers">headers</see>
|
||||
/// and a writable <see cref="P:Body">body</see>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Typically implemented by an HTTP request on the client-side, or a response on the server-side.
|
||||
/// </remarks>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
public interface IHttpOutputMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the message headers.
|
||||
/// </summary>
|
||||
HttpHeaders Headers { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Sets the delegate that writes the body message as a stream.
|
||||
/// </summary>
|
||||
Action<Stream> Body { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2010 the original author or authors.
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -255,8 +255,8 @@ namespace Spring.Http
|
||||
AssertUtils.ArgumentHasText(subtype, "'subtype' must not be empty");
|
||||
//checkToken(type);
|
||||
//checkToken(subtype);
|
||||
this.type = type.ToLowerInvariant();
|
||||
this.subtype = subtype.ToLowerInvariant();
|
||||
this.type = type.ToLower(CultureInfo.InvariantCulture);
|
||||
this.subtype = subtype.ToLower(CultureInfo.InvariantCulture);
|
||||
this.parameters = new Dictionary<string, string>(parameters, StringComparer.InvariantCultureIgnoreCase);
|
||||
//if (parameters.Count > 0)
|
||||
//{
|
||||
@@ -550,9 +550,12 @@ namespace Spring.Http
|
||||
/// <summary>
|
||||
/// Parse the given String into a single <see cref="MediaType"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method can be used to parse a 'Content-Type' header.
|
||||
/// </remarks>
|
||||
/// <param name="mediaType">The string to parse.</param>
|
||||
/// <returns>The media type.</returns>
|
||||
public static MediaType ParseMediaType(string mediaType)
|
||||
public static MediaType Parse(string mediaType)
|
||||
{
|
||||
if (!StringUtils.HasText(mediaType))
|
||||
{
|
||||
@@ -600,29 +603,6 @@ namespace Spring.Http
|
||||
return new MediaType(type, subtype, parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parse the given, comma-seperated string into a list of <see cref="MediaType"/> objects.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method can be used to parse an 'Accept' or 'Content-Type' header.
|
||||
/// </remarks>
|
||||
/// <param name="mediaTypes">The string to parse.</param>
|
||||
/// <returns>The list of media types.</returns>
|
||||
public static List<MediaType> ParseMediaTypes(string mediaTypes)
|
||||
{
|
||||
List<MediaType> mediaTypeList = new List<MediaType>();
|
||||
if (!StringUtils.HasText(mediaTypes))
|
||||
{
|
||||
return mediaTypeList;
|
||||
}
|
||||
string[] tokens = mediaTypes.Split(',');
|
||||
foreach (string token in tokens)
|
||||
{
|
||||
mediaTypeList.Add(ParseMediaType(token));
|
||||
}
|
||||
return mediaTypeList;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return a string representation of the given list of <see cref="MediaType"/> objects.
|
||||
/// </summary>
|
||||
@@ -638,7 +618,7 @@ namespace Spring.Http
|
||||
{
|
||||
if (builder.Length > 0)
|
||||
{
|
||||
builder.Append(", ");
|
||||
builder.Append(',');
|
||||
}
|
||||
builder.Append(mediaType);
|
||||
}
|
||||
|
||||
76
src/Spring/Spring.Http/Http/Rest/HttpClientErrorException.cs
Normal file
76
src/Spring/Spring.Http/Http/Rest/HttpClientErrorException.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
|
||||
namespace Spring.Http.Rest
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception thrown when an HTTP 4xx is received.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpClientErrorException : HttpStatusCodeException
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpClientErrorException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/>.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
public HttpClientErrorException(HttpStatusCode statusCode)
|
||||
: base (statusCode)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpClientErrorException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/> and a status description.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpClientErrorException(HttpStatusCode statusCode, string statusDescription)
|
||||
: base (statusCode, statusDescription)
|
||||
{
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpClientErrorException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpClientErrorException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
76
src/Spring/Spring.Http/Http/Rest/HttpServerErrorException.cs
Normal file
76
src/Spring/Spring.Http/Http/Rest/HttpServerErrorException.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
|
||||
namespace Spring.Http.Rest
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception thrown when an HTTP 5xx is received.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpServerErrorException : HttpStatusCodeException
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpServerErrorException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/>.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
public HttpServerErrorException(HttpStatusCode statusCode)
|
||||
: base (statusCode)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpServerErrorException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/> and a status description.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpServerErrorException(HttpStatusCode statusCode, string statusDescription)
|
||||
: base (statusCode, statusDescription)
|
||||
{
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="HttpServerErrorException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpServerErrorException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
129
src/Spring/Spring.Http/Http/Rest/HttpStatusCodeException.cs
Normal file
129
src/Spring/Spring.Http/Http/Rest/HttpStatusCodeException.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
#region License
|
||||
|
||||
/*
|
||||
* Copyright 2002-2011 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* 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.Runtime.Serialization;
|
||||
using System.Security.Permissions;
|
||||
|
||||
namespace Spring.Http.Rest
|
||||
{
|
||||
/// <summary>
|
||||
/// Base class for exceptions based on a <see cref="HttpStatusCode"/>.
|
||||
/// </summary>
|
||||
/// <author>Arjen Poutsma</author>
|
||||
/// <author>Bruno Baia (.NET)</author>
|
||||
#if !SILVERLIGHT
|
||||
[Serializable]
|
||||
#endif
|
||||
public class HttpStatusCodeException : RestClientException
|
||||
{
|
||||
private HttpStatusCode statusCode;
|
||||
private string statusDescription;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status code.
|
||||
/// </summary>
|
||||
public HttpStatusCode StatusCode
|
||||
{
|
||||
get { return this.statusCode; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP status description.
|
||||
/// </summary>
|
||||
public string StatusDescription
|
||||
{
|
||||
get { return this.statusDescription; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpStatusCodeException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/>.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
public HttpStatusCodeException(HttpStatusCode statusCode)
|
||||
: base(String.Format("The server returned '{0}' with the status code {0:d}.", statusCode))
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.statusDescription = statusCode.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="HttpStatusCodeException"/>
|
||||
/// based on a <see cref="HttpStatusCode"/> and a status description.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The HTTP status code.</param>
|
||||
/// <param name="statusDescription">The HTTP status description.</param>
|
||||
public HttpStatusCodeException(HttpStatusCode statusCode, string statusDescription)
|
||||
: base(String.Format("The server returned '{0}' with the status code {1:d} - {1}.", statusDescription, statusCode))
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.statusDescription = statusDescription;
|
||||
}
|
||||
|
||||
#if !SILVERLIGHT
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="RestClientException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
|
||||
/// that holds the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/>
|
||||
/// that contains contextual information about the source or destination.
|
||||
/// </param>
|
||||
protected HttpStatusCodeException(SerializationInfo info, StreamingContext context)
|
||||
: base(info, context)
|
||||
{
|
||||
if (info != null)
|
||||
{
|
||||
this.statusCode = (HttpStatusCode)info.GetInt32("StatusCode");
|
||||
this.statusDescription = info.GetString("StatusDescription");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Populates the <see cref="System.Runtime.Serialization.SerializationInfo"/> with
|
||||
/// information about the exception.
|
||||
/// </summary>
|
||||
/// <param name="info">
|
||||
/// The <see cref="System.Runtime.Serialization.SerializationInfo"/> that holds
|
||||
/// the serialized object data about the exception being thrown.
|
||||
/// </param>
|
||||
/// <param name="context">
|
||||
/// The <see cref="System.Runtime.Serialization.StreamingContext"/> that contains contextual
|
||||
/// information about the source or destination.
|
||||
/// </param>
|
||||
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
|
||||
public override void GetObjectData(
|
||||
SerializationInfo info, StreamingContext context)
|
||||
{
|
||||
base.GetObjectData(info, context);
|
||||
if (info != null)
|
||||
{
|
||||
info.AddValue("StatusCode", (int)this.statusCode);
|
||||
info.AddValue("StatusDescription", this.statusDescription);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user