Commit b5a7ed24 authored by csharptest's avatar csharptest Committed by rogerk

Conditional extensions in serialization, Removed usages of extensions methods from unit tests

parent 4ad55269
......@@ -17,7 +17,11 @@ namespace Google.ProtocolBuffers
/// Serializes the message to JSON text. This is a trivial wrapper
/// around Serialization.JsonFormatWriter.WriteMessage.
/// </summary>
public static string ToJson(this IMessageLite message)
public static string ToJson(
#if !NET20
this
#endif
IMessageLite message)
{
JsonFormatWriter w = JsonFormatWriter.CreateInstance();
w.WriteMessage(message);
......@@ -27,7 +31,11 @@ namespace Google.ProtocolBuffers
/// Serializes the message to XML text. This is a trivial wrapper
/// around Serialization.XmlFormatWriter.WriteMessage.
/// </summary>
public static string ToXml(this IMessageLite message)
public static string ToXml(
#if !NET20
this
#endif
IMessageLite message)
{
StringWriter w = new StringWriter(new StringBuilder(4096));
XmlFormatWriter.CreateInstance(w).WriteMessage(message);
......@@ -37,7 +45,11 @@ namespace Google.ProtocolBuffers
/// Serializes the message to XML text using the element name provided.
/// This is a trivial wrapper around Serialization.XmlFormatWriter.WriteMessage.
/// </summary>
public static string ToXml(this IMessageLite message, string rootElementName)
public static string ToXml(
#if !NET20
this
#endif
IMessageLite message, string rootElementName)
{
StringWriter w = new StringWriter(new StringBuilder(4096));
XmlFormatWriter.CreateInstance(w).WriteMessage(rootElementName, message);
......@@ -51,7 +63,11 @@ namespace Google.ProtocolBuffers
/// <param name="options">Options specific to writing this message and/or content type</param>
/// <param name="contentType">The mime type of the content to be written</param>
/// <param name="output">The stream to write the message to</param>
public static void WriteTo(this IMessageLite message, MessageFormatOptions options, string contentType, Stream output)
public static void WriteTo(
#if !NET20
this
#endif
IMessageLite message, MessageFormatOptions options, string contentType, Stream output)
{
ICodedOutputStream codedOutput = MessageFormatFactory.CreateOutputStream(options, contentType, output);
......@@ -71,7 +87,11 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Merges a JSON object into this builder and returns
/// </summary>
public static TBuilder MergeFromJson<TBuilder>(this TBuilder builder, string jsonText) where TBuilder : IBuilderLite
public static TBuilder MergeFromJson<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, string jsonText) where TBuilder : IBuilderLite
{
return JsonFormatReader.CreateInstance(jsonText)
.Merge(builder);
......@@ -79,14 +99,22 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Merges a JSON object into this builder and returns
/// </summary>
public static TBuilder MergeFromJson<TBuilder>(this TBuilder builder, TextReader reader) where TBuilder : IBuilderLite
public static TBuilder MergeFromJson<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, TextReader reader) where TBuilder : IBuilderLite
{
return MergeFromJson(builder, reader, ExtensionRegistry.Empty);
}
/// <summary>
/// Merges a JSON object into this builder using the extensions provided and returns
/// </summary>
public static TBuilder MergeFromJson<TBuilder>(this TBuilder builder, TextReader reader, ExtensionRegistry extensionRegistry) where TBuilder : IBuilderLite
public static TBuilder MergeFromJson<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, TextReader reader, ExtensionRegistry extensionRegistry) where TBuilder : IBuilderLite
{
return JsonFormatReader.CreateInstance(reader)
.Merge(builder, extensionRegistry);
......@@ -95,7 +123,11 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Merges an XML object into this builder and returns
/// </summary>
public static TBuilder MergeFromXml<TBuilder>(this TBuilder builder, XmlReader reader) where TBuilder : IBuilderLite
public static TBuilder MergeFromXml<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, XmlReader reader) where TBuilder : IBuilderLite
{
return MergeFromXml(builder, XmlFormatReader.DefaultRootElementName, reader, ExtensionRegistry.Empty);
}
......@@ -103,7 +135,11 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Merges an XML object into this builder and returns
/// </summary>
public static TBuilder MergeFromXml<TBuilder>(this TBuilder builder, string rootElementName, XmlReader reader) where TBuilder : IBuilderLite
public static TBuilder MergeFromXml<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, string rootElementName, XmlReader reader) where TBuilder : IBuilderLite
{
return MergeFromXml(builder, rootElementName, reader, ExtensionRegistry.Empty);
}
......@@ -111,8 +147,12 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Merges an XML object into this builder using the extensions provided and returns
/// </summary>
public static TBuilder MergeFromXml<TBuilder>(this TBuilder builder, string rootElementName, XmlReader reader,
ExtensionRegistry extensionRegistry) where TBuilder : IBuilderLite
public static TBuilder MergeFromXml<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, string rootElementName, XmlReader reader,
ExtensionRegistry extensionRegistry) where TBuilder : IBuilderLite
{
return XmlFormatReader.CreateInstance(reader)
.Merge(rootElementName, builder, extensionRegistry);
......@@ -127,7 +167,11 @@ namespace Google.ProtocolBuffers
/// <param name="contentType">The mime type of the input stream content</param>
/// <param name="input">The stream to read the message from</param>
/// <returns>The same builder instance that was supplied in the builder parameter</returns>
public static TBuilder MergeFrom<TBuilder>(this TBuilder builder, MessageFormatOptions options, string contentType, Stream input) where TBuilder : IBuilderLite
public static TBuilder MergeFrom<TBuilder>(
#if !NET20
this
#endif
TBuilder builder, MessageFormatOptions options, string contentType, Stream input) where TBuilder : IBuilderLite
{
ICodedInputStream codedInput = MessageFormatFactory.CreateInputStream(options, contentType, input);
codedInput.ReadMessageStart();
......@@ -150,14 +194,18 @@ namespace Google.ProtocolBuffers
/// <param name="input">The input stream</param>
/// <param name="responseType">The mime type for the output stream</param>
/// <param name="output">The output stream</param>
public static void HttpCallMethod(this IRpcServerStub stub, string methodName, MessageFormatOptions options,
public static void HttpCallMethod(
#if !NET20
this
#endif
IRpcServerStub stub, string methodName, MessageFormatOptions options,
string contentType, Stream input, string responseType, Stream output)
{
ICodedInputStream codedInput = MessageFormatFactory.CreateInputStream(options, contentType, input);
codedInput.ReadMessageStart();
IMessageLite response = stub.CallMethod(methodName, codedInput, options.ExtensionRegistry);
codedInput.ReadMessageEnd();
response.WriteTo(options, responseType, output);
WriteTo(response, options, responseType, output);
}
#endregion
......
......@@ -34,6 +34,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<DefineConstants>TRACE;NET20;</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
......@@ -42,7 +43,7 @@
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DefineConstants>$(DefineConstants)DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -54,7 +55,7 @@
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>$(DefineConstants)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -67,7 +68,7 @@
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<DefineConstants>$(DefineConstants)DEBUG;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -79,7 +80,7 @@
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<DefineConstants>$(DefineConstants)SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -89,12 +90,7 @@
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Xml" />
<!-- Only for 2.x compatibility of extension methods -->
<Reference Include="System.Core">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\System.Core\System.Core.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Core" Condition="'$(TargetFrameworkVersion)' != 'v2.0'" />
</ItemGroup>
<ItemGroup>
<Compile Include="Extensions.cs" />
......
......@@ -34,6 +34,7 @@
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<DefineConstants>TRACE;NET20;</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
......@@ -42,7 +43,7 @@
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DefineConstants>$(DefineConstants)DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -54,7 +55,7 @@
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>$(DefineConstants)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -67,7 +68,7 @@
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<DefineConstants>$(DefineConstants)DEBUG;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -79,7 +80,7 @@
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591, 1570, 1571, 1572, 1573, 1574</NoWarn>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<DefineConstants>$(DefineConstants)SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
......@@ -89,12 +90,7 @@
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Xml" />
<!-- Only for 2.x compatibility of extension methods -->
<Reference Include="System.Core">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\System.Core\System.Core.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Core" Condition="'$(TargetFrameworkVersion)' != 'v2.0'" />
</ItemGroup>
<ItemGroup>
<Compile Include="Extensions.cs" />
......
......@@ -90,8 +90,8 @@ namespace Google.ProtocolBuffers
TestAllTypes m2 = b1.Build();
Assert.AreEqual("{\"optional_foreign_message\":{},\"repeated_int32\":[2],\"default_int32\":1}", m1.ToJson());
Assert.AreEqual("{\"optional_foreign_message\":{\"c\":7},\"repeated_int32\":[2,6],\"default_int32\":5}", m2.ToJson());
Assert.AreEqual("{\"optional_foreign_message\":{},\"repeated_int32\":[2],\"default_int32\":1}", Extensions.ToJson(m1));
Assert.AreEqual("{\"optional_foreign_message\":{\"c\":7},\"repeated_int32\":[2,6],\"default_int32\":5}", Extensions.ToJson(m2));
}
[Test]
......
......@@ -98,9 +98,9 @@ namespace Google.ProtocolBuffers
[Test]
public void TestMergeFromJsonType()
{
TestXmlMessage msg = new TestXmlMessage.Builder().MergeFrom(
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/json", new MemoryStream(Encoding.ASCII.GetBytes(
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToJson()
Extensions.ToJson(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
)))
.Build();
Assert.AreEqual("a", msg.Text);
......@@ -109,9 +109,9 @@ namespace Google.ProtocolBuffers
[Test]
public void TestMergeFromXmlType()
{
TestXmlMessage msg = new TestXmlMessage.Builder().MergeFrom(
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/xml", new MemoryStream(Encoding.ASCII.GetBytes(
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToXml()
Extensions.ToXml(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
)))
.Build();
Assert.AreEqual("a", msg.Text);
......@@ -120,7 +120,7 @@ namespace Google.ProtocolBuffers
[Test]
public void TestMergeFromProtoType()
{
TestXmlMessage msg = new TestXmlMessage.Builder().MergeFrom(
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/vnd.google.protobuf", new MemoryStream(
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToByteArray()
))
......@@ -132,8 +132,8 @@ namespace Google.ProtocolBuffers
public void TestWriteToJsonType()
{
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(new MessageFormatOptions(), "application/json", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/json", ms);
Assert.AreEqual(@"{""text"":""a"",""number"":1}", Encoding.UTF8.GetString(ms.ToArray()));
}
......@@ -141,8 +141,8 @@ namespace Google.ProtocolBuffers
public void TestWriteToXmlType()
{
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(new MessageFormatOptions(), "application/xml", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/xml", ms);
Assert.AreEqual("<root><text>a</text><number>1</number></root>", Encoding.UTF8.GetString(ms.ToArray()));
}
......@@ -150,8 +150,8 @@ namespace Google.ProtocolBuffers
public void TestWriteToProtoType()
{
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(new MessageFormatOptions(), "application/vnd.google.protobuf", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/vnd.google.protobuf", ms);
byte[] bytes = TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToByteArray();
Assert.AreEqual(bytes, ms.ToArray());
......@@ -171,7 +171,7 @@ namespace Google.ProtocolBuffers
XmlReaderRootElementName = "my-root-node"
};
TestXmlMessage msg = new TestXmlMessage.Builder().MergeFrom(
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
options, "application/xml", ms)
.Build();
......@@ -191,7 +191,7 @@ namespace Google.ProtocolBuffers
};
MemoryStream ms = new MemoryStream();
message.WriteTo(options, "application/xml", ms);
Extensions.WriteTo(message, options, "application/xml", ms);
ms.Position = 0;
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
......@@ -207,8 +207,8 @@ namespace Google.ProtocolBuffers
public void TestJsonFormatted()
{
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(new MessageFormatOptions() { FormattedOutput = true }, "application/json", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions() { FormattedOutput = true }, "application/json", ms);
Assert.AreEqual("{\r\n \"text\": \"a\",\r\n \"number\": 1\r\n}", Encoding.UTF8.GetString(ms.ToArray()));
}
......@@ -216,8 +216,8 @@ namespace Google.ProtocolBuffers
public void TestXmlFormatted()
{
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(new MessageFormatOptions() { FormattedOutput = true }, "application/xml", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions() { FormattedOutput = true }, "application/xml", ms);
Assert.AreEqual("<root>\r\n <text>a</text>\r\n <number>1</number>\r\n</root>", Encoding.UTF8.GetString(ms.ToArray()));
}
......@@ -233,10 +233,10 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(1, options.MimeInputTypes.Count);
Stream xmlStream = new MemoryStream(Encoding.ASCII.GetBytes(
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToXml()
));
Extensions.ToXml(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
));
TestXmlMessage msg = new TestXmlMessage.Builder().MergeFrom(
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
options, "-custom-XML-mime-type-", xmlStream)
.Build();
Assert.AreEqual("a", msg.Text);
......@@ -255,8 +255,8 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(1, options.MimeOutputTypes.Count);
MemoryStream ms = new MemoryStream();
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build()
.WriteTo(options, "-custom-XML-mime-type-", ms);
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
options, "-custom-XML-mime-type-", ms);
Assert.AreEqual("<root><text>a</text><number>1</number></root>", Encoding.UTF8.GetString(ms.ToArray()));
}
......
......@@ -123,8 +123,8 @@ namespace Google.ProtocolBuffers
void IHttpTransfer.Execute(string method, string contentType, Stream input, string acceptType, Stream output)
{
//Extension for: Google.ProtocolBuffers.Serialization.Http.ServiceExtensions.HttpCallMethod(_stub,
_stub.HttpCallMethod(
//3.5: _stub.HttpCallMethod(
Extensions.HttpCallMethod(_stub,
method, Options,
contentType, input,
acceptType, output
......@@ -165,14 +165,14 @@ namespace Google.ProtocolBuffers
MemoryStream output = new MemoryStream();
//Write to _mimeType format
request.WriteTo(Options, _mimeType, input);
Extensions.WriteTo(request, Options, _mimeType, input);
input.Position = 0;
_wire.Execute(method, _mimeType, input, _mimeType, output);
//Read from _mimeType format
output.Position = 0;
response.MergeFrom(Options, _mimeType, output);
Extensions.MergeFrom(response, Options, _mimeType, output);
return response.Build();
}
......
......@@ -15,7 +15,8 @@ namespace Google.ProtocolBuffers
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFromJson(@"{""valid"":true}");
//3.5: builder.MergeFromJson(@"{""valid"":true}");
Extensions.MergeFromJson(builder, @"{""valid"":true}");
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
......@@ -29,7 +30,8 @@ namespace Google.ProtocolBuffers
.SetValid(true)
.Build();
string json = message.ToJson();
//3.5: string json = message.ToJson();
string json = Extensions.ToJson(message);
Assert.AreEqual(@"{""valid"":true}", json);
}
......@@ -100,9 +102,9 @@ namespace Google.ProtocolBuffers
public void TestToJsonParseFromJson()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string json = msg.ToJson();
string json = Extensions.ToJson(msg);
Assert.AreEqual("{\"default_bool\":true}", json);
TestAllTypes copy = new TestAllTypes.Builder().MergeFromJson(json).Build();
TestAllTypes copy = Extensions.MergeFromJson(new TestAllTypes.Builder(), json).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
......@@ -111,9 +113,9 @@ namespace Google.ProtocolBuffers
public void TestToJsonParseFromJsonReader()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string json = msg.ToJson();
string json = Extensions.ToJson(msg);
Assert.AreEqual("{\"default_bool\":true}", json);
TestAllTypes copy = new TestAllTypes.Builder().MergeFromJson(new StringReader(json)).Build();
TestAllTypes copy = Extensions.MergeFromJson(new TestAllTypes.Builder(), new StringReader(json)).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
......@@ -429,7 +431,7 @@ namespace Google.ProtocolBuffers
StringBuilder sb = new StringBuilder(8192);
for (int i = 0; i < 80; i++)
sb.Append("{\"child\":");
TestXmlRescursive msg = new TestXmlRescursive.Builder().MergeFromJson(sb.ToString()).Build();
TestXmlRescursive msg = Extensions.MergeFromJson(new TestXmlRescursive.Builder(), sb.ToString()).Build();
}
[Test, ExpectedException(typeof(FormatException))]
public void FailWithEmptyText()
......
......@@ -18,7 +18,8 @@ namespace Google.ProtocolBuffers
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
XmlReader rdr = XmlReader.Create(new StringReader(@"<root><valid>true</valid></root>"));
builder.MergeFromXml(rdr);
//3.5: builder.MergeFromXml(rdr);
Extensions.MergeFromXml(builder, rdr);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
......@@ -32,7 +33,8 @@ namespace Google.ProtocolBuffers
.SetValid(true)
.Build();
string Xml = message.ToXml();
//3.5: string Xml = message.ToXml();
string Xml = Extensions.ToXml(message);
Assert.AreEqual(@"<root><valid>true</valid></root>", Xml);
}
......@@ -75,9 +77,9 @@ namespace Google.ProtocolBuffers
public void TestToXmlParseFromXml()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string xml = msg.ToXml();
string xml = Extensions.ToXml(msg);
Assert.AreEqual("<root><default_bool>true</default_bool></root>", xml);
TestAllTypes copy = new TestAllTypes.Builder().MergeFromXml(XmlReader.Create(new StringReader(xml))).Build();
TestAllTypes copy = Extensions.MergeFromXml(new TestAllTypes.Builder(), XmlReader.Create(new StringReader(xml))).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
......@@ -86,9 +88,9 @@ namespace Google.ProtocolBuffers
public void TestToXmlParseFromXmlWithRootName()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string xml = msg.ToXml("message");
string xml = Extensions.ToXml(msg, "message");
Assert.AreEqual("<message><default_bool>true</default_bool></message>", xml);
TestAllTypes copy = new TestAllTypes.Builder().MergeFromXml("message", XmlReader.Create(new StringReader(xml))).Build();
TestAllTypes copy = Extensions.MergeFromXml(new TestAllTypes.Builder(), "message", XmlReader.Create(new StringReader(xml))).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
......@@ -447,7 +449,7 @@ namespace Google.ProtocolBuffers
StringBuilder sb = new StringBuilder(8192);
for (int i = 0; i < 80; i++)
sb.Append("<child>");
TestXmlRescursive msg = new TestXmlRescursive.Builder().MergeFromXml("child", XmlReader.Create(new StringReader(sb.ToString()))).Build();
TestXmlRescursive msg = Extensions.MergeFromXml(new TestXmlRescursive.Builder(), "child", XmlReader.Create(new StringReader(sb.ToString()))).Build();
}
}
}
......@@ -56,6 +56,12 @@
<Compile Include="..\ProtocolBuffers.Test\Properties\AssemblyInfo.cs">
<Link>Properties\AssemblyInfo.cs</Link>
</Compile>
<Compile Include="..\ProtocolBuffers.Test\TestRpcForMimeTypes.cs">
<Link>TestRpcForMimeTypes.cs</Link>
</Compile>
<Compile Include="..\ProtocolBuffers.Test\TestRpcGenerator.cs">
<Link>TestRpcGenerator.cs</Link>
</Compile>
<Compile Include="AbstractBuilderLiteTest.cs" />
<Compile Include="AbstractMessageLiteTest.cs" />
<Compile Include="ExtendableBuilderLiteTest.cs" />
......@@ -67,8 +73,6 @@
<Compile Include="TestProtos\UnitTestImportLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestRpcInteropLite.cs" />
<Compile Include="TestRpcForMimeTypes.cs" />
<Compile Include="TestRpcGenerator.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers.Serialization\ProtocolBuffersLite.Serialization.csproj">
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers;
using Google.ProtocolBuffers.Serialization.Http;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
using System.IO;
using Google.ProtocolBuffers.Serialization;
using System.Text;
namespace Google.ProtocolBuffers
{
/// <summary>
/// This class verifies the correct code is generated from unittest_rpc_interop.proto and provides a small demonstration
/// of using the new IRpcDispatch to write a client/server
/// </summary>
[TestFixture]
public class TestRpcForMimeTypes
{
/// <summary>
/// A sample implementation of the ISearchService for testing
/// </summary>
private class ExampleSearchImpl : ISearchService
{
SearchResponse ISearchService.Search(SearchRequest searchRequest)
{
if (searchRequest.CriteriaCount == 0)
{
throw new ArgumentException("No criteria specified.", new InvalidOperationException());
}
SearchResponse.Builder resp = SearchResponse.CreateBuilder();
foreach (string criteria in searchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://search.com").
Build());
}
return resp.Build();
}
SearchResponse ISearchService.RefineSearch(RefineSearchRequest refineSearchRequest)
{
SearchResponse.Builder resp = refineSearchRequest.PreviousResults.ToBuilder();
foreach (string criteria in refineSearchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://refine.com").
Build());
}
return resp.Build();
}
}
/// <summary>
/// An example extraction of the wire protocol
/// </summary>
private interface IHttpTransfer
{
void Execute(string method, string contentType, Stream input, string acceptType, Stream output);
}
/// <summary>
/// An example of a server responding to a web/http request
/// </summary>
private class ExampleHttpServer : IHttpTransfer
{
public readonly MessageFormatOptions Options =
new MessageFormatOptions
{
ExtensionRegistry = ExtensionRegistry.Empty,
FormattedOutput = true,
XmlReaderOptions = XmlReaderOptions.ReadNestedArrays,
XmlReaderRootElementName = "request",
XmlWriterOptions = XmlWriterOptions.OutputNestedArrays,
XmlWriterRootElementName = "response"
};
private readonly IRpcServerStub _stub;
public ExampleHttpServer(ISearchService implementation)
{
//on the server, we create a dispatch to call the appropriate method by name
IRpcDispatch dispatch = new SearchService.Dispatch(implementation);
//we then wrap that dispatch in a server stub which will deserialize the wire bytes to the message
//type appropriate for the method name being invoked.
_stub = new SearchService.ServerStub(dispatch);
}
void IHttpTransfer.Execute(string method, string contentType, Stream input, string acceptType, Stream output)
{
//Extension for: Google.ProtocolBuffers.Serialization.Http.ServiceExtensions.HttpCallMethod(_stub,
_stub.HttpCallMethod(
method, Options,
contentType, input,
acceptType, output
);
}
}
/// <summary>
/// An example of a client sending a wire request
/// </summary>
private class ExampleClient : IRpcDispatch
{
public readonly MessageFormatOptions Options =
new MessageFormatOptions
{
ExtensionRegistry = ExtensionRegistry.Empty,
FormattedOutput = true,
XmlReaderOptions = XmlReaderOptions.ReadNestedArrays,
XmlReaderRootElementName = "response",
XmlWriterOptions = XmlWriterOptions.OutputNestedArrays,
XmlWriterRootElementName = "request"
};
private readonly IHttpTransfer _wire;
private readonly string _mimeType;
public ExampleClient(IHttpTransfer wire, string mimeType)
{
_wire = wire;
_mimeType = mimeType;
}
TMessage IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, IMessageLite request,
IBuilderLite<TMessage, TBuilder> response)
{
MemoryStream input = new MemoryStream();
MemoryStream output = new MemoryStream();
//Write to _mimeType format
request.WriteTo(Options, _mimeType, input);
input.Position = 0;
_wire.Execute(method, _mimeType, input, _mimeType, output);
//Read from _mimeType format
output.Position = 0;
response.MergeFrom(Options, _mimeType, output);
return response.Build();
}
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestClientServerWithJsonFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "text/json"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestClientServerWithXmlFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "text/xml"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestClientServerWithProtoFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "application/x-protobuf"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestClientServerWithCustomFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//Setup our custom mime-type format as the only format supported:
server.Options.MimeInputTypes.Clear();
server.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance);
server.Options.MimeOutputTypes.Clear();
server.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance);
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ExampleClient exclient = new ExampleClient(wire, "foo/bar");
//Add our custom mime-type format
exclient.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance);
exclient.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance);
ISearchService client = new SearchService(exclient);
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestServerWithUriFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes("?Criteria=Test&Criteria=Test+of%20URI"));
MemoryStream output = new MemoryStream();
//Call the server
wire.Execute("Search",
MessageFormatOptions.ContentFormUrlEncoded, input,
MessageFormatOptions.ContentTypeProtoBuffer, output
);
SearchResponse result = SearchResponse.ParseFrom(output.ToArray());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Test of URI", result.ResultsList[1].Name);
Assert.AreEqual("http://search.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestInvalidMimeType()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream();
MemoryStream output = new MemoryStream();
//Call the server
wire.Execute("Search",
"bad/mime", input,
MessageFormatOptions.ContentTypeProtoBuffer, output
);
Assert.Fail();
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[Test]
public void TestDefaultMimeType()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream(new SearchRequest.Builder().AddCriteria("Test").Build().ToByteArray());
MemoryStream output = new MemoryStream();
//With this default set, any invalid/unknown mime-type will be mapped to use that format
server.Options.DefaultContentType = MessageFormatOptions.ContentTypeProtoBuffer;
wire.Execute("Search",
"foo", input,
"bar", output
);
SearchResponse result = SearchResponse.ParseFrom(output.ToArray());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
}
}
}
\ No newline at end of file
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
/// <summary>
/// This class verifies the correct code is generated from unittest_rpc_interop.proto and provides a small demonstration
/// of using the new IRpcDispatch to write a client/server
/// </summary>
[TestFixture]
public class TestRpcGenerator
{
/// <summary>
/// A sample implementation of the ISearchService for testing
/// </summary>
private class ExampleSearchImpl : ISearchService
{
SearchResponse ISearchService.Search(SearchRequest searchRequest)
{
if (searchRequest.CriteriaCount == 0)
{
throw new ArgumentException("No criteria specified.", new InvalidOperationException());
}
SearchResponse.Builder resp = SearchResponse.CreateBuilder();
foreach (string criteria in searchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://search.com").
Build());
}
return resp.Build();
}
SearchResponse ISearchService.RefineSearch(RefineSearchRequest refineSearchRequest)
{
SearchResponse.Builder resp = refineSearchRequest.PreviousResults.ToBuilder();
foreach (string criteria in refineSearchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://refine.com").
Build());
}
return resp.Build();
}
}
/// <summary>
/// An example extraction of the wire protocol
/// </summary>
private interface IWireTransfer
{
byte[] Execute(string method, byte[] message);
}
/// <summary>
/// An example of a server responding to a wire request
/// </summary>
private class ExampleServerHost : IWireTransfer
{
private readonly IRpcServerStub _stub;
public ExampleServerHost(ISearchService implementation)
{
//on the server, we create a dispatch to call the appropriate method by name
IRpcDispatch dispatch = new SearchService.Dispatch(implementation);
//we then wrap that dispatch in a server stub which will deserialize the wire bytes to the message
//type appropriate for the method name being invoked.
_stub = new SearchService.ServerStub(dispatch);
}
byte[] IWireTransfer.Execute(string method, byte[] message)
{
//now when we recieve a wire transmission to invoke a method by name with a byte[] or stream payload
//we just simply call the sub:
IMessageLite response = _stub.CallMethod(method, CodedInputStream.CreateInstance(message),
ExtensionRegistry.Empty);
//now we return the expected response message:
return response.ToByteArray();
}
}
/// <summary>
/// An example of a client sending a wire request
/// </summary>
private class ExampleClient : IRpcDispatch
{
private readonly IWireTransfer _wire;
public ExampleClient(IWireTransfer wire)
{
_wire = wire;
}
TMessage IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, IMessageLite request,
IBuilderLite<TMessage, TBuilder> response)
{
byte[] rawResponse = _wire.Execute(method, request.ToByteArray());
response.MergeFrom(rawResponse);
return response.Build();
}
}
/// <summary>
/// Put it all together to create one seamless client/server experience full of rich-type goodness ;)
/// All you need to do is send/recieve the method name and message bytes across the wire.
/// </summary>
[Test]
public void TestClientServerDispatch()
{
ExampleServerHost server = new ExampleServerHost(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IWireTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment