Commit 3f225111 authored by Jon Skeet's avatar Jon Skeet

Added address book example

parent 828510cd
# Untracked files # Untracked files
src/AddressBook/bin
src/AddressBook/obj
src/ProtocolBuffers/bin/ src/ProtocolBuffers/bin/
src/ProtocolBuffers/obj/ src/ProtocolBuffers/obj/
src/ProtocolBuffers.Test/bin/ src/ProtocolBuffers.Test/bin/
......
...@@ -80,6 +80,7 @@ ...@@ -80,6 +80,7 @@
<arg file="${protos-dir}/google/protobuf/unittest_import.proto" /> <arg file="${protos-dir}/google/protobuf/unittest_import.proto" />
<arg file="${protos-dir}/google/protobuf/unittest_mset.proto" /> <arg file="${protos-dir}/google/protobuf/unittest_mset.proto" />
<arg file="${protos-dir}/google/protobuf/unittest_optimize_for.proto" /> <arg file="${protos-dir}/google/protobuf/unittest_optimize_for.proto" />
<arg file="${protos-dir}/tutorial/addressbook.proto" />
</exec> </exec>
<exec program="${tools-protogen}" <exec program="${tools-protogen}"
...@@ -107,6 +108,12 @@ ...@@ -107,6 +108,12 @@
<include name="UnitTestOptimizeForProtoFile.cs" /> <include name="UnitTestOptimizeForProtoFile.cs" />
</fileset> </fileset>
</copy> </copy>
<copy todir="${src}/AddressBook">
<fileset basedir="${tmp-dir}">
<include name="AddressBookProtos.cs" />
</fileset>
</copy>
</target> </target>
<target name="build" <target name="build"
......
import "google/protobuf/csharp_options.proto";
import "google/protobuf/descriptor.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.Examples.AddressBook";
option (google.protobuf.csharp_file_options).umbrella_classname = "AddressBookProtos";
package tutorial;
option optimize_for = SPEED;
message Person {
required string name = 1;
required int32 id = 2; // Unique ID number for this person.
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
// Our address book file is just one of these.
message AddressBook {
repeated Person person = 1;
}

using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
class AddPerson {
/// <summary>
/// Builds a person based on user input
/// </summary>
static Person PromptForAddress(TextReader input, TextWriter output) {
Person.Builder person = Person.CreateBuilder();
output.Write("Enter person ID: ");
person.Id = int.Parse(input.ReadLine());
output.Write("Enter name: ");
person.Name = input.ReadLine();
output.Write("Enter email address (blank for none): ");
string email = input.ReadLine();
if (email.Length > 0) {
person.Email = email;
}
while (true) {
output.Write("Enter a phone number (or leave blank to finish): ");
string number = input.ReadLine();
if (number.Length == 0) {
break;
}
Person.Types.PhoneNumber.Builder phoneNumber =
Person.Types.PhoneNumber.CreateBuilder().SetNumber(number);
output.Write("Is this a mobile, home, or work phone? ");
String type = input.ReadLine();
switch (type) {
case "mobile":
phoneNumber.Type = Person.Types.PhoneType.MOBILE;
break;
case "home":
phoneNumber.Type = Person.Types.PhoneType.HOME;
break;
case "work":
phoneNumber.Type = Person.Types.PhoneType.WORK;
break;
default:
output.Write("Unknown phone type. Using default.");
break;
}
person.AddPhone(phoneNumber);
}
return person.Build();
}
/// <summary>
/// Entry point - loads an existing addressbook or creates a new one,
/// then writes it back to the file.
/// </summary>
public static int Main(string[] args) {
if (args.Length != 1) {
Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE");
return -1;
}
AddressBook.Builder addressBook = AddressBook.CreateBuilder();
if (File.Exists(args[0])) {
using (Stream file = File.OpenRead(args[0])) {
addressBook.MergeFrom(file);
}
} else {
Console.WriteLine("{0}: File not found. Creating a new file.", args[0]);
}
// Add an address.
addressBook.AddPerson(PromptForAddress(Console.In, Console.Out));
// Write the new address book back to disk.
using (Stream output = File.OpenWrite(args[0])) {
addressBook.Build().WriteTo(output);
}
return 0;
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A31F5FB2-4FF3-432A-B35B-5CD203606311}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.Examples.AddressBook</RootNamespace>
<AssemblyName>AddressBook</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkSubset>
</TargetFrameworkSubset>
<StartupObject>Google.ProtocolBuffers.Examples.AddressBook.Program</StartupObject>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="AddPerson.cs" />
<Compile Include="AddressBookProtos.cs" />
<Compile Include="ListPeople.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
This diff is collapsed.

using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook {
class ListPeople {
/// <summary>
/// Iterates though all people in the AddressBook and prints info about them.
/// </summary>
static void Print(AddressBook addressBook) {
foreach (Person person in addressBook.PersonList) {
Console.WriteLine("Person ID: {0}", person.Id);
Console.WriteLine(" Name: {0}", person.Name);
if (person.HasEmail) {
Console.WriteLine(" E-mail address: {0}", person.Email);
}
foreach (Person.Types.PhoneNumber phoneNumber in person.PhoneList) {
switch (phoneNumber.Type) {
case Person.Types.PhoneType.MOBILE:
Console.Write(" Mobile phone #: ");
break;
case Person.Types.PhoneType.HOME:
Console.Write(" Home phone #: ");
break;
case Person.Types.PhoneType.WORK:
Console.Write(" Work phone #: ");
break;
}
Console.WriteLine(phoneNumber.Number);
}
}
}
/// <summary>
/// Entry point - loads the addressbook and then displays it.
/// </summary>
public static int Main(string[] args) {
if (args.Length != 1) {
Console.Error.WriteLine("Usage: ListPeople ADDRESS_BOOK_FILE");
return 1;
}
if (!File.Exists(args[0])) {
Console.WriteLine("{0} doesn't exist. Add a person to create the file first.", args[0]);
return 0;
}
// Read the existing address book.
using (Stream stream = File.OpenRead(args[0])) {
AddressBook addressBook = AddressBook.ParseFrom(stream);
Print(addressBook);
}
return 0;
}
}
}
using System;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
/// <summary>
/// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour
/// to individual actions. Each action has its own Main method, so that it can be used as an
/// invidual complete program.
/// </summary>
class Program {
static int Main(string[] args) {
if (args.Length > 1) {
Console.Error.WriteLine("Usage: AddressBook [file]");
Console.Error.WriteLine("If the filename isn't specified, \"addressbook.data\" is used instead.");
return 1;
}
string addressBookFile = args.Length > 0 ? args[0] : "addressbook.data";
bool stopping = false;
while (!stopping) {
Console.WriteLine("Options:");
Console.WriteLine(" L: List contents");
Console.WriteLine(" A: Add new person");
Console.WriteLine(" Q: Quit");
Console.Write("Action? ");
Console.Out.Flush();
char choice = Console.ReadKey().KeyChar;
Console.WriteLine();
try {
switch (choice) {
case 'A':
case 'a':
AddPerson.Main(new string[] { addressBookFile });
break;
case 'L':
case 'l':
ListPeople.Main(new string[] { addressBookFile });
break;
case 'Q':
case 'q':
stopping = true;
break;
default:
Console.WriteLine("Unknown option: {0}", choice);
break;
}
} catch (Exception e) {
Console.WriteLine("Exception executing action: {0}", e);
}
Console.WriteLine();
}
return 0;
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AddressBook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AddressBook")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("57123e6e-28d1-4b9e-80a5-5e720df8035a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
...@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoGen", "ProtoGen\ProtoG ...@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoGen", "ProtoGen\ProtoG
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoGen.Test", "ProtoGen.Test\ProtoGen.Test.csproj", "{C268DA4C-4004-47DA-AF23-44C983281A68}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoGen.Test", "ProtoGen.Test\ProtoGen.Test.csproj", "{C268DA4C-4004-47DA-AF23-44C983281A68}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddressBook", "AddressBook\AddressBook.csproj", "{A31F5FB2-4FF3-432A-B35B-5CD203606311}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -31,6 +33,10 @@ Global ...@@ -31,6 +33,10 @@ Global
{C268DA4C-4004-47DA-AF23-44C983281A68}.Debug|Any CPU.Build.0 = Debug|Any CPU {C268DA4C-4004-47DA-AF23-44C983281A68}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C268DA4C-4004-47DA-AF23-44C983281A68}.Release|Any CPU.ActiveCfg = Release|Any CPU {C268DA4C-4004-47DA-AF23-44C983281A68}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C268DA4C-4004-47DA-AF23-44C983281A68}.Release|Any CPU.Build.0 = Release|Any CPU {C268DA4C-4004-47DA-AF23-44C983281A68}.Release|Any CPU.Build.0 = Release|Any CPU
{A31F5FB2-4FF3-432A-B35B-5CD203606311}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A31F5FB2-4FF3-432A-B35B-5CD203606311}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A31F5FB2-4FF3-432A-B35B-5CD203606311}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A31F5FB2-4FF3-432A-B35B-5CD203606311}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
......
Current task list (not in order) Current task list (not in order)
Diff stuff
- Performance framework - Performance framework
- Optionally remove dependencies to core and csharp options - Optionally remove dependencies to core and csharp options (2.0.3
will remove core dependency)
- Remove multifile support - Remove multifile support
- Mono support - Mono support
- Docs - Docs
......
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