diff options
author | Jan Tattermusch <jtattermusch@google.com> | 2018-07-25 18:36:51 +0200 |
---|---|---|
committer | Jan Tattermusch <jtattermusch@google.com> | 2018-07-26 12:59:07 +0200 |
commit | b56747397b7a7f267a1f96a8f0aed590386d213f (patch) | |
tree | e8c77f12432618f253a57cafc1b2a0208cfb6435 /examples/csharp/RouteGuide | |
parent | b8acb536e3f14dcdab0bdc25380ee9ae37b46e7f (diff) |
rename route_guide -> RouteGuide
Diffstat (limited to 'examples/csharp/RouteGuide')
-rw-r--r-- | examples/csharp/RouteGuide/.gitignore | 5 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/README.md | 6 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide.sln | 34 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide/RouteGuide.cs | 919 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide/RouteGuide.csproj | 25 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide/RouteGuideGrpc.cs | 332 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide/RouteGuideUtil.cs | 123 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuide/route_guide_db.json | 601 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuideClient/Program.cs | 241 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuideClient/RouteGuideClient.csproj | 16 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuideServer/Program.cs | 46 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuideServer/RouteGuideImpl.cs | 153 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/RouteGuideServer/RouteGuideServer.csproj | 16 | ||||
-rw-r--r-- | examples/csharp/RouteGuide/generate_protos.bat | 26 |
14 files changed, 2543 insertions, 0 deletions
diff --git a/examples/csharp/RouteGuide/.gitignore b/examples/csharp/RouteGuide/.gitignore new file mode 100644 index 0000000000..585000ea2d --- /dev/null +++ b/examples/csharp/RouteGuide/.gitignore @@ -0,0 +1,5 @@ +bin/ +obj/ +packages/ +*.suo +*.userprefs diff --git a/examples/csharp/RouteGuide/README.md b/examples/csharp/RouteGuide/README.md new file mode 100644 index 0000000000..3cfb14ae9a --- /dev/null +++ b/examples/csharp/RouteGuide/README.md @@ -0,0 +1,6 @@ +# gRPC Basics: C# sample code + +The files in this folder are the samples used in [gRPC Basics: C#][], +a detailed tutorial for using gRPC in C#. + +[gRPC Basics: C#]:https://grpc.io/docs/tutorials/basic/csharp.html diff --git a/examples/csharp/RouteGuide/RouteGuide.sln b/examples/csharp/RouteGuide/RouteGuide.sln new file mode 100644 index 0000000000..73e6e306b1 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26228.4 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuide", "RouteGuide\RouteGuide.csproj", "{49954D9C-5F17-4662-96B2-73BE833DD81A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideClient", "RouteGuideClient\RouteGuideClient.csproj", "{D47BE663-4DE3-4206-B7A8-EA3FA066DADC}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RouteGuideServer", "RouteGuideServer\RouteGuideServer.csproj", "{4B7C7794-BE24-4477-ACE7-18259EB73D27}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {49954D9C-5F17-4662-96B2-73BE833DD81A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {49954D9C-5F17-4662-96B2-73BE833DD81A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {49954D9C-5F17-4662-96B2-73BE833DD81A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {49954D9C-5F17-4662-96B2-73BE833DD81A}.Release|Any CPU.Build.0 = Release|Any CPU + {D47BE663-4DE3-4206-B7A8-EA3FA066DADC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D47BE663-4DE3-4206-B7A8-EA3FA066DADC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D47BE663-4DE3-4206-B7A8-EA3FA066DADC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D47BE663-4DE3-4206-B7A8-EA3FA066DADC}.Release|Any CPU.Build.0 = Release|Any CPU + {4B7C7794-BE24-4477-ACE7-18259EB73D27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4B7C7794-BE24-4477-ACE7-18259EB73D27}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4B7C7794-BE24-4477-ACE7-18259EB73D27}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4B7C7794-BE24-4477-ACE7-18259EB73D27}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/examples/csharp/RouteGuide/RouteGuide/RouteGuide.cs b/examples/csharp/RouteGuide/RouteGuide/RouteGuide.cs new file mode 100644 index 0000000000..603809ee76 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide/RouteGuide.cs @@ -0,0 +1,919 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: route_guide.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Routeguide { + + /// <summary>Holder for reflection information generated from route_guide.proto</summary> + public static partial class RouteGuideReflection { + + #region Descriptor + /// <summary>File descriptor for route_guide.proto</summary> + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static RouteGuideReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChFyb3V0ZV9ndWlkZS5wcm90bxIKcm91dGVndWlkZSIsCgVQb2ludBIQCghs", + "YXRpdHVkZRgBIAEoBRIRCglsb25naXR1ZGUYAiABKAUiSQoJUmVjdGFuZ2xl", + "Eh0KAmxvGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIdCgJoaRgCIAEoCzIR", + "LnJvdXRlZ3VpZGUuUG9pbnQiPAoHRmVhdHVyZRIMCgRuYW1lGAEgASgJEiMK", + "CGxvY2F0aW9uGAIgASgLMhEucm91dGVndWlkZS5Qb2ludCJBCglSb3V0ZU5v", + "dGUSIwoIbG9jYXRpb24YASABKAsyES5yb3V0ZWd1aWRlLlBvaW50Eg8KB21l", + "c3NhZ2UYAiABKAkiYgoMUm91dGVTdW1tYXJ5EhMKC3BvaW50X2NvdW50GAEg", + "ASgFEhUKDWZlYXR1cmVfY291bnQYAiABKAUSEAoIZGlzdGFuY2UYAyABKAUS", + "FAoMZWxhcHNlZF90aW1lGAQgASgFMoUCCgpSb3V0ZUd1aWRlEjYKCkdldEZl", + "YXR1cmUSES5yb3V0ZWd1aWRlLlBvaW50GhMucm91dGVndWlkZS5GZWF0dXJl", + "IgASPgoMTGlzdEZlYXR1cmVzEhUucm91dGVndWlkZS5SZWN0YW5nbGUaEy5y", + "b3V0ZWd1aWRlLkZlYXR1cmUiADABEj4KC1JlY29yZFJvdXRlEhEucm91dGVn", + "dWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5IgAoARI/CglS", + "b3V0ZUNoYXQSFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZRoVLnJvdXRlZ3VpZGUu", + "Um91dGVOb3RlIgAoATABQjYKG2lvLmdycGMuZXhhbXBsZXMucm91dGVndWlk", + "ZUIPUm91dGVHdWlkZVByb3RvUAGiAgNSVEdiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Routeguide.Point), global::Routeguide.Point.Parser, new[]{ "Latitude", "Longitude" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Routeguide.Rectangle), global::Routeguide.Rectangle.Parser, new[]{ "Lo", "Hi" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Routeguide.Feature), global::Routeguide.Feature.Parser, new[]{ "Name", "Location" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Routeguide.RouteNote), global::Routeguide.RouteNote.Parser, new[]{ "Location", "Message" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Routeguide.RouteSummary), global::Routeguide.RouteSummary.Parser, new[]{ "PointCount", "FeatureCount", "Distance", "ElapsedTime" }, null, null, null) + })); + } + #endregion + + } + #region Messages + /// <summary> + /// Points are represented as latitude-longitude pairs in the E7 representation + /// (degrees multiplied by 10**7 and rounded to the nearest integer). + /// Latitudes should be in the range +/- 90 degrees and longitude should be in + /// the range +/- 180 degrees (inclusive). + /// </summary> + public sealed partial class Point : pb::IMessage<Point> { + private static readonly pb::MessageParser<Point> _parser = new pb::MessageParser<Point>(() => new Point()); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser<Point> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Routeguide.RouteGuideReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Point() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Point(Point other) : this() { + latitude_ = other.latitude_; + longitude_ = other.longitude_; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Point Clone() { + return new Point(this); + } + + /// <summary>Field number for the "latitude" field.</summary> + public const int LatitudeFieldNumber = 1; + private int latitude_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int Latitude { + get { return latitude_; } + set { + latitude_ = value; + } + } + + /// <summary>Field number for the "longitude" field.</summary> + public const int LongitudeFieldNumber = 2; + private int longitude_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int Longitude { + get { return longitude_; } + set { + longitude_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Point); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Point other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Latitude != other.Latitude) return false; + if (Longitude != other.Longitude) return false; + return true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Latitude != 0) hash ^= Latitude.GetHashCode(); + if (Longitude != 0) hash ^= Longitude.GetHashCode(); + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Latitude != 0) { + output.WriteRawTag(8); + output.WriteInt32(Latitude); + } + if (Longitude != 0) { + output.WriteRawTag(16); + output.WriteInt32(Longitude); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Latitude != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Latitude); + } + if (Longitude != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Longitude); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Point other) { + if (other == null) { + return; + } + if (other.Latitude != 0) { + Latitude = other.Latitude; + } + if (other.Longitude != 0) { + Longitude = other.Longitude; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Latitude = input.ReadInt32(); + break; + } + case 16: { + Longitude = input.ReadInt32(); + break; + } + } + } + } + + } + + /// <summary> + /// A latitude-longitude rectangle, represented as two diagonally opposite + /// points "lo" and "hi". + /// </summary> + public sealed partial class Rectangle : pb::IMessage<Rectangle> { + private static readonly pb::MessageParser<Rectangle> _parser = new pb::MessageParser<Rectangle>(() => new Rectangle()); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser<Rectangle> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Routeguide.RouteGuideReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Rectangle() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Rectangle(Rectangle other) : this() { + Lo = other.lo_ != null ? other.Lo.Clone() : null; + Hi = other.hi_ != null ? other.Hi.Clone() : null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Rectangle Clone() { + return new Rectangle(this); + } + + /// <summary>Field number for the "lo" field.</summary> + public const int LoFieldNumber = 1; + private global::Routeguide.Point lo_; + /// <summary> + /// One corner of the rectangle. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Routeguide.Point Lo { + get { return lo_; } + set { + lo_ = value; + } + } + + /// <summary>Field number for the "hi" field.</summary> + public const int HiFieldNumber = 2; + private global::Routeguide.Point hi_; + /// <summary> + /// The other corner of the rectangle. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Routeguide.Point Hi { + get { return hi_; } + set { + hi_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Rectangle); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Rectangle other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Lo, other.Lo)) return false; + if (!object.Equals(Hi, other.Hi)) return false; + return true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (lo_ != null) hash ^= Lo.GetHashCode(); + if (hi_ != null) hash ^= Hi.GetHashCode(); + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (lo_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Lo); + } + if (hi_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Hi); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (lo_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Lo); + } + if (hi_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Hi); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Rectangle other) { + if (other == null) { + return; + } + if (other.lo_ != null) { + if (lo_ == null) { + lo_ = new global::Routeguide.Point(); + } + Lo.MergeFrom(other.Lo); + } + if (other.hi_ != null) { + if (hi_ == null) { + hi_ = new global::Routeguide.Point(); + } + Hi.MergeFrom(other.Hi); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + if (lo_ == null) { + lo_ = new global::Routeguide.Point(); + } + input.ReadMessage(lo_); + break; + } + case 18: { + if (hi_ == null) { + hi_ = new global::Routeguide.Point(); + } + input.ReadMessage(hi_); + break; + } + } + } + } + + } + + /// <summary> + /// A feature names something at a given point. + /// + /// If a feature could not be named, the name is empty. + /// </summary> + public sealed partial class Feature : pb::IMessage<Feature> { + private static readonly pb::MessageParser<Feature> _parser = new pb::MessageParser<Feature>(() => new Feature()); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser<Feature> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Routeguide.RouteGuideReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Feature() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Feature(Feature other) : this() { + name_ = other.name_; + Location = other.location_ != null ? other.Location.Clone() : null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Feature Clone() { + return new Feature(this); + } + + /// <summary>Field number for the "name" field.</summary> + public const int NameFieldNumber = 1; + private string name_ = ""; + /// <summary> + /// The name of the feature. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// <summary>Field number for the "location" field.</summary> + public const int LocationFieldNumber = 2; + private global::Routeguide.Point location_; + /// <summary> + /// The point where the feature is detected. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Routeguide.Point Location { + get { return location_; } + set { + location_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Feature); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Feature other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (!object.Equals(Location, other.Location)) return false; + return true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (location_ != null) hash ^= Location.GetHashCode(); + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (location_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Location); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (location_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Location); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Feature other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.location_ != null) { + if (location_ == null) { + location_ = new global::Routeguide.Point(); + } + Location.MergeFrom(other.Location); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + if (location_ == null) { + location_ = new global::Routeguide.Point(); + } + input.ReadMessage(location_); + break; + } + } + } + } + + } + + /// <summary> + /// A RouteNote is a message sent while at a given point. + /// </summary> + public sealed partial class RouteNote : pb::IMessage<RouteNote> { + private static readonly pb::MessageParser<RouteNote> _parser = new pb::MessageParser<RouteNote>(() => new RouteNote()); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser<RouteNote> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Routeguide.RouteGuideReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteNote() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteNote(RouteNote other) : this() { + Location = other.location_ != null ? other.Location.Clone() : null; + message_ = other.message_; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteNote Clone() { + return new RouteNote(this); + } + + /// <summary>Field number for the "location" field.</summary> + public const int LocationFieldNumber = 1; + private global::Routeguide.Point location_; + /// <summary> + /// The location from which the message is sent. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::Routeguide.Point Location { + get { return location_; } + set { + location_ = value; + } + } + + /// <summary>Field number for the "message" field.</summary> + public const int MessageFieldNumber = 2; + private string message_ = ""; + /// <summary> + /// The message to be sent. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Message { + get { return message_; } + set { + message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RouteNote); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RouteNote other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Location, other.Location)) return false; + if (Message != other.Message) return false; + return true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (location_ != null) hash ^= Location.GetHashCode(); + if (Message.Length != 0) hash ^= Message.GetHashCode(); + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (location_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Location); + } + if (Message.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Message); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (location_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Location); + } + if (Message.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RouteNote other) { + if (other == null) { + return; + } + if (other.location_ != null) { + if (location_ == null) { + location_ = new global::Routeguide.Point(); + } + Location.MergeFrom(other.Location); + } + if (other.Message.Length != 0) { + Message = other.Message; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + if (location_ == null) { + location_ = new global::Routeguide.Point(); + } + input.ReadMessage(location_); + break; + } + case 18: { + Message = input.ReadString(); + break; + } + } + } + } + + } + + /// <summary> + /// A RouteSummary is received in response to a RecordRoute rpc. + /// + /// It contains the number of individual points received, the number of + /// detected features, and the total distance covered as the cumulative sum of + /// the distance between each point. + /// </summary> + public sealed partial class RouteSummary : pb::IMessage<RouteSummary> { + private static readonly pb::MessageParser<RouteSummary> _parser = new pb::MessageParser<RouteSummary>(() => new RouteSummary()); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser<RouteSummary> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Routeguide.RouteGuideReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteSummary() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteSummary(RouteSummary other) : this() { + pointCount_ = other.pointCount_; + featureCount_ = other.featureCount_; + distance_ = other.distance_; + elapsedTime_ = other.elapsedTime_; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RouteSummary Clone() { + return new RouteSummary(this); + } + + /// <summary>Field number for the "point_count" field.</summary> + public const int PointCountFieldNumber = 1; + private int pointCount_; + /// <summary> + /// The number of points received. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int PointCount { + get { return pointCount_; } + set { + pointCount_ = value; + } + } + + /// <summary>Field number for the "feature_count" field.</summary> + public const int FeatureCountFieldNumber = 2; + private int featureCount_; + /// <summary> + /// The number of known features passed while traversing the route. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int FeatureCount { + get { return featureCount_; } + set { + featureCount_ = value; + } + } + + /// <summary>Field number for the "distance" field.</summary> + public const int DistanceFieldNumber = 3; + private int distance_; + /// <summary> + /// The distance covered in metres. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int Distance { + get { return distance_; } + set { + distance_ = value; + } + } + + /// <summary>Field number for the "elapsed_time" field.</summary> + public const int ElapsedTimeFieldNumber = 4; + private int elapsedTime_; + /// <summary> + /// The duration of the traversal in seconds. + /// </summary> + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int ElapsedTime { + get { return elapsedTime_; } + set { + elapsedTime_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RouteSummary); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RouteSummary other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (PointCount != other.PointCount) return false; + if (FeatureCount != other.FeatureCount) return false; + if (Distance != other.Distance) return false; + if (ElapsedTime != other.ElapsedTime) return false; + return true; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (PointCount != 0) hash ^= PointCount.GetHashCode(); + if (FeatureCount != 0) hash ^= FeatureCount.GetHashCode(); + if (Distance != 0) hash ^= Distance.GetHashCode(); + if (ElapsedTime != 0) hash ^= ElapsedTime.GetHashCode(); + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (PointCount != 0) { + output.WriteRawTag(8); + output.WriteInt32(PointCount); + } + if (FeatureCount != 0) { + output.WriteRawTag(16); + output.WriteInt32(FeatureCount); + } + if (Distance != 0) { + output.WriteRawTag(24); + output.WriteInt32(Distance); + } + if (ElapsedTime != 0) { + output.WriteRawTag(32); + output.WriteInt32(ElapsedTime); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (PointCount != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PointCount); + } + if (FeatureCount != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FeatureCount); + } + if (Distance != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Distance); + } + if (ElapsedTime != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(ElapsedTime); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RouteSummary other) { + if (other == null) { + return; + } + if (other.PointCount != 0) { + PointCount = other.PointCount; + } + if (other.FeatureCount != 0) { + FeatureCount = other.FeatureCount; + } + if (other.Distance != 0) { + Distance = other.Distance; + } + if (other.ElapsedTime != 0) { + ElapsedTime = other.ElapsedTime; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + PointCount = input.ReadInt32(); + break; + } + case 16: { + FeatureCount = input.ReadInt32(); + break; + } + case 24: { + Distance = input.ReadInt32(); + break; + } + case 32: { + ElapsedTime = input.ReadInt32(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/examples/csharp/RouteGuide/RouteGuide/RouteGuide.csproj b/examples/csharp/RouteGuide/RouteGuide/RouteGuide.csproj new file mode 100644 index 0000000000..0d9d21f150 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide/RouteGuide.csproj @@ -0,0 +1,25 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <AssemblyTitle>RouteGuide</AssemblyTitle> + <TargetFrameworks>netcoreapp1.0</TargetFrameworks> + <DebugType>portable</DebugType> + <AssemblyName>RouteGuide</AssemblyName> + <PackageId>RouteGuide</PackageId> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Google.Protobuf" Version="3.5.0" /> + <PackageReference Include="Google.Protobuf.Tools" Version="3.5.0" /> + <PackageReference Include="Grpc" Version="1.8.0" /> + <PackageReference Include="Grpc.Tools" Version="1.8.0" /> + <PackageReference Include="Newtonsoft.Json" Version="9.0.1" /> + </ItemGroup> + + <ItemGroup> + <None Include="route_guide_db.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + +</Project> diff --git a/examples/csharp/RouteGuide/RouteGuide/RouteGuideGrpc.cs b/examples/csharp/RouteGuide/RouteGuide/RouteGuideGrpc.cs new file mode 100644 index 0000000000..765d5d520b --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide/RouteGuideGrpc.cs @@ -0,0 +1,332 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: route_guide.proto +// Original file comments: +// Copyright 2015 gRPC 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. +// +#pragma warning disable 1591 +#region Designer generated code + +using System; +using System.Threading; +using System.Threading.Tasks; +using grpc = global::Grpc.Core; + +namespace Routeguide { + /// <summary> + /// Interface exported by the server. + /// </summary> + public static partial class RouteGuide + { + static readonly string __ServiceName = "routeguide.RouteGuide"; + + static readonly grpc::Marshaller<global::Routeguide.Point> __Marshaller_Point = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Point.Parser.ParseFrom); + static readonly grpc::Marshaller<global::Routeguide.Feature> __Marshaller_Feature = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Feature.Parser.ParseFrom); + static readonly grpc::Marshaller<global::Routeguide.Rectangle> __Marshaller_Rectangle = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.Rectangle.Parser.ParseFrom); + static readonly grpc::Marshaller<global::Routeguide.RouteSummary> __Marshaller_RouteSummary = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteSummary.Parser.ParseFrom); + static readonly grpc::Marshaller<global::Routeguide.RouteNote> __Marshaller_RouteNote = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Routeguide.RouteNote.Parser.ParseFrom); + + static readonly grpc::Method<global::Routeguide.Point, global::Routeguide.Feature> __Method_GetFeature = new grpc::Method<global::Routeguide.Point, global::Routeguide.Feature>( + grpc::MethodType.Unary, + __ServiceName, + "GetFeature", + __Marshaller_Point, + __Marshaller_Feature); + + static readonly grpc::Method<global::Routeguide.Rectangle, global::Routeguide.Feature> __Method_ListFeatures = new grpc::Method<global::Routeguide.Rectangle, global::Routeguide.Feature>( + grpc::MethodType.ServerStreaming, + __ServiceName, + "ListFeatures", + __Marshaller_Rectangle, + __Marshaller_Feature); + + static readonly grpc::Method<global::Routeguide.Point, global::Routeguide.RouteSummary> __Method_RecordRoute = new grpc::Method<global::Routeguide.Point, global::Routeguide.RouteSummary>( + grpc::MethodType.ClientStreaming, + __ServiceName, + "RecordRoute", + __Marshaller_Point, + __Marshaller_RouteSummary); + + static readonly grpc::Method<global::Routeguide.RouteNote, global::Routeguide.RouteNote> __Method_RouteChat = new grpc::Method<global::Routeguide.RouteNote, global::Routeguide.RouteNote>( + grpc::MethodType.DuplexStreaming, + __ServiceName, + "RouteChat", + __Marshaller_RouteNote, + __Marshaller_RouteNote); + + /// <summary>Service descriptor</summary> + public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor + { + get { return global::Routeguide.RouteGuideReflection.Descriptor.Services[0]; } + } + + /// <summary>Base class for server-side implementations of RouteGuide</summary> + public abstract partial class RouteGuideBase + { + /// <summary> + /// A simple RPC. + /// + /// Obtains the feature at a given position. + /// + /// A feature with an empty name is returned if there's no feature at the given + /// position. + /// </summary> + /// <param name="request">The request received from the client.</param> + /// <param name="context">The context of the server-side call handler being invoked.</param> + /// <returns>The response to send back to the client (wrapped by a task).</returns> + public virtual global::System.Threading.Tasks.Task<global::Routeguide.Feature> GetFeature(global::Routeguide.Point request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + /// <summary> + /// A server-to-client streaming RPC. + /// + /// Obtains the Features available within the given Rectangle. Results are + /// streamed rather than returned at once (e.g. in a response message with a + /// repeated field), as the rectangle may cover a large area and contain a + /// huge number of features. + /// </summary> + /// <param name="request">The request received from the client.</param> + /// <param name="responseStream">Used for sending responses back to the client.</param> + /// <param name="context">The context of the server-side call handler being invoked.</param> + /// <returns>A task indicating completion of the handler.</returns> + public virtual global::System.Threading.Tasks.Task ListFeatures(global::Routeguide.Rectangle request, grpc::IServerStreamWriter<global::Routeguide.Feature> responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + /// <summary> + /// A client-to-server streaming RPC. + /// + /// Accepts a stream of Points on a route being traversed, returning a + /// RouteSummary when traversal is completed. + /// </summary> + /// <param name="requestStream">Used for reading requests from the client.</param> + /// <param name="context">The context of the server-side call handler being invoked.</param> + /// <returns>The response to send back to the client (wrapped by a task).</returns> + public virtual global::System.Threading.Tasks.Task<global::Routeguide.RouteSummary> RecordRoute(grpc::IAsyncStreamReader<global::Routeguide.Point> requestStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + /// <summary> + /// A Bidirectional streaming RPC. + /// + /// Accepts a stream of RouteNotes sent while a route is being traversed, + /// while receiving other RouteNotes (e.g. from other users). + /// </summary> + /// <param name="requestStream">Used for reading requests from the client.</param> + /// <param name="responseStream">Used for sending responses back to the client.</param> + /// <param name="context">The context of the server-side call handler being invoked.</param> + /// <returns>A task indicating completion of the handler.</returns> + public virtual global::System.Threading.Tasks.Task RouteChat(grpc::IAsyncStreamReader<global::Routeguide.RouteNote> requestStream, grpc::IServerStreamWriter<global::Routeguide.RouteNote> responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + } + + /// <summary>Client for RouteGuide</summary> + public partial class RouteGuideClient : grpc::ClientBase<RouteGuideClient> + { + /// <summary>Creates a new client for RouteGuide</summary> + /// <param name="channel">The channel to use to make remote calls.</param> + public RouteGuideClient(grpc::Channel channel) : base(channel) + { + } + /// <summary>Creates a new client for RouteGuide that uses a custom <c>CallInvoker</c>.</summary> + /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> + public RouteGuideClient(grpc::CallInvoker callInvoker) : base(callInvoker) + { + } + /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> + protected RouteGuideClient() : base() + { + } + /// <summary>Protected constructor to allow creation of configured clients.</summary> + /// <param name="configuration">The client configuration.</param> + protected RouteGuideClient(ClientBaseConfiguration configuration) : base(configuration) + { + } + + /// <summary> + /// A simple RPC. + /// + /// Obtains the feature at a given position. + /// + /// A feature with an empty name is returned if there's no feature at the given + /// position. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> + /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> + /// <param name="cancellationToken">An optional token for canceling the call.</param> + /// <returns>The response received from the server.</returns> + public virtual global::Routeguide.Feature GetFeature(global::Routeguide.Point request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetFeature(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// <summary> + /// A simple RPC. + /// + /// Obtains the feature at a given position. + /// + /// A feature with an empty name is returned if there's no feature at the given + /// position. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="options">The options for the call.</param> + /// <returns>The response received from the server.</returns> + public virtual global::Routeguide.Feature GetFeature(global::Routeguide.Point request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_GetFeature, null, options, request); + } + /// <summary> + /// A simple RPC. + /// + /// Obtains the feature at a given position. + /// + /// A feature with an empty name is returned if there's no feature at the given + /// position. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> + /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> + /// <param name="cancellationToken">An optional token for canceling the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return GetFeatureAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// <summary> + /// A simple RPC. + /// + /// Obtains the feature at a given position. + /// + /// A feature with an empty name is returned if there's no feature at the given + /// position. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="options">The options for the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncUnaryCall<global::Routeguide.Feature> GetFeatureAsync(global::Routeguide.Point request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_GetFeature, null, options, request); + } + /// <summary> + /// A server-to-client streaming RPC. + /// + /// Obtains the Features available within the given Rectangle. Results are + /// streamed rather than returned at once (e.g. in a response message with a + /// repeated field), as the rectangle may cover a large area and contain a + /// huge number of features. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> + /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> + /// <param name="cancellationToken">An optional token for canceling the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return ListFeatures(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// <summary> + /// A server-to-client streaming RPC. + /// + /// Obtains the Features available within the given Rectangle. Results are + /// streamed rather than returned at once (e.g. in a response message with a + /// repeated field), as the rectangle may cover a large area and contain a + /// huge number of features. + /// </summary> + /// <param name="request">The request to send to the server.</param> + /// <param name="options">The options for the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncServerStreamingCall<global::Routeguide.Feature> ListFeatures(global::Routeguide.Rectangle request, grpc::CallOptions options) + { + return CallInvoker.AsyncServerStreamingCall(__Method_ListFeatures, null, options, request); + } + /// <summary> + /// A client-to-server streaming RPC. + /// + /// Accepts a stream of Points on a route being traversed, returning a + /// RouteSummary when traversal is completed. + /// </summary> + /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> + /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> + /// <param name="cancellationToken">An optional token for canceling the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return RecordRoute(new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// <summary> + /// A client-to-server streaming RPC. + /// + /// Accepts a stream of Points on a route being traversed, returning a + /// RouteSummary when traversal is completed. + /// </summary> + /// <param name="options">The options for the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncClientStreamingCall<global::Routeguide.Point, global::Routeguide.RouteSummary> RecordRoute(grpc::CallOptions options) + { + return CallInvoker.AsyncClientStreamingCall(__Method_RecordRoute, null, options); + } + /// <summary> + /// A Bidirectional streaming RPC. + /// + /// Accepts a stream of RouteNotes sent while a route is being traversed, + /// while receiving other RouteNotes (e.g. from other users). + /// </summary> + /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> + /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> + /// <param name="cancellationToken">An optional token for canceling the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) + { + return RouteChat(new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// <summary> + /// A Bidirectional streaming RPC. + /// + /// Accepts a stream of RouteNotes sent while a route is being traversed, + /// while receiving other RouteNotes (e.g. from other users). + /// </summary> + /// <param name="options">The options for the call.</param> + /// <returns>The call object.</returns> + public virtual grpc::AsyncDuplexStreamingCall<global::Routeguide.RouteNote, global::Routeguide.RouteNote> RouteChat(grpc::CallOptions options) + { + return CallInvoker.AsyncDuplexStreamingCall(__Method_RouteChat, null, options); + } + /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> + protected override RouteGuideClient NewInstance(ClientBaseConfiguration configuration) + { + return new RouteGuideClient(configuration); + } + } + + /// <summary>Creates service definition that can be registered with a server</summary> + /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> + public static grpc::ServerServiceDefinition BindService(RouteGuideBase serviceImpl) + { + return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_GetFeature, serviceImpl.GetFeature) + .AddMethod(__Method_ListFeatures, serviceImpl.ListFeatures) + .AddMethod(__Method_RecordRoute, serviceImpl.RecordRoute) + .AddMethod(__Method_RouteChat, serviceImpl.RouteChat).Build(); + } + + } +} +#endregion diff --git a/examples/csharp/RouteGuide/RouteGuide/RouteGuideUtil.cs b/examples/csharp/RouteGuide/RouteGuide/RouteGuideUtil.cs new file mode 100644 index 0000000000..f9af190888 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide/RouteGuideUtil.cs @@ -0,0 +1,123 @@ +// Copyright 2015 gRPC 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. + +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Routeguide +{ + /// <summary> + /// Utility methods for the route guide example. + /// </summary> + public static class RouteGuideUtil + { + public const string DefaultFeaturesFile = "route_guide_db.json"; + + private const double CoordFactor = 1e7; + + /// <summary> + /// Indicates whether the given feature exists (i.e. has a valid name). + /// </summary> + public static bool Exists(this Feature feature) + { + return feature != null && (feature.Name.Length != 0); + } + + public static double GetLatitude(this Point point) + { + return point.Latitude / CoordFactor; + } + + public static double GetLongitude(this Point point) + { + return point.Longitude / CoordFactor; + } + + /// <summary> + /// Calculate the distance between two points using the "haversine" formula. + /// The formula is based on http://mathforum.org/library/drmath/view/51879.html + /// </summary> + /// <param name="start">the starting point</param> + /// <param name="end">the end point</param> + /// <returns>the distance between the points in meters</returns> + public static double GetDistance(this Point start, Point end) + { + int r = 6371000; // earth radius in metres + double lat1 = ToRadians(start.GetLatitude()); + double lat2 = ToRadians(end.GetLatitude()); + double lon1 = ToRadians(start.GetLongitude()); + double lon2 = ToRadians(end.GetLongitude()); + double deltalat = lat2 - lat1; + double deltalon = lon2 - lon1; + + double a = Math.Sin(deltalat / 2) * Math.Sin(deltalat / 2) + Math.Cos(lat1) * Math.Cos(lat2) * Math.Sin(deltalon / 2) * Math.Sin(deltalon / 2); + double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); + return r * c; + } + + /// <summary> + /// Returns <c>true</c> if rectangular area contains given point. + /// </summary> + public static bool Contains(this Rectangle rectangle, Point point) + { + int left = Math.Min(rectangle.Lo.Longitude, rectangle.Hi.Longitude); + int right = Math.Max(rectangle.Lo.Longitude, rectangle.Hi.Longitude); + int top = Math.Max(rectangle.Lo.Latitude, rectangle.Hi.Latitude); + int bottom = Math.Min(rectangle.Lo.Latitude, rectangle.Hi.Latitude); + return (point.Longitude >= left && point.Longitude <= right && point.Latitude >= bottom && point.Latitude <= top); + } + + private static double ToRadians(double val) + { + return (Math.PI / 180) * val; + } + + /// <summary> + /// Parses features from a JSON file. + /// </summary> + public static List<Feature> ParseFeatures(string filename) + { + var features = new List<Feature>(); + var jsonFeatures = JsonConvert.DeserializeObject<List<JsonFeature>>(File.ReadAllText(filename)); + + foreach(var jsonFeature in jsonFeatures) + { + features.Add(new Feature + { + Name = jsonFeature.name, + Location = new Point { Longitude = jsonFeature.location.longitude, Latitude = jsonFeature.location.latitude} + }); + } + return features; + } + + private class JsonFeature + { + public string name; + public JsonLocation location; + } + + private class JsonLocation + { + public int longitude; + public int latitude; + } + } +} diff --git a/examples/csharp/RouteGuide/RouteGuide/route_guide_db.json b/examples/csharp/RouteGuide/RouteGuide/route_guide_db.json new file mode 100644 index 0000000000..9342beb579 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuide/route_guide_db.json @@ -0,0 +1,601 @@ +[{ + "location": { + "latitude": 407838351, + "longitude": -746143763 + }, + "name": "Patriots Path, Mendham, NJ 07945, USA" +}, { + "location": { + "latitude": 408122808, + "longitude": -743999179 + }, + "name": "101 New Jersey 10, Whippany, NJ 07981, USA" +}, { + "location": { + "latitude": 413628156, + "longitude": -749015468 + }, + "name": "U.S. 6, Shohola, PA 18458, USA" +}, { + "location": { + "latitude": 419999544, + "longitude": -740371136 + }, + "name": "5 Conners Road, Kingston, NY 12401, USA" +}, { + "location": { + "latitude": 414008389, + "longitude": -743951297 + }, + "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA" +}, { + "location": { + "latitude": 419611318, + "longitude": -746524769 + }, + "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA" +}, { + "location": { + "latitude": 406109563, + "longitude": -742186778 + }, + "name": "4001 Tremley Point Road, Linden, NJ 07036, USA" +}, { + "location": { + "latitude": 416802456, + "longitude": -742370183 + }, + "name": "352 South Mountain Road, Wallkill, NY 12589, USA" +}, { + "location": { + "latitude": 412950425, + "longitude": -741077389 + }, + "name": "Bailey Turn Road, Harriman, NY 10926, USA" +}, { + "location": { + "latitude": 412144655, + "longitude": -743949739 + }, + "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA" +}, { + "location": { + "latitude": 415736605, + "longitude": -742847522 + }, + "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA" +}, { + "location": { + "latitude": 413843930, + "longitude": -740501726 + }, + "name": "162 Merrill Road, Highland Mills, NY 10930, USA" +}, { + "location": { + "latitude": 410873075, + "longitude": -744459023 + }, + "name": "Clinton Road, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 412346009, + "longitude": -744026814 + }, + "name": "16 Old Brook Lane, Warwick, NY 10990, USA" +}, { + "location": { + "latitude": 402948455, + "longitude": -747903913 + }, + "name": "3 Drake Lane, Pennington, NJ 08534, USA" +}, { + "location": { + "latitude": 406337092, + "longitude": -740122226 + }, + "name": "6324 8th Avenue, Brooklyn, NY 11220, USA" +}, { + "location": { + "latitude": 406421967, + "longitude": -747727624 + }, + "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA" +}, { + "location": { + "latitude": 416318082, + "longitude": -749677716 + }, + "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA" +}, { + "location": { + "latitude": 415301720, + "longitude": -748416257 + }, + "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA" +}, { + "location": { + "latitude": 402647019, + "longitude": -747071791 + }, + "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA" +}, { + "location": { + "latitude": 412567807, + "longitude": -741058078 + }, + "name": "New York State Reference Route 987E, Southfields, NY 10975, USA" +}, { + "location": { + "latitude": 416855156, + "longitude": -744420597 + }, + "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA" +}, { + "location": { + "latitude": 404663628, + "longitude": -744820157 + }, + "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA" +}, { + "location": { + "latitude": 407113723, + "longitude": -749746483 + }, + "name": "" +}, { + "location": { + "latitude": 402133926, + "longitude": -743613249 + }, + "name": "" +}, { + "location": { + "latitude": 400273442, + "longitude": -741220915 + }, + "name": "" +}, { + "location": { + "latitude": 411236786, + "longitude": -744070769 + }, + "name": "" +}, { + "location": { + "latitude": 411633782, + "longitude": -746784970 + }, + "name": "211-225 Plains Road, Augusta, NJ 07822, USA" +}, { + "location": { + "latitude": 415830701, + "longitude": -742952812 + }, + "name": "" +}, { + "location": { + "latitude": 413447164, + "longitude": -748712898 + }, + "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA" +}, { + "location": { + "latitude": 405047245, + "longitude": -749800722 + }, + "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA" +}, { + "location": { + "latitude": 418858923, + "longitude": -746156790 + }, + "name": "" +}, { + "location": { + "latitude": 417951888, + "longitude": -748484944 + }, + "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA" +}, { + "location": { + "latitude": 407033786, + "longitude": -743977337 + }, + "name": "26 East 3rd Street, New Providence, NJ 07974, USA" +}, { + "location": { + "latitude": 417548014, + "longitude": -740075041 + }, + "name": "" +}, { + "location": { + "latitude": 410395868, + "longitude": -744972325 + }, + "name": "" +}, { + "location": { + "latitude": 404615353, + "longitude": -745129803 + }, + "name": "" +}, { + "location": { + "latitude": 406589790, + "longitude": -743560121 + }, + "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA" +}, { + "location": { + "latitude": 414653148, + "longitude": -740477477 + }, + "name": "18 Lannis Avenue, New Windsor, NY 12553, USA" +}, { + "location": { + "latitude": 405957808, + "longitude": -743255336 + }, + "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA" +}, { + "location": { + "latitude": 411733589, + "longitude": -741648093 + }, + "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA" +}, { + "location": { + "latitude": 412676291, + "longitude": -742606606 + }, + "name": "1270 Lakes Road, Monroe, NY 10950, USA" +}, { + "location": { + "latitude": 409224445, + "longitude": -748286738 + }, + "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA" +}, { + "location": { + "latitude": 406523420, + "longitude": -742135517 + }, + "name": "652 Garden Street, Elizabeth, NJ 07202, USA" +}, { + "location": { + "latitude": 401827388, + "longitude": -740294537 + }, + "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA" +}, { + "location": { + "latitude": 410564152, + "longitude": -743685054 + }, + "name": "13-17 Stanley Street, West Milford, NJ 07480, USA" +}, { + "location": { + "latitude": 408472324, + "longitude": -740726046 + }, + "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA" +}, { + "location": { + "latitude": 412452168, + "longitude": -740214052 + }, + "name": "5 White Oak Lane, Stony Point, NY 10980, USA" +}, { + "location": { + "latitude": 409146138, + "longitude": -746188906 + }, + "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA" +}, { + "location": { + "latitude": 404701380, + "longitude": -744781745 + }, + "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 409642566, + "longitude": -746017679 + }, + "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA" +}, { + "location": { + "latitude": 408031728, + "longitude": -748645385 + }, + "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA" +}, { + "location": { + "latitude": 413700272, + "longitude": -742135189 + }, + "name": "367 Prospect Road, Chester, NY 10918, USA" +}, { + "location": { + "latitude": 404310607, + "longitude": -740282632 + }, + "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA" +}, { + "location": { + "latitude": 409319800, + "longitude": -746201391 + }, + "name": "11 Ward Street, Mount Arlington, NJ 07856, USA" +}, { + "location": { + "latitude": 406685311, + "longitude": -742108603 + }, + "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA" +}, { + "location": { + "latitude": 419018117, + "longitude": -749142781 + }, + "name": "43 Dreher Road, Roscoe, NY 12776, USA" +}, { + "location": { + "latitude": 412856162, + "longitude": -745148837 + }, + "name": "Swan Street, Pine Island, NY 10969, USA" +}, { + "location": { + "latitude": 416560744, + "longitude": -746721964 + }, + "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA" +}, { + "location": { + "latitude": 405314270, + "longitude": -749836354 + }, + "name": "" +}, { + "location": { + "latitude": 414219548, + "longitude": -743327440 + }, + "name": "" +}, { + "location": { + "latitude": 415534177, + "longitude": -742900616 + }, + "name": "565 Winding Hills Road, Montgomery, NY 12549, USA" +}, { + "location": { + "latitude": 406898530, + "longitude": -749127080 + }, + "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA" +}, { + "location": { + "latitude": 407586880, + "longitude": -741670168 + }, + "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA" +}, { + "location": { + "latitude": 400106455, + "longitude": -742870190 + }, + "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA" +}, { + "location": { + "latitude": 400066188, + "longitude": -746793294 + }, + "name": "" +}, { + "location": { + "latitude": 418803880, + "longitude": -744102673 + }, + "name": "40 Mountain Road, Napanoch, NY 12458, USA" +}, { + "location": { + "latitude": 414204288, + "longitude": -747895140 + }, + "name": "" +}, { + "location": { + "latitude": 414777405, + "longitude": -740615601 + }, + "name": "" +}, { + "location": { + "latitude": 415464475, + "longitude": -747175374 + }, + "name": "48 North Road, Forestburgh, NY 12777, USA" +}, { + "location": { + "latitude": 404062378, + "longitude": -746376177 + }, + "name": "" +}, { + "location": { + "latitude": 405688272, + "longitude": -749285130 + }, + "name": "" +}, { + "location": { + "latitude": 400342070, + "longitude": -748788996 + }, + "name": "" +}, { + "location": { + "latitude": 401809022, + "longitude": -744157964 + }, + "name": "" +}, { + "location": { + "latitude": 404226644, + "longitude": -740517141 + }, + "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA" +}, { + "location": { + "latitude": 410322033, + "longitude": -747871659 + }, + "name": "" +}, { + "location": { + "latitude": 407100674, + "longitude": -747742727 + }, + "name": "" +}, { + "location": { + "latitude": 418811433, + "longitude": -741718005 + }, + "name": "213 Bush Road, Stone Ridge, NY 12484, USA" +}, { + "location": { + "latitude": 415034302, + "longitude": -743850945 + }, + "name": "" +}, { + "location": { + "latitude": 411349992, + "longitude": -743694161 + }, + "name": "" +}, { + "location": { + "latitude": 404839914, + "longitude": -744759616 + }, + "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA" +}, { + "location": { + "latitude": 414638017, + "longitude": -745957854 + }, + "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA" +}, { + "location": { + "latitude": 412127800, + "longitude": -740173578 + }, + "name": "" +}, { + "location": { + "latitude": 401263460, + "longitude": -747964303 + }, + "name": "" +}, { + "location": { + "latitude": 412843391, + "longitude": -749086026 + }, + "name": "" +}, { + "location": { + "latitude": 418512773, + "longitude": -743067823 + }, + "name": "" +}, { + "location": { + "latitude": 404318328, + "longitude": -740835638 + }, + "name": "42-102 Main Street, Belford, NJ 07718, USA" +}, { + "location": { + "latitude": 419020746, + "longitude": -741172328 + }, + "name": "" +}, { + "location": { + "latitude": 404080723, + "longitude": -746119569 + }, + "name": "" +}, { + "location": { + "latitude": 401012643, + "longitude": -744035134 + }, + "name": "" +}, { + "location": { + "latitude": 404306372, + "longitude": -741079661 + }, + "name": "" +}, { + "location": { + "latitude": 403966326, + "longitude": -748519297 + }, + "name": "" +}, { + "location": { + "latitude": 405002031, + "longitude": -748407866 + }, + "name": "" +}, { + "location": { + "latitude": 409532885, + "longitude": -742200683 + }, + "name": "" +}, { + "location": { + "latitude": 416851321, + "longitude": -742674555 + }, + "name": "" +}, { + "location": { + "latitude": 406411633, + "longitude": -741722051 + }, + "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA" +}, { + "location": { + "latitude": 413069058, + "longitude": -744597778 + }, + "name": "261 Van Sickle Road, Goshen, NY 10924, USA" +}, { + "location": { + "latitude": 418465462, + "longitude": -746859398 + }, + "name": "" +}, { + "location": { + "latitude": 411733222, + "longitude": -744228360 + }, + "name": "" +}, { + "location": { + "latitude": 410248224, + "longitude": -747127767 + }, + "name": "3 Hasta Way, Newton, NJ 07860, USA" +}]
\ No newline at end of file diff --git a/examples/csharp/RouteGuide/RouteGuideClient/Program.cs b/examples/csharp/RouteGuide/RouteGuideClient/Program.cs new file mode 100644 index 0000000000..9ce0cbcad3 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuideClient/Program.cs @@ -0,0 +1,241 @@ +// Copyright 2015 gRPC 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. + +using Grpc.Core; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Routeguide +{ + class Program + { + /// <summary> + /// Sample client code that makes gRPC calls to the server. + /// </summary> + public class RouteGuideClient + { + readonly RouteGuide.RouteGuideClient client; + + public RouteGuideClient(RouteGuide.RouteGuideClient client) + { + this.client = client; + } + + /// <summary> + /// Blocking unary call example. Calls GetFeature and prints the response. + /// </summary> + public void GetFeature(int lat, int lon) + { + try + { + Log("*** GetFeature: lat={0} lon={1}", lat, lon); + + Point request = new Point { Latitude = lat, Longitude = lon }; + + Feature feature = client.GetFeature(request); + if (feature.Exists()) + { + Log("Found feature called \"{0}\" at {1}, {2}", + feature.Name, feature.Location.GetLatitude(), feature.Location.GetLongitude()); + } + else + { + Log("Found no feature at {0}, {1}", + feature.Location.GetLatitude(), feature.Location.GetLongitude()); + } + } + catch (RpcException e) + { + Log("RPC failed " + e); + throw; + } + } + + + /// <summary> + /// Server-streaming example. Calls listFeatures with a rectangle of interest. Prints each response feature as it arrives. + /// </summary> + public async Task ListFeatures(int lowLat, int lowLon, int hiLat, int hiLon) + { + try + { + Log("*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", lowLat, lowLon, hiLat, + hiLon); + + Rectangle request = new Rectangle + { + Lo = new Point { Latitude = lowLat, Longitude = lowLon }, + Hi = new Point { Latitude = hiLat, Longitude = hiLon } + }; + + using (var call = client.ListFeatures(request)) + { + var responseStream = call.ResponseStream; + StringBuilder responseLog = new StringBuilder("Result: "); + + while (await responseStream.MoveNext()) + { + Feature feature = responseStream.Current; + responseLog.Append(feature.ToString()); + } + Log(responseLog.ToString()); + } + } + catch (RpcException e) + { + Log("RPC failed " + e); + throw; + } + } + + /// <summary> + /// Client-streaming example. Sends numPoints randomly chosen points from features + /// with a variable delay in between. Prints the statistics when they are sent from the server. + /// </summary> + public async Task RecordRoute(List<Feature> features, int numPoints) + { + try + { + Log("*** RecordRoute"); + using (var call = client.RecordRoute()) + { + // Send numPoints points randomly selected from the features list. + StringBuilder numMsg = new StringBuilder(); + Random rand = new Random(); + for (int i = 0; i < numPoints; ++i) + { + int index = rand.Next(features.Count); + Point point = features[index].Location; + Log("Visiting point {0}, {1}", point.GetLatitude(), point.GetLongitude()); + + await call.RequestStream.WriteAsync(point); + + // A bit of delay before sending the next one. + await Task.Delay(rand.Next(1000) + 500); + } + await call.RequestStream.CompleteAsync(); + + RouteSummary summary = await call.ResponseAsync; + Log("Finished trip with {0} points. Passed {1} features. " + + "Travelled {2} meters. It took {3} seconds.", summary.PointCount, + summary.FeatureCount, summary.Distance, summary.ElapsedTime); + + Log("Finished RecordRoute"); + } + } + catch (RpcException e) + { + Log("RPC failed", e); + throw; + } + } + + /// <summary> + /// Bi-directional streaming example. Send some chat messages, and print any + /// chat messages that are sent from the server. + /// </summary> + public async Task RouteChat() + { + try + { + Log("*** RouteChat"); + var requests = new List<RouteNote> + { + NewNote("First message", 0, 0), + NewNote("Second message", 0, 1), + NewNote("Third message", 1, 0), + NewNote("Fourth message", 0, 0) + }; + + using (var call = client.RouteChat()) + { + var responseReaderTask = Task.Run(async () => + { + while (await call.ResponseStream.MoveNext()) + { + var note = call.ResponseStream.Current; + Log("Got message \"{0}\" at {1}, {2}", note.Message, + note.Location.Latitude, note.Location.Longitude); + } + }); + + foreach (RouteNote request in requests) + { + Log("Sending message \"{0}\" at {1}, {2}", request.Message, + request.Location.Latitude, request.Location.Longitude); + + await call.RequestStream.WriteAsync(request); + } + await call.RequestStream.CompleteAsync(); + await responseReaderTask; + + Log("Finished RouteChat"); + } + } + catch (RpcException e) + { + Log("RPC failed", e); + throw; + } + } + + private void Log(string s, params object[] args) + { + Console.WriteLine(string.Format(s, args)); + } + + private void Log(string s) + { + Console.WriteLine(s); + } + + private RouteNote NewNote(string message, int lat, int lon) + { + return new RouteNote + { + Message = message, + Location = new Point { Latitude = lat, Longitude = lon } + }; + } + } + + static void Main(string[] args) + { + var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure); + var client = new RouteGuideClient(new RouteGuide.RouteGuideClient(channel)); + + // Looking for a valid feature + client.GetFeature(409146138, -746188906); + + // Feature missing. + client.GetFeature(0, 0); + + // Looking for features between 40, -75 and 42, -73. + client.ListFeatures(400000000, -750000000, 420000000, -730000000).Wait(); + + // Record a few randomly selected points from the features file. + client.RecordRoute(RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile), 10).Wait(); + + // Send and receive some notes. + client.RouteChat().Wait(); + + channel.ShutdownAsync().Wait(); + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} diff --git a/examples/csharp/RouteGuide/RouteGuideClient/RouteGuideClient.csproj b/examples/csharp/RouteGuide/RouteGuideClient/RouteGuideClient.csproj new file mode 100644 index 0000000000..96cc204ba3 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuideClient/RouteGuideClient.csproj @@ -0,0 +1,16 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <AssemblyTitle>RouteGuideClient</AssemblyTitle> + <TargetFrameworks>netcoreapp1.0</TargetFrameworks> + <DebugType>portable</DebugType> + <AssemblyName>RouteGuideClient</AssemblyName> + <OutputType>Exe</OutputType> + <PackageId>RouteGuideClient</PackageId> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\RouteGuide\RouteGuide.csproj" /> + </ItemGroup> + +</Project> diff --git a/examples/csharp/RouteGuide/RouteGuideServer/Program.cs b/examples/csharp/RouteGuide/RouteGuideServer/Program.cs new file mode 100644 index 0000000000..4548ddf8e7 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuideServer/Program.cs @@ -0,0 +1,46 @@ +// Copyright 2015 gRPC 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. + +using Grpc.Core; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Routeguide +{ + class Program + { + static void Main(string[] args) + { + const int Port = 50052; + + var features = RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile); + + Server server = new Server + { + Services = { RouteGuide.BindService(new RouteGuideImpl(features)) }, + Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } + }; + server.Start(); + + Console.WriteLine("RouteGuide server listening on port " + Port); + Console.WriteLine("Press any key to stop the server..."); + Console.ReadKey(); + + server.ShutdownAsync().Wait(); + } + } +} diff --git a/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideImpl.cs b/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideImpl.cs new file mode 100644 index 0000000000..f157ca08ab --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideImpl.cs @@ -0,0 +1,153 @@ +// Copyright 2015 gRPC 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. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using Grpc.Core; +using Grpc.Core.Utils; + +namespace Routeguide +{ + /// <summary> + /// Example implementation of RouteGuide server. + /// </summary> + public class RouteGuideImpl : RouteGuide.RouteGuideBase + { + readonly List<Feature> features; + readonly object myLock = new object(); + readonly Dictionary<Point, List<RouteNote>> routeNotes = new Dictionary<Point, List<RouteNote>>(); + + public RouteGuideImpl(List<Feature> features) + { + this.features = features; + } + + /// <summary> + /// Gets the feature at the requested point. If no feature at that location + /// exists, an unnammed feature is returned at the provided location. + /// </summary> + public override Task<Feature> GetFeature(Point request, ServerCallContext context) + { + return Task.FromResult(CheckFeature(request)); + } + + /// <summary> + /// Gets all features contained within the given bounding rectangle. + /// </summary> + public override async Task ListFeatures(Rectangle request, IServerStreamWriter<Feature> responseStream, ServerCallContext context) + { + var responses = features.FindAll( (feature) => feature.Exists() && request.Contains(feature.Location) ); + foreach (var response in responses) + { + await responseStream.WriteAsync(response); + } + } + + /// <summary> + /// Gets a stream of points, and responds with statistics about the "trip": number of points, + /// number of known features visited, total distance traveled, and total time spent. + /// </summary> + public override async Task<RouteSummary> RecordRoute(IAsyncStreamReader<Point> requestStream, ServerCallContext context) + { + int pointCount = 0; + int featureCount = 0; + int distance = 0; + Point previous = null; + var stopwatch = new Stopwatch(); + stopwatch.Start(); + + while (await requestStream.MoveNext()) + { + var point = requestStream.Current; + pointCount++; + if (CheckFeature(point).Exists()) + { + featureCount++; + } + if (previous != null) + { + distance += (int) previous.GetDistance(point); + } + previous = point; + } + + stopwatch.Stop(); + + return new RouteSummary + { + PointCount = pointCount, + FeatureCount = featureCount, + Distance = distance, + ElapsedTime = (int)(stopwatch.ElapsedMilliseconds / 1000) + }; + } + + /// <summary> + /// Receives a stream of message/location pairs, and responds with a stream of all previous + /// messages at each of those locations. + /// </summary> + public override async Task RouteChat(IAsyncStreamReader<RouteNote> requestStream, IServerStreamWriter<RouteNote> responseStream, ServerCallContext context) + { + while (await requestStream.MoveNext()) + { + var note = requestStream.Current; + List<RouteNote> prevNotes = AddNoteForLocation(note.Location, note); + foreach (var prevNote in prevNotes) + { + await responseStream.WriteAsync(prevNote); + } + } + } + + /// <summary> + /// Adds a note for location and returns a list of pre-existing notes for that location (not containing the newly added note). + /// </summary> + private List<RouteNote> AddNoteForLocation(Point location, RouteNote note) + { + lock (myLock) + { + List<RouteNote> notes; + if (!routeNotes.TryGetValue(location, out notes)) { + notes = new List<RouteNote>(); + routeNotes.Add(location, notes); + } + var preexistingNotes = new List<RouteNote>(notes); + notes.Add(note); + return preexistingNotes; + } + } + + /// <summary> + /// Gets the feature at the given point. + /// </summary> + /// <param name="location">the location to check</param> + /// <returns>The feature object at the point Note that an empty name indicates no feature.</returns> + private Feature CheckFeature(Point location) + { + var result = features.FirstOrDefault((feature) => feature.Location.Equals(location)); + if (result == null) + { + // No feature was found, return an unnamed feature. + return new Feature { Name = "", Location = location }; + } + return result; + } + } +} diff --git a/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideServer.csproj b/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideServer.csproj new file mode 100644 index 0000000000..aa6315bf81 --- /dev/null +++ b/examples/csharp/RouteGuide/RouteGuideServer/RouteGuideServer.csproj @@ -0,0 +1,16 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <AssemblyTitle>RouteGuideServer</AssemblyTitle> + <TargetFrameworks>netcoreapp1.0</TargetFrameworks> + <DebugType>portable</DebugType> + <AssemblyName>RouteGuideServer</AssemblyName> + <OutputType>Exe</OutputType> + <PackageId>RouteGuideServer</PackageId> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\RouteGuide\RouteGuide.csproj" /> + </ItemGroup> + +</Project> diff --git a/examples/csharp/RouteGuide/generate_protos.bat b/examples/csharp/RouteGuide/generate_protos.bat new file mode 100644 index 0000000000..a8c9cb505a --- /dev/null +++ b/examples/csharp/RouteGuide/generate_protos.bat @@ -0,0 +1,26 @@ +@rem Copyright 2016 gRPC authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. + +@rem Generate the C# code for .proto files + +setlocal + +@rem enter this directory +cd /d %~dp0 + +set TOOLS_PATH=packages\Grpc.Tools.1.8.0\tools\windows_x86 + +%TOOLS_PATH%\protoc.exe -I../../protos --csharp_out RouteGuide ../../protos/route_guide.proto --grpc_out RouteGuide --plugin=protoc-gen-grpc=%TOOLS_PATH%\grpc_csharp_plugin.exe + +endlocal |