Added sample code from the Getting Started Wiki

pull/288/head
csharptest 14 years ago committed by rogerk
parent 232c79562c
commit 1ee7a96b36
  1. 5
      src/AddressBook/AddressBook.csproj
  2. 44
      src/AddressBook/SampleUsage.cs

@ -54,12 +54,15 @@
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AddPerson.cs" />
<Compile Include="AddressBookProtos.cs" />
<Compile Include="SampleUsage.cs" />
<Compile Include="ListPeople.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

@ -0,0 +1,44 @@
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
class SampleUsage
{
static void Main()
{
byte[] bytes;
//Create a builder to start building a message
Person.Builder newContact = Person.CreateBuilder();
//Set the primitive properties
newContact.SetId(1)
.SetName("Foo")
.SetEmail("foo@bar");
//Now add an item to a list (repeating) field
newContact.AddPhone(
//Create the child message inline
Person.Types.PhoneNumber.CreateBuilder().SetNumber("555-1212").Build()
);
//Now build the final message:
Person person = newContact.Build();
//The builder is no longer valid (at least not now, scheduled for 2.4):
newContact = null;
using(MemoryStream stream = new MemoryStream())
{
//Save the person to a stream
person.WriteTo(stream);
bytes = stream.ToArray();
}
//Create another builder, merge the byte[], and build the message:
Person copy = Person.CreateBuilder().MergeFrom(bytes).Build();
//A more streamlined approach might look like this:
bytes = AddressBook.CreateBuilder().AddPerson(copy).Build().ToByteArray();
//And read the address book back again
AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build();
//The message performs a deep-comparison on equality:
if(restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
throw new ApplicationException("There is a bad person in here!");
}
}
}
Loading…
Cancel
Save