Merge pull request #2 from jtattermusch/csharp_protobuf_imported

Pulling protobuf-csharp-port into csharp/ directory
pull/288/head
Jan Tattermusch 10 years ago
commit 01c8c35ca3
  1. 43
      csharp/.gitignore
  2. 148
      csharp/CHANGES.txt
  3. 17
      csharp/README.md
  4. 8
      csharp/build/BuildAll.bat
  5. 122
      csharp/build/Common.targets
  6. 59
      csharp/build/Google.ProtocolBuffers.nuspec
  7. 60
      csharp/build/Google.ProtocolBuffersLite.nuspec
  8. 2
      csharp/build/RunBenchmarks.bat
  9. 20
      csharp/build/build.bat
  10. 241
      csharp/build/build.csproj
  11. 248
      csharp/build/googlecode_upload.py
  12. 79
      csharp/build/nuspec.xsd
  13. 186
      csharp/build/publish.csproj
  14. 167
      csharp/build/target.csproj
  15. 41
      csharp/csproj_templates/CF20.csproj
  16. 44
      csharp/csproj_templates/CF35.csproj
  17. 17
      csharp/csproj_templates/NET20.csproj
  18. 20
      csharp/csproj_templates/NET35.csproj
  19. 20
      csharp/csproj_templates/NET40.csproj
  20. 51
      csharp/csproj_templates/PL40.csproj
  21. 44
      csharp/csproj_templates/SL20.csproj
  22. 47
      csharp/csproj_templates/SL30.csproj
  23. 48
      csharp/csproj_templates/SL40.csproj
  24. 34
      csharp/csproj_templates/SLTest.targets
  25. BIN
      csharp/keys/Google.ProtocolBuffers.snk
  26. 13
      csharp/keys/generate_new_key.bat
  27. 54
      csharp/lib/NUnit-config/Microsoft.VisualStudio.TestTools.cs
  28. 18
      csharp/lib/NUnit-config/nunit-console.v2.0.config
  29. 18
      csharp/lib/NUnit-config/nunit-console.v3.5.config
  30. 18
      csharp/lib/NUnit-config/nunit-console.v4.0.config
  31. 13
      csharp/lib/README.md
  32. 37
      csharp/mono/buildall.sh
  33. 29
      csharp/mono/generatesource.sh
  34. 91
      csharp/mono/readme.txt
  35. 140
      csharp/protos/benchmarks/google_size.proto
  36. 140
      csharp/protos/benchmarks/google_speed.proto
  37. 37
      csharp/protos/extest/unittest_extras.proto
  38. 72
      csharp/protos/extest/unittest_extras_full.proto
  39. 117
      csharp/protos/extest/unittest_extras_lite.proto
  40. 54
      csharp/protos/extest/unittest_extras_xmltest.proto
  41. 29
      csharp/protos/extest/unittest_generic_services.proto
  42. 137
      csharp/protos/extest/unittest_issues.proto
  43. 41
      csharp/protos/extest/unittest_rpc_interop.proto
  44. 42
      csharp/protos/extest/unittest_rpc_interop_lite.proto
  45. 147
      csharp/protos/google/protobuf/compiler/plugin.proto
  46. 115
      csharp/protos/google/protobuf/csharp_options.proto
  47. 533
      csharp/protos/google/protobuf/descriptor.proto
  48. 636
      csharp/protos/google/protobuf/unittest.proto
  49. 52
      csharp/protos/google/protobuf/unittest_csharp_options.proto
  50. 372
      csharp/protos/google/protobuf/unittest_custom_options.proto
  51. 56
      csharp/protos/google/protobuf/unittest_embed_optimize_for.proto
  52. 43
      csharp/protos/google/protobuf/unittest_empty.proto
  53. 1052
      csharp/protos/google/protobuf/unittest_enormous_descriptor.proto
  54. 67
      csharp/protos/google/protobuf/unittest_import.proto
  55. 55
      csharp/protos/google/protobuf/unittest_import_lite.proto
  56. 318
      csharp/protos/google/protobuf/unittest_lite.proto
  57. 49
      csharp/protos/google/protobuf/unittest_lite_imports_nonlite.proto
  58. 78
      csharp/protos/google/protobuf/unittest_mset.proto
  59. 58
      csharp/protos/google/protobuf/unittest_no_generic_services.proto
  60. 67
      csharp/protos/google/protobuf/unittest_optimize_for.proto
  61. 140
      csharp/protos/google/test/google_size.proto
  62. 140
      csharp/protos/google/test/google_speed.proto
  63. 44
      csharp/protos/npp.language.xml
  64. 31
      csharp/protos/tutorial/addressbook.proto
  65. 136
      csharp/src/AddressBook/AddPerson.cs
  66. 75
      csharp/src/AddressBook/AddressBook.csproj
  67. 1160
      csharp/src/AddressBook/AddressBookProtos.cs
  68. 103
      csharp/src/AddressBook/ListPeople.cs
  69. 99
      csharp/src/AddressBook/Program.cs
  70. 29
      csharp/src/AddressBook/Properties/AssemblyInfo.cs
  71. 44
      csharp/src/AddressBook/SampleUsage.cs
  72. 3
      csharp/src/AddressBook/app.config
  73. 538
      csharp/src/ProtoBench/Program.cs
  74. 32
      csharp/src/ProtoBench/Properties/AssemblyInfo.cs
  75. 88
      csharp/src/ProtoBench/ProtoBench.csproj
  76. 4572
      csharp/src/ProtoBench/TestProtos/GoogleSizeProtoFile.cs
  77. 6637
      csharp/src/ProtoBench/TestProtos/GoogleSpeedProtoFile.cs
  78. 346
      csharp/src/ProtoBench/TestProtos/UnitTestImportProtoFile.cs
  79. 21602
      csharp/src/ProtoBench/TestProtos/UnitTestProtoFile.cs
  80. BIN
      csharp/src/ProtoBench/google_message1.dat
  81. BIN
      csharp/src/ProtoBench/google_message2.dat
  82. 88
      csharp/src/ProtoDump/Program.cs
  83. 30
      csharp/src/ProtoDump/Properties/AssemblyInfo.cs
  84. 65
      csharp/src/ProtoDump/ProtoDump.csproj
  85. 150
      csharp/src/ProtoGen.Test/DependencyResolutionTest.cs
  86. 30
      csharp/src/ProtoGen.Test/Properties/AssemblyInfo.cs
  87. 99
      csharp/src/ProtoGen.Test/ProtoGen.Test.csproj
  88. 683
      csharp/src/ProtoGen.Test/ProtocGenCsUnittests.cs
  89. 59
      csharp/src/ProtoGen.Test/TempFile.cs
  90. 733
      csharp/src/ProtoGen.Test/TestPreprocessing.cs
  91. 101
      csharp/src/ProtoGen.Test/protoc-gen-cs.Test.csproj
  92. 55
      csharp/src/ProtoGen/DependencyResolutionException.cs
  93. 106
      csharp/src/ProtoGen/DescriptorUtil.cs
  94. 148
      csharp/src/ProtoGen/EnumFieldGenerator.cs
  95. 62
      csharp/src/ProtoGen/EnumGenerator.cs
  96. 183
      csharp/src/ProtoGen/ExtensionGenerator.cs
  97. 389
      csharp/src/ProtoGen/FieldGeneratorBase.cs
  98. 267
      csharp/src/ProtoGen/Generator.cs
  99. 330
      csharp/src/ProtoGen/GeneratorOptions.cs
  100. 45
      csharp/src/ProtoGen/Helpers.cs
  101. Some files were not shown because too many files have changed in this diff Show More

43
csharp/.gitignore vendored

@ -0,0 +1,43 @@
#
# Untracked directories
#
src/AddressBook/bin
src/AddressBook/obj
src/ProtocolBuffers/bin/
src/ProtocolBuffers/obj/
src/ProtocolBuffers/objCF
src/ProtocolBuffers.Test/bin/
src/ProtocolBuffers.Test/obj/
src/ProtocolBuffersLite.Test/bin/
src/ProtocolBuffersLite.Test/obj/
src/ProtoBench/bin/
src/ProtoBench/obj/
src/ProtoDump/bin/
src/ProtoDump/obj/
src/ProtoGen/bin/
src/ProtoGen/obj/
src/ProtoGen.Test/bin/
src/ProtoGen.Test/obj/
src/ProtoMunge/bin/
src/ProtoMunge/obj/
mono/bin
mono/tmp
mono/protoc
build_output
build_temp
build/msbuild*.log
lib/Microsoft.Silverlight.Testing
lib/NUnit
#
# Untracked files
#
*.user
*.suo
_ReSharper.*
*.sln.cache
mono/TestResult.xml
mono/.libs
mono/*.exe
mono/*.dll
lib/protoc.exe

@ -0,0 +1,148 @@
===============================================================================
Welcome to the C# port of Google Protocol Buffers, written by Jon Skeet
(skeet@pobox.com) based on the work of many talented people.
===============================================================================
RELEASE NOTES - Code imported into Google's main protobuf repository
===============================================================================
Everything below note this represents history of protobuf-csharp-port project
before the code was merged into csharp/ subtree of GitHub google/protobuf
repository.
Frozen legacy version of the original project is available in
https://github.com/jskeet/protobuf-csharp-port.
===============================================================================
RELEASE NOTES - Version 2.4.1.555
===============================================================================
Changes:
- Upgrade solution format to Visual Studio 2012.
- Add the ability to print a builder (not just a message)
- TextGenerator introduces a new overload of PrintTo
- Munge protoc's error format into a VS-C#-compatible output format.
- Work to make ProtoGen clone that acts as a protoc.exe plugin.
- Added the AllowPartiallyTrustedCallers attribute
- Optimized enum parsing.
Fixes:
- Fix for bug in limited input stream's Position, Introduced Position on
output stream
- Fix for writing a character to a JSON output overflows allocated buffer
- Optimize FromBase64String to return Empty when presented with empty string.
- Use string.Concat instead of operator to avoid potential import problems
- Issue 81: quoting for NUnit parameters.
- Issue 56: NuGet package is noisy
- Issue 70: Portable library project has some invalid Nunit-based code.
- Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
- Issue 84: warning CS0219: The variable `size' is assigned but never used
===============================================================================
RELEASE NOTES - Version 2.4.1.521
===============================================================================
Changes:
- Add generated_code_attributes option, defaulted to false
- Added support for Portable library
- Added 'Unsafe' static type in ByteString to allow direct buffer access
Fixes:
- Issue 50: The XML serializer will fail to deserialize a message with empty
child message
- Issue 45: Use of 'item' as a field name causes AmbiguousMatchException
- Issue 49: Generated nested static Types class should be partial
- Issue 38: Disable CLSCompliant warnings (3021)
- Issue 40: proto_path does not work for command-line file names
- Issue 54: should retire all bytes in buffer (bufferSize)
- Issue 43: Fix to correct identical 'umbrella_classname' options from trying
to write to the same filename.
===============================================================================
RELEASE NOTES - Version 2.4.1.473
===============================================================================
Features:
- Added option service_generator_type to control service generation with
NONE, GENERIC, INTERFACE, or IRPCDISPATCH
- Added interfaces IRpcDispatch and IRpcServerStub to provide for blocking
services and implementations.
- Added ProtoGen.exe command-line argument "--protoc_dir=" to specify the
location of protoc.exe.
- Extracted interfaces for ICodedInputStream and ICodedOutputStream to allow
custom implementation of writers with both speed and size optimizations.
- Addition of the "Google.ProtoBuffers.Serialization" assembly to support
reading and writing messages to/from XML, JSON, IDictionary<,> and others.
- Several performance related fixes and tweeks
- Issue 3: Add option to mark generated code with attribute
- Issue 20: Support for decorating classes [Serializable]
- Issue 21: Decorate fields with [deprecated=true] as [System.Obsolete]
- Issue 22: Reusable Builder classes
- Issue 24: Support for using Json/Xml formats with ICodedInputStream
- Issue 25: Added support for NuGet packages
- Issue 31: Upgraded protoc.exe and descriptor to 2.4.1
Fixes:
- Issue 13: Message with Field same name as message causes uncompilable .cs
- Issue 16: Does not integrate well with other tooling
- Issue 19: Support for negative enum values
- Issue 26: AddRange in GeneratedBuilder iterates twice.
- Issue 27: Remove XML documentation output from test projects to clear
warnings/errors.
- Issue 28: Circular message dependencies result in null default values for
Message fields.
- Issue 29: Message classes generated have a public default constructor. You
can disable private ctor generation with the option generate_private_ctor.
- Issue 35: Fixed a bug in ProtoGen handling of arguments with trailing \
- Big-endian support for float, and double on Silverlight
- Packed and Unpacked parsing allow for all repeated, as per version 2.3
- Fix for leaving Builder a public ctor on internal classes for use with
generic "where T: new()" constraints.
Other:
- Changed the code signing key to a privately held key
- Reformatted all code and line-endings to C# defaults
- Reworking of performance benchmarks to produce reliable results, option /v2
- Issue 34: Silverlight assemblies are now unit tested
===============================================================================
RELEASE NOTES - Version 2.3.0.277
===============================================================================
Features:
- Added cls_compliance option to generate attributes indicating
non-CLS-compliance.
- Added file_extension option to control the generated output file's extension.
- Added umbrella_namespace option to place the umbrella class into a nested
namespace to address issues with proto files having the same name as a
message it contains.
- Added output_directory option to set the output path for the source file(s).
- Added ignore_google_protobuf option to avoid generating code for includes
from the google.protobuf package.
- Added the LITE framework (Google.ProtoBuffersLite.dll) and the ability to
generate code with "option optimize_for = LITE_RUNTIME;".
- Added ability to invoke protoc.exe from within ProtoGen.exe.
- Upgraded to protoc.exe (2.3) compiler.
Fixes:
- Issue 9: Class cannot be static and sealed error
- Issue 12: default value for enumerate fields must be filled out
Other:
- Rewrite of build using MSBbuild instead of NAnt
- Moved to NUnit Version 2.2.8.0
- Changed to using secure .snk for releases
===============================================================================
RELEASE NOTES - Version 0.9.1
===============================================================================
Fixes:
- issue 10: Incorrect encoding of packed fields when serialized
===============================================================================
RELEASE NOTES - Version 0.9.0
===============================================================================
- Initial release
===============================================================================

@ -0,0 +1,17 @@
This directory contains a library that implements Protocol Buffers
functionality in C#.
Experimental only
-----------------
C# protobufs are currently under development and are not officially supported yet.
Also, as of now, only proto2 is supported. Proto3 support for C# is currently in progress
(both design & implementation).
History of C# protobufs
-----------------------
This subtree was originally imported from https://github.com/jskeet/protobuf-csharp-port
and represents the latest development version of C# protobufs, that will now be developed
and maintained by Google. All the development will be done in open, under this repository
(https://github.com/google/protobuf).

@ -0,0 +1,8 @@
@echo off
SET BUILD_TARGET=%~1
SET BUILD_CONFIG=%~2
IF "%BUILD_TARGET%"=="" SET BUILD_TARGET=Rebuild
IF "%BUILD_CONFIG%"=="" SET BUILD_CONFIG=Debug
CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo build.csproj /t:%BUILD_TARGET% /toolsversion:4.0 "/p:Configuration=%BUILD_CONFIG%" %3 %4 %5 %6

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- **********************************************************************************************
Targets For Clean
*********************************************************************************************** -->
<Target Name="_CleanFolder">
<Message Importance="normal" Text="Removing temporary directory '$(CleanFolderDirectory)'"/>
<Error Text="Can not remove empty directory name." Condition=" '$(CleanFolderDirectory)' == '' " />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)" Condition="Exists($(CleanFolderDirectory))" Outputs="@(Ignore)"
Command="MOVE /Y &quot;$(CleanFolderDirectory)&quot; &quot;$(CleanFolderDirectory)-deleted&quot; > NUL" />
<RemoveDir Directories="$(CleanFolderDirectory)-deleted" Condition="Exists('$(CleanFolderDirectory)-deleted')" />
</Target>
<Target Name="_CleanTempOutput">
<MSBuild Projects="$(MSBuildProjectFullPath)" Properties="CleanFolderDirectory=%(TempBuildFolder.Identity);" Targets="_CleanFolder" />
</Target>
<Target Name="_CleanAll" DependsOnTargets="_CleanTempOutput">
<MakeDir Directories="$(BuildTempDirectory)" />
<MakeDir Directories="$(BuildOutputDirectory)" />
</Target>
<!-- **********************************************************************************************
Targets For Build
*********************************************************************************************** -->
<Target Name="_CompileAll">
<MSBuild Projects="$(MSBuildProjectFullPath)" Properties="SolutionTarget=Rebuild;" Targets="_BuildAllConfigurations" />
</Target>
<Target Name="_BuildAllConfigurations">
<MSBuild Properties="TargetVersion=cf20;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=cf35;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=net20;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=net35;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=net40;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=sl20;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=sl30;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=sl40;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="TargetVersion=pl40;Configuration=$(Configuration);Platform=$(Platform);" Targets="$(SolutionTarget)" Projects="$(MSBuildProjectDirectory)\target.csproj" />
</Target>
<!-- **********************************************************************************************
Targets For Tools
*********************************************************************************************** -->
<Target Name="_BuildTools">
<MSBuild Targets="Build" ToolsVersion="3.5" Projects="$(ProjectDirectory)\src\ProtocolBuffers.sln" Properties="Configuration=Release;Platform=Any CPU;" />
<Copy SourceFiles="%(ToolsOutputItem.Identity)" DestinationFolder="$(BuildOutputDirectory)\tools" />
<Copy SourceFiles="$(LibDirectory)\NUnit-config\nunit-console.v2.0.config" DestinationFiles="$(NUnitExePath).config" />
<Exec
WorkingDirectory="%(ToolsTestContainer.RootDir)%(ToolsTestContainer.Directory)"
Command="&quot;$(NUnitExePath)&quot; /nologo /noshadow &quot;%(ToolsTestContainer.Identity)&quot; /xml:&quot;$(BuildTempDirectory)\%(ToolsTestContainer.Filename).xml&quot;" />
</Target>
<!-- **********************************************************************************************
Targets For GenerateSource
*********************************************************************************************** -->
<Target Name="_GenerateProjects">
<Exec Command="&quot;$(CsProjectProjector)&quot; csproj_templates src\ProtocolBuffersLibrary.sln" WorkingDirectory="$(ProjectDirectory)" />
</Target>
<Target Name="_CleanTempSource">
<MSBuild Projects="$(MSBuildProjectFullPath)" Properties="CleanFolderDirectory=$(SourceTempDirectory);" Targets="_CleanFolder" />
<MakeDir Directories="$(SourceTempDirectory)" />
</Target>
<Target Name="_GenerateSource" DependsOnTargets="_CleanTempSource">
<Message Importance="high" Text="Generating source from proto files" />
<Exec Command="&quot;$(ProtocExePath)&quot; --proto_path=$(ProtosDirectory) --descriptor_set_out=compiled.pb @(Protos->'%(RelativeDir)%(Filename)%(Extension)', ' ')" WorkingDirectory="$(SourceTempDirectory)" />
<Exec Command="&quot;$(ProtogenExePath)&quot; compiled.pb" WorkingDirectory="$(SourceTempDirectory)" />
</Target>
<Target Name="_CopyGeneratedSource" DependsOnTargets="_GenerateSource">
<Copy SourceFiles="%(GeneratedSource.Identity)" DestinationFiles="%(GeneratedSource.TargetDirectory)\%(GeneratedSource.Filename)%(GeneratedSource.Extension)" />
</Target>
<!-- **********************************************************************************************
Targets For Package
*********************************************************************************************** -->
<Target Name="_PackageAll">
<MSBuild Projects="$(MSBuildProjectFullPath)" Properties="SolutionTarget=_Publish;" Targets="_BuildAllConfigurations" />
</Target>
<Target Name="_GeneratePackage">
<Copy SourceFiles="@(StaticPackageItem)" DestinationFolder="$(BuildOutputPackage)\%(StaticPackageItem.TargetDirectory)\%(StaticPackageItem.RecursiveDir)" />
<Exec Command="&quot;$(ZipExePath)&quot; a -tzip $(BuildTempDirectory)\$(PackageName)-binaries.zip * -x!*.pdb -r" WorkingDirectory="$(BuildOutputPackage)" />
<Exec Command="&quot;$(ZipExePath)&quot; a -tzip $(BuildTempDirectory)\$(PackageName)-symbols.zip * -r" WorkingDirectory="$(BuildOutputPackage)" />
</Target>
<!-- **********************************************************************************************
Targets For Benchmark
*********************************************************************************************** -->
<Target Name="_RunBenchmarks">
<ItemGroup>
<BenchmarkParameter Include="Google.ProtocolBuffers.ProtoBench.SizeMessage1,ProtoBench" />
<BenchmarkParameter Include="google_message1.dat" />
<BenchmarkParameter Include="Google.ProtocolBuffers.ProtoBench.SpeedMessage1,ProtoBench" />
<BenchmarkParameter Include="google_message1.dat" />
<BenchmarkParameter Include="Google.ProtocolBuffers.ProtoBench.SizeMessage2,ProtoBench" />
<BenchmarkParameter Include="google_message2.dat" />
<BenchmarkParameter Include="Google.ProtocolBuffers.ProtoBench.SpeedMessage2,ProtoBench" />
<BenchmarkParameter Include="google_message2.dat" />
</ItemGroup>
<Message Text="Running ProtoBench.exe" />
<Exec Command="ProtoBench.exe $(BenchmarkArgs) @(BenchmarkParameter->'%(Identity)', ' ') &quot;/log:$(BenchmarkOutputFile)&quot;"
WorkingDirectory="$(SourceDirectory)\ProtoBench\bin\NET35\Release" />
</Target>
</Project>

@ -0,0 +1,59 @@
<?xml version="1.0"?>
<package xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="nuspec.xsd">
<metadata>
<id>Google.ProtocolBuffers</id>
<version>$version$</version>
<owners>Jon Skeet</owners>
<authors>Jon Skeet</authors>
<licenseUrl>http://code.google.com/p/protobuf-csharp-port/source/browse/license.txt</licenseUrl>
<projectUrl>http://code.google.com/p/protobuf-csharp-port/</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<copyright>Copyright 2008 Google Inc. All rights reserved.</copyright>
<tags>Protocol Buffers Binary Serialization Format Google</tags>
<title>Google.ProtocolBuffers</title>
<summary>A managed code generator and library for Google's data interchange format.</summary>
<description><![CDATA[
Protocol Buffers is a binary serialization format and technology, released to the open source community by Google in 2008.
Its primary use is to produce small fast binary representations of a 'message' or object for serialization or transportation.
There are various implementations of Protocol Buffers in .NET. This project is a fairly close port of the Google Java implementation.
There are two main parts:
tools/protoc.exe, which takes the textual representation of the protocol buffer and turns it into a binary representation for use with ProtoGen.exe.
tools/ProtoGen.exe, which takes binary representations of protocol buffer descriptors (as generated by the "stock" protoc binary supplied by Google) and creates C# source code. This is only required at build time.
lib/*/Google.ProtocolBuffers.dll, which is a supporting library. This is required at execution time.
lib/*/Google.ProtocolBuffers.Serialization.dll, a supplementary library that provides extensions for reading and writing protocol buffers to xml, json, and others.
LINKS:
Project Home - http://code.google.com/p/protobuf-csharp-port
Online Help - http://help.protobuffers.net
Developer Guide - http://code.google.com/apis/protocolbuffers/docs/overview.html
Language Guide - http://code.google.com/apis/protocolbuffers/docs/proto.html
]]></description>
<references>
<reference file="Google.ProtocolBuffers.dll"/>
<reference file="Google.ProtocolBuffers.Serialization.dll"/>
</references>
</metadata>
<files>
<!-- Release Binaries -->
<file src="..\build_output\Release\**\Google.ProtocolBuffers.???" target="lib\" />
<file src="..\build_output\Release\**\Google.ProtocolBuffers.Serialization.???" target="lib\" />
<!-- Tools -->
<file src="..\build_output\tools\**\*" target="tools\" />
<file src="..\build_output\protos\**\*" target="tools\" />
<!-- Content -->
<file src="..\build_output\CHANGES.txt" target="tools\"/>
<file src="..\build_output\license.txt" target="tools\"/>
<file src="..\build_output\tools\protoc-license.txt" target="tools\"/>
<!-- Source -->
<file src="..\src\ProtocolBuffers\**\*.cs" target="src\ProtocolBuffers\"/>
<file src="..\src\ProtocolBuffers.Serialization\**\*.cs" target="src\ProtocolBuffers.Serialization\"/>
</files>
</package>

@ -0,0 +1,60 @@
<?xml version="1.0"?>
<package xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="nuspec.xsd">
<metadata>
<id>Google.ProtocolBuffersLite</id>
<version>$version$</version>
<owners>Jon Skeet</owners>
<authors>Jon Skeet</authors>
<licenseUrl>http://code.google.com/p/protobuf-csharp-port/source/browse/license.txt</licenseUrl>
<projectUrl>http://code.google.com/p/protobuf-csharp-port/</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<copyright>Copyright 2008 Google Inc. All rights reserved.</copyright>
<tags>Protocol Buffers Binary Serialization Format Google</tags>
<title>Google.ProtocolBuffersLite</title>
<summary>A managed code generator and library for Google's data interchange format.</summary>
<description><![CDATA[
Protocol Buffers is a binary serialization format and technology, released to the open source community by Google in 2008.
Its primary use is to produce small fast binary representations of a 'message' or object for serialization or transportation.
There are various implementations of Protocol Buffers in .NET. This project is a fairly close port of the Google Java implementation.
There are two main parts:
tools/protoc.exe, which takes the textual representation of the protocol buffer and turns it into a binary representation for use with ProtoGen.exe.
tools/ProtoGen.exe, which takes binary representations of protocol buffer descriptors (as generated by the "stock" protoc binary supplied by Google) and creates C# source code. This is only required at build time.
lib/*/Google.ProtocolBuffersLite.dll, which is a supporting library. This is required at execution time.
lib/*/Google.ProtocolBuffersLite.Serialization.dll, a supplementary library that provides extensions for reading and writing protocol buffers to xml, json, and others.
LINKS:
Project Home - http://code.google.com/p/protobuf-csharp-port
Online Help - http://help.protobuffers.net
Developer Guide - http://code.google.com/apis/protocolbuffers/docs/overview.html
Language Guide - http://code.google.com/apis/protocolbuffers/docs/proto.html
]]></description>
<references>
<reference file="Google.ProtocolBuffersLite.dll"/>
<reference file="Google.ProtocolBuffersLite.Serialization.dll"/>
</references>
</metadata>
<files>
<!-- Release Binaries -->
<file src="..\build_output\Release\**\Google.ProtocolBuffersLite.???" target="lib\" />
<file src="..\build_output\Release\**\Google.ProtocolBuffersLite.Serialization.???" target="lib\" />
<!-- Tools -->
<file src="..\build_output\tools\**\*" target="tools\" />
<file src="..\build_output\protos\**\*" target="tools\" />
<!-- Content -->
<file src="..\build_output\CHANGES.txt" target="tools\"/>
<file src="..\build_output\license.txt" target="tools\"/>
<file src="..\build_output\tools\protoc-license.txt" target="tools\"/>
<!-- Source -->
<file src="..\src\ProtocolBuffers\**\*.cs" target="src\ProtocolBuffers\"/>
<file src="..\src\ProtocolBuffers.Serialization\**\*.cs" target="src\ProtocolBuffers.Serialization\"/>
</files>
</package>

@ -0,0 +1,2 @@
@echo off
CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo build.csproj /toolsversion:4.0 /t:RunBenchmarks %1 %2 %3 %4

@ -0,0 +1,20 @@
@echo off
SET BUILD_VERSION=%~1
SET BUILD_TARGET=%~2
SET BUILD_CONFIG=%~3
IF NOT "%BUILD_VERSION%"=="" GOTO RUN
ECHO.
ECHO Usage: build.bat platform [target] [config] [msbuild arguments]
ECHO.
ECHO - platform: CF20, CF35, NET20, NET35, NET40, PL40, SL20, SL30, or SL40
ECHO - [target]: Rebuild, Clean, Build, Test, or Publish
ECHO - [config]: Debug or Release
ECHO.
EXIT /B 1
:RUN
IF "%BUILD_TARGET%"=="" SET BUILD_TARGET=Rebuild
IF "%BUILD_CONFIG%"=="" SET BUILD_CONFIG=Debug
CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo target.csproj /toolsversion:4.0 %4 %5 %6 "/t:%BUILD_TARGET%" "/p:Configuration=%BUILD_CONFIG%;TargetVersion=%BUILD_VERSION%"

@ -0,0 +1,241 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- build targets -->
<Target Name="Clean" DependsOnTargets="_CleanAll" />
<Target Name="BuildTools" DependsOnTargets="_BuildTools" />
<Target Name="GenerateProjects" DependsOnTargets="_GenerateProjects" />
<Target Name="GenerateSource" DependsOnTargets="_GenerateSource;_CopyGeneratedSource" />
<Target Name="RebuildSource" DependsOnTargets="Clean;BuildTools;GenerateSource" />
<Target Name="Build" DependsOnTargets="GenerateProjects;BuildTools;GenerateSource;_CompileAll" />
<Target Name="Rebuild" DependsOnTargets="Clean;Build" />
<Target Name="GeneratePackage" DependsOnTargets="_PackageAll;_GeneratePackage" />
<Target Name="FullBuild" DependsOnTargets="Rebuild;GeneratePackage" />
<!-- misc targets -->
<Target Name="RunBenchmarks" DependsOnTargets="_CleanAll;_BuildTools;_RunBenchmarks" />
<PropertyGroup>
<ProjectName>Protocol Buffers</ProjectName>
<Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
<Platform Condition=" '$(Platform)' == '' ">Any CPU</Platform>
<!--Directory Paths-->
<ProjectDirectory>$(MSBuildProjectDirectory)\..</ProjectDirectory>
<SourceDirectory>$(ProjectDirectory)\src</SourceDirectory>
<LibDirectory>$(ProjectDirectory)\lib</LibDirectory>
<ProtosDirectory>$(ProjectDirectory)\protos</ProtosDirectory>
<SourceTempDirectory>$(ProjectDirectory)\build_temp\GeneratedSource</SourceTempDirectory>
<BuildTempDirectory>$(ProjectDirectory)\build_temp</BuildTempDirectory>
<BuildOutputDirectory>$(ProjectDirectory)\build_output</BuildOutputDirectory>
<BuildOutputPackage>$(BuildOutputDirectory)</BuildOutputPackage>
<BenchmarkArgs>/v2 /fast /formats</BenchmarkArgs>
<BenchmarkOutputFile>$(BuildTempDirectory)\..\BenchmarkResults.txt</BenchmarkOutputFile>
<BenchmarkProtosDirectory>$(ProjectDirectory)\benchmarks</BenchmarkProtosDirectory>
<PackageName Condition=" '$(PackageName)' == '' ">$(Configuration)</PackageName>
<!--Tool Paths-->
<ProtocExePath>$(BuildOutputDirectory)\tools\protoc.exe</ProtocExePath>
<ProtogenExePath>$(BuildOutputDirectory)\tools\protogen.exe</ProtogenExePath>
<NUnitExePath>$(LibDirectory)\NUnit\tools\nunit-console.exe</NUnitExePath>
<CsProjectProjector>$(LibDirectory)\CsProjectProjector\CsProjectProjector.exe</CsProjectProjector>
<ZipExePath>$(LibDirectory)\7-Zip 9.20\7za.exe</ZipExePath>
</PropertyGroup>
<Import Project="Common.targets"/>
<!-- Proto Files -->
<ItemGroup>
<Protos Include="$(ProtosDirectory)\extest\unittest_issues.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_extras.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_extras_full.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_extras_lite.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_extras_xmltest.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_generic_services.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_rpc_interop.proto" />
<Protos Include="$(ProtosDirectory)\extest\unittest_rpc_interop_lite.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\descriptor.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\csharp_options.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_csharp_options.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_custom_options.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_embed_optimize_for.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_empty.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_import.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_import_lite.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_lite.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_lite_imports_nonlite.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_mset.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_no_generic_services.proto" />
<Protos Include="$(ProtosDirectory)\google\protobuf\unittest_optimize_for.proto" />
<Protos Include="$(ProtosDirectory)\google\test\google_size.proto" />
<Protos Include="$(ProtosDirectory)\google\test\google_speed.proto" />
<Protos Include="$(ProtosDirectory)\tutorial\addressbook.proto" />
<!-- for benchmark -->
<Protos Include="$(ProtosDirectory)\benchmarks\google_size.proto" />
<Protos Include="$(ProtosDirectory)\benchmarks\google_speed.proto" />
</ItemGroup>
<!-- Generated Source -->
<ItemGroup>
<!-- Main protos -->
<GeneratedSource Include="$(SourceTempDirectory)\CSharpOptions.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers\DescriptorProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\DescriptorProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers\DescriptorProtos</TargetDirectory>
</GeneratedSource>
<!-- Address book sample -->
<GeneratedSource Include="$(SourceTempDirectory)\AddressBookProtos.cs">
<TargetDirectory>$(SourceDirectory)\AddressBook</TargetDirectory>
</GeneratedSource>
<!-- Unit test -->
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestExtrasProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestExtrasIssuesProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestXmlSerializerTestProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestCSharpOptionsProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestCustomOptionsProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestEmbedOptimizeForProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestEmptyProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestImportLiteProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestImportProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestMessageSetProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestNoGenericServicesProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestOptimizeForProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestRpcInterop.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestRpcInteropLite.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestGenericServices.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<!-- Lite unit test -->
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestExtrasFullProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestExtrasLiteProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestImportLiteProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestImportProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestLiteImportNonLiteProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestLiteProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestGoogleSizeProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestGoogleSpeedProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtocolBuffers.Test\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\GoogleSizeProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtoBench\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\GoogleSpeedProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtoBench\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestImportProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtoBench\TestProtos</TargetDirectory>
</GeneratedSource>
<GeneratedSource Include="$(SourceTempDirectory)\UnitTestProtoFile.cs">
<TargetDirectory>$(SourceDirectory)\ProtoBench\TestProtos</TargetDirectory>
</GeneratedSource>
</ItemGroup>
<!-- Package Items -->
<ItemGroup>
<StaticPackageItem Include="$(ProjectDirectory)\CHANGES.txt" />
<StaticPackageItem Include="$(ProjectDirectory)\license.txt" />
<StaticPackageItem Include="$(ProjectDirectory)\protos\google\protobuf\descriptor.proto">
<TargetDirectory>\protos\google\protobuf</TargetDirectory>
</StaticPackageItem>
<StaticPackageItem Include="$(ProjectDirectory)\protos\google\protobuf\compiler\plugin.proto">
<TargetDirectory>\protos\google\protobuf\compiler</TargetDirectory>
</StaticPackageItem>
<StaticPackageItem Include="$(ProjectDirectory)\protos\google\protobuf\csharp_options.proto">
<TargetDirectory>\protos\google\protobuf</TargetDirectory>
</StaticPackageItem>
<StaticPackageItem Include="$(ProjectDirectory)\protos\tutorial\addressbook.proto">
<TargetDirectory>\protos\tutorial</TargetDirectory>
</StaticPackageItem>
</ItemGroup>
<!-- Tools -->
<ItemGroup>
<ToolsTestContainer Include="$(SourceDirectory)\ProtoGen.Test\bin\NET35\Release\Google.ProtocolBuffers.ProtoGen.Test.dll" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtocolBuffers\bin\NET35\Release\Google.ProtocolBuffers.dll" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\NET35\Release\Google.ProtocolBuffers.Serialization.dll" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtoGen\bin\NET35\Release\ProtoGen.exe" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtoGen\bin\NET35\Release\ProtoGen.exe.config" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtoMunge\bin\NET35\Release\ProtoMunge.exe" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtoDump\bin\NET35\Release\ProtoDump.exe" />
<ToolsOutputItem Include="$(SourceDirectory)\ProtoBench\bin\NET35\Release\ProtoBench.exe" />
<ToolsOutputItem Include="$(LibDirectory)\protoc.exe" />
<ToolsOutputItem Include="$(LibDirectory)\protoc-license.txt" />
</ItemGroup>
<!-- Temporary Directories -->
<ItemGroup>
<TempBuildFolder Include="$(BuildTempDirectory)" />
<TempBuildFolder Include="$(BuildOutputDirectory)" />
<TempBuildFolder Include="$(SourceDirectory)\AddressBook\obj" />
<TempBuildFolder Include="$(SourceDirectory)\AddressBook\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoBench\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoBench\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers.Serialization\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers.Test\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffers.Test\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffersLite.Test\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtocolBuffersLite.Test\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoDump\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoDump\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoGen\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoGen\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoGen.Test\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoGen.Test\bin" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoMunge\obj" />
<TempBuildFolder Include="$(SourceDirectory)\ProtoMunge\bin" />
</ItemGroup>
</Project>

@ -0,0 +1,248 @@
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- original location: https://hg01.codeplex.com/nuget/raw-file/tip/src/Core/Authoring/nuspec.xsd -->
<xs:schema id="nuspec" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="package">
<xs:complexType>
<xs:sequence>
<xs:element name="metadata" maxOccurs="1" minOccurs="1">
<xs:complexType>
<xs:all>
<xs:element name="id" maxOccurs="1" minOccurs="1" type="xs:string" />
<xs:element name="version" maxOccurs="1" minOccurs="1" type="xs:string" />
<xs:element name="title" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="authors" maxOccurs="1" minOccurs="1" type="xs:string" />
<xs:element name="owners" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="licenseUrl" maxOccurs="1" minOccurs="0" type="xs:anyURI" />
<xs:element name="projectUrl" maxOccurs="1" minOccurs="0" type="xs:anyURI" />
<xs:element name="iconUrl" maxOccurs="1" minOccurs="0" type="xs:anyURI" />
<xs:element name="requireLicenseAcceptance" maxOccurs="1" minOccurs="0" type="xs:boolean" />
<xs:element name="description" maxOccurs="1" minOccurs="1" type="xs:string" />
<xs:element name="summary" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="releaseNotes" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="copyright" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="language" maxOccurs="1" minOccurs="0" type="xs:string" default="en-US" />
<xs:element name="tags" maxOccurs="1" minOccurs="0" type="xs:string" />
<xs:element name="dependencies" maxOccurs="1" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="dependency" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="frameworkAssemblies" maxOccurs="1" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="frameworkAssembly" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="assemblyName" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="references" maxOccurs="1" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="reference" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="file" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
<xs:element name="files" minOccurs="0" maxOccurs="1" nillable="true">
<xs:complexType>
<xs:sequence>
<xs:element name="file" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="src" use="required" type="xs:string" />
<xs:attribute name="target" use="optional" type="xs:string" />
<xs:attribute name="exclude" use="optional" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

@ -0,0 +1,186 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Publish" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- build targets -->
<Target Name="Clean" DependsOnTargets="_Clean" />
<Target Name="Build" DependsOnTargets="_Clean;_Prerequisites;_StampVersion;_GenerateSource;_Build" />
<Target Name="Label" DependsOnTargets="_HgLabel" />
<Target Name="Package" DependsOnTargets="_HgPack;_NugetPack" />
<Target Name="Prepare" DependsOnTargets="Clean;Build;Label;Package" />
<Target Name="PushAll" DependsOnTargets="_HgPush;_NugetPush" />
<Target Name="Publish" DependsOnTargets="Prepare;PushAll" />
<PropertyGroup>
<ProjectName>Protocol Buffers</ProjectName>
<VersionMajor>2</VersionMajor>
<VersionMinor>4</VersionMinor>
<VersionBuild>1</VersionBuild>
<VersionRevision></VersionRevision>
<VersionLabel></VersionLabel>
<PackagePrefix>protobuf-csharp-port-</PackagePrefix>
<PublishDebug>false</PublishDebug>
<GoogleUsername></GoogleUsername>
<GooglePassword></GooglePassword>
<!--Directory Paths-->
<ProjectDirectory>$(MSBuildProjectDirectory)\..</ProjectDirectory>
<BuildTempDirectory>$(ProjectDirectory)\build_temp</BuildTempDirectory>
<BuildOutputDirectory>$(ProjectDirectory)\build_output</BuildOutputDirectory>
<SourceDirectory>$(ProjectDirectory)\src</SourceDirectory>
<LibDirectory>$(ProjectDirectory)\lib</LibDirectory>
<!-- File Paths -->
<SigningKey>$(ProjectDirectory)\release-key\Google.ProtocolBuffers.snk</SigningKey>
<!--Tool Paths-->
<HgTool>hg.exe</HgTool>
<Python>C:\Python25\python.exe</Python>
<SnTool>$(registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A@InstallationFolder)Bin\sn.exe</SnTool>
<StampVer>$(LibDirectory)\StampVersion.exe</StampVer>
<ZipExePath>$(LibDirectory)\7-Zip 9.20\7za.exe</ZipExePath>
<NuGet>$(LibDirectory)\NuGet.exe</NuGet>
<ProtogenExePath>$(BuildOutputDirectory)\tools\protogen.exe</ProtogenExePath>
</PropertyGroup>
<!-- Import user settings -->
<Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')" />
<!-- Files -->
<ItemGroup>
</ItemGroup>
<!-- Tasks -->
<Target Name="_Prerequisites" DependsOnTargets="_CheckEnvironment;_ReadVersion" />
<Target Name="_Clean">
<MSBuild Properties="Configuration=Debug;" Targets="Clean" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MSBuild Properties="Configuration=Release;" Targets="Clean" Projects="$(MSBuildProjectDirectory)\target.csproj" />
<MakeDir Directories="$(BuildTempDirectory)" />
<MakeDir Directories="$(BuildOutputDirectory)" />
</Target>
<Target Name="_WriteUserConfig">
<ItemGroup>
<Lines Include="&lt;Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>" />
<Lines Include=" &lt;PropertyGroup>"/>
<Lines Include=" &lt;GoogleUsername> (Enter your google-code user/password here) &lt;/GoogleUsername>"/>
<Lines Include=" &lt;GooglePassword>&lt;/GooglePassword>"/>
<Lines Include=" &lt;/PropertyGroup>" />
<Lines Include="&lt;/Project>" />
</ItemGroup>
<WriteLinesToFile File="$(MSBuildProjectFullPath).user" Lines="@(Lines)" Overwrite="true" Condition="!Exists('$(MSBuildProjectFullPath).user')" />
<Exec Command="Notepad.exe $(MSBuildProjectFullPath).user" />
</Target>
<Target Name="_CheckEnvironment">
<!-- Require google credentials -->
<CallTarget Targets="_WriteUserConfig" Condition=" '$(GooglePassword)' == '' " />
<Error Text="Restart after you verify your credentials in $(MSBuildProjectFullPath).user" Condition=" '$(GooglePassword)' == '' " />
<!-- Require Win7.0A SDK to verify strong-name -->
<Error Text="Unable to locate Win7SDK Tools: $(SnTool)" Condition="!Exists($(SnTool))" />
<!-- Require Python 2.5 installed -->
<!-- Error Text="Unable to locate Python 2.5: $(Python)" Condition="!Exists($(Python))" / -->
<!-- Require production signing key -->
<Exec Command="$(HgTool) clone https://bitbucket.org/rknapp/protobuf-csharp-port-keyfile $(ProjectDirectory)\release-key" Condition="!Exists('$(SigningKey)')" />
<Error Text="Unable to locate release signing key: $(SigningKey)" Condition="!Exists($(SigningKey))" />
</Target>
<Target Name="_ReadVersion" Condition=" '$(VersionLabel)' == '' ">
<Exec Command="$(HgTool) log -l 1 --template &quot;{rev}&quot; > &quot;$(BuildTempDirectory)\revision.txt&quot;"></Exec>
<ReadLinesFromFile File="$(BuildTempDirectory)\revision.txt">
<Output TaskParameter="Lines" PropertyName="VersionRevision"/>
</ReadLinesFromFile>
<PropertyGroup>
<VersionLabel>$(VersionMajor).$(VersionMinor).$(VersionBuild).$(VersionRevision)</VersionLabel>
</PropertyGroup>
<Message Text="Building version $(VersionLabel)" Importance="high" />
</Target>
<Target Name="_StampVersion" DependsOnTargets="_Prerequisites">
<Exec Command="$(StampVer) /major:$(VersionMajor) /minor:$(VersionMinor) /build:$(VersionBuild) /revision:$(VersionRevision)" WorkingDirectory="$(SourceDirectory)" />
<Exec Command="FIND &quot;$(VersionLabel)&quot; ProtocolBuffers\Properties\AssemblyInfo.cs" WorkingDirectory="$(SourceDirectory)" />
</Target>
<Target Name="_GenerateSource" DependsOnTargets="_Prerequisites">
<MSBuild Properties="Configuration=Release;AssemblyOriginatorKeyFile=$(SigningKey)" Targets="GenerateProjects;BuildTools;GenerateSource" Projects="$(MSBuildProjectDirectory)\build.csproj" />
<Exec Command="&quot;$(SnTool)&quot; -T &quot;$(ProtogenExePath)&quot; > signkey.txt" WorkingDirectory="$(BuildTempDirectory)" />
<!-- Make sure we are signing with the correct key -->
<Exec Command="FIND &quot;55f7125234beb589&quot; signkey.txt" WorkingDirectory="$(BuildTempDirectory)" />
</Target>
<Target Name="_Build" DependsOnTargets="_Prerequisites">
<!-- Release Build -->
<MSBuild Properties="Configuration=Release;AssemblyOriginatorKeyFile=$(SigningKey)" Targets="_CompileAll" Projects="$(MSBuildProjectDirectory)\build.csproj" />
<MSBuild Properties="Configuration=Release;AssemblyOriginatorKeyFile=$(SigningKey);PackageName=$(PackagePrefix)$(VersionLabel)-release" Targets="GeneratePackage" Projects="$(MSBuildProjectDirectory)\build.csproj" />
<!-- Debug Build -->
<MSBuild Condition=" '$(PublishDebug)' == 'true' " Properties="Configuration=Debug;AssemblyOriginatorKeyFile=$(SigningKey)" Targets="_CompileAll" Projects="$(MSBuildProjectDirectory)\build.csproj" />
<MSBuild Condition=" '$(PublishDebug)' == 'true' " Properties="Configuration=Debug;AssemblyOriginatorKeyFile=$(SigningKey);PackageName=$(PackagePrefix)$(VersionLabel)-full" Targets="GeneratePackage" Projects="$(MSBuildProjectDirectory)\build.csproj" />
</Target>
<Target Name="_HgPack" DependsOnTargets="_Prerequisites">
<Exec Command="$(HgTool) archive $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-source.zip" WorkingDirectory="$(ProjectDirectory)" />
</Target>
<Target Name="_HgLabel" DependsOnTargets="_Prerequisites">
<Exec Command="$(HgTool) commit -m &quot;version $(VersionLabel)&quot;" WorkingDirectory="$(ProjectDirectory)" />
<Exec Command="$(HgTool) tag $(VersionLabel)" WorkingDirectory="$(ProjectDirectory)" />
</Target>
<Target Name="_HgPush" DependsOnTargets="_Prerequisites">
<Exec Command="$(HgTool) push" WorkingDirectory="$(ProjectDirectory)" />
</Target>
<Target Name="_PkgPush" DependsOnTargets="_Prerequisites">
<PropertyGroup>
<UploadPackage>$(Python) "$(MSBuildProjectDirectory)\googlecode_upload.py" --project protobuf-csharp-port --user "$(GoogleUsername)" --password "$(GooglePassword)"</UploadPackage>
<SourcePackage>$(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-source.zip</SourcePackage>
<ReleasePackageBin>$(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-release-binaries.zip</ReleasePackageBin>
<ReleasePackageSyb>$(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-release-symbols.zip</ReleasePackageSyb>
<DebugPackageBin>$(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-full-binaries.zip</DebugPackageBin>
<DebugPackageSyb>$(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-full-symbols.zip</DebugPackageSyb>
</PropertyGroup>
<Error Condition="!Exists('$(SourcePackage)')" Text="File not found: $(SourcePackage)" />
<Error Condition="!Exists('$(ReleasePackageBin)')" Text="File not found: $(ReleasePackageBin)" />
<Error Condition="!Exists('$(ReleasePackageSyb)')" Text="File not found: $(ReleasePackageSyb)" />
<Error Condition="'$(PublishDebug)' == 'true' And !Exists('$(DebugPackageBin)')" Text="File not found: $(DebugPackageBin)" />
<Error Condition="'$(PublishDebug)' == 'true' And !Exists('$(DebugPackageSyb)')" Text="File not found: $(DebugPackageSyb)" />
<Exec WorkingDirectory="$(ProjectDirectory)"
Command="$(UploadPackage) --labels Type-Source,Featured --summary &quot;Version $(VersionLabel) source&quot; $(SourcePackage)" />
<Exec WorkingDirectory="$(ProjectDirectory)"
Command="$(UploadPackage) --labels Type-Executable,Featured --summary &quot;Version $(VersionLabel) release binaries only&quot; $(ReleasePackageBin)" />
<Exec WorkingDirectory="$(ProjectDirectory)"
Command="$(UploadPackage) --labels Type-Executable,Featured --summary &quot;Version $(VersionLabel) release binaries and symbols&quot; $(ReleasePackageSyb)" />
<Exec WorkingDirectory="$(ProjectDirectory)" Condition=" '$(PublishDebug)' == 'true' "
Command="$(UploadPackage) --labels Type-Executable,Featured --summary &quot;Version $(VersionLabel) all binaries&quot; $(DebugPackageBin)" />
<Exec WorkingDirectory="$(ProjectDirectory)" Condition=" '$(PublishDebug)' == 'true' "
Command="$(UploadPackage) --labels Type-Executable,Featured --summary &quot;Version $(VersionLabel) all binaries and symbols&quot; $(DebugPackageSyb)" />
</Target>
<Target Name="_NugetPack" DependsOnTargets="_Prerequisites">
<Exec WorkingDirectory="$(MSBuildProjectDirectory)"
Command="$(NuGet) update -self" />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)"
Command="$(NuGet) pack Google.ProtocolBuffers.nuspec -Symbols -Version $(VersionLabel) -NoPackageAnalysis -OutputDirectory $(BuildTempDirectory)" />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)"
Command="$(NuGet) pack Google.ProtocolBuffersLite.nuspec -Symbols -Version $(VersionLabel) -NoPackageAnalysis -OutputDirectory $(BuildTempDirectory)" />
</Target>
<Target Name="_NugetPush" DependsOnTargets="_Prerequisites">
<Exec WorkingDirectory="$(BuildTempDirectory)" Command="$(NuGet) push Google.ProtocolBuffers.$(VersionLabel).nupkg" ContinueOnError="true" />
<Exec WorkingDirectory="$(BuildTempDirectory)" Command="$(NuGet) push Google.ProtocolBuffersLite.$(VersionLabel).nupkg" ContinueOnError="true" />
<Exec WorkingDirectory="$(BuildTempDirectory)" Command="$(NuGet) push Google.ProtocolBuffers.$(VersionLabel).symbols.nupkg" ContinueOnError="true" />
<Exec WorkingDirectory="$(BuildTempDirectory)" Command="$(NuGet) push Google.ProtocolBuffersLite.$(VersionLabel).symbols.nupkg" ContinueOnError="true" />
</Target>
</Project>

@ -0,0 +1,167 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- **********************************************************************************************
High-level Targets
*********************************************************************************************** -->
<Target Name="Clean" DependsOnTargets="_Clean" />
<Target Name="Build" DependsOnTargets="_Compile;_Test" />
<Target Name="Test" DependsOnTargets="_Test" />
<Target Name="Rebuild" DependsOnTargets="Clean;Build" />
<Target Name="Publish" DependsOnTargets="Clean;Build;_Publish" />
<!-- **********************************************************************************************
Properties
*********************************************************************************************** -->
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">Any CPU</Platform>
<TargetVersion Condition=" '$(TargetVersion)' == '' ">NET20</TargetVersion>
<BuildParams></BuildParams>
<!--Directory Paths-->
<ProjectDirectory>$(MSBuildProjectDirectory)\..</ProjectDirectory>
<SourceDirectory>$(ProjectDirectory)\src</SourceDirectory>
<LibDirectory>$(ProjectDirectory)\lib</LibDirectory>
<!--File Paths-->
<BuildTempDirectory>$(ProjectDirectory)\build_temp\$(Configuration)\$(TargetVersion)</BuildTempDirectory>
<BuildOutputDirectory>$(ProjectDirectory)\build_output\$(Configuration)\$(TargetVersion)</BuildOutputDirectory>
<SolutionFile>$(SourceDirectory)\ProtocolBuffersLibrary.$(TargetVersion).sln</SolutionFile>
<!--Tool Paths-->
<NUnitExePath>$(LibDirectory)\NUnit\tools\nunit-console.exe</NUnitExePath>
<StatLightExePath>$(LibDirectory)\StatLight\tools\StatLight.exe</StatLightExePath>
</PropertyGroup>
<!-- **********************************************************************************************
Target Versions
*********************************************************************************************** -->
<PropertyGroup Condition=" '$(TargetVersion)' == 'NET20' ">
<BuildTools>3.5</BuildTools>
<TestFramework>NUNIT</TestFramework>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'NET35' ">
<BuildTools>3.5</BuildTools>
<TestFramework>NUNIT</TestFramework>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'NET40' ">
<BuildTools>4.0</BuildTools>
<TestFramework>NUNIT</TestFramework>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'CF20' ">
<BuildTools>3.5</BuildTools>
<TestFramework>NONE</TestFramework>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'CF35' ">
<BuildTools>3.5</BuildTools>
<TestFramework>NONE</TestFramework>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'SL20' ">
<BuildTools>3.5</BuildTools>
<TestFramework>SILVERLIGHT</TestFramework>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'SL30' ">
<BuildTools>3.5</BuildTools>
<TestFramework>SILVERLIGHT</TestFramework>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'SL40' ">
<BuildTools>4.0</BuildTools>
<TestFramework>SILVERLIGHT</TestFramework>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetVersion)' == 'PL40' ">
<BuildTools>4.0</BuildTools>
<TestFramework>SILVERLIGHT</TestFramework>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<BuildOutputDirectory>$(ProjectDirectory)\build_output\$(Configuration)\portable-net40+sl4+sl5+wp7+wp8+win8</BuildOutputDirectory>
</PropertyGroup>
<!-- **********************************************************************************************
File Groups
*********************************************************************************************** -->
<ItemGroup>
<WorkingDirectories Include="$(BuildTempDirectory)" />
<WorkingDirectories Include="$(BuildOutputDirectory)" />
<TestContainer Include="$(SourceDirectory)\ProtocolBuffers.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.Test.dll" />
<TestContainer Include="$(SourceDirectory)\ProtocolBuffersLite.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.Test.dll" />
<TestContainer Include="$(SourceDirectory)\ProtocolBuffersLite.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersMixedLite.Test.dll" />
<StatLightTestContainer Include="$(SourceDirectory)\ProtocolBuffers.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.Test.xap" />
<StatLightTestContainer Include="$(SourceDirectory)\ProtocolBuffersLite.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.Test.xap" />
<StatLightTestContainer Include="$(SourceDirectory)\ProtocolBuffersLite.Test\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersMixedLite.Test.xap" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.dll" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.pdb" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.xml" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.dll" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.pdb" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.xml" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.Serialization.dll" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.Serialization.pdb" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffers.Serialization.xml" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.Serialization.dll" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.Serialization.pdb" />
<PublishItem Include="$(SourceDirectory)\ProtocolBuffers.Serialization\bin\$(TargetVersion)\$(Configuration)\Google.ProtocolBuffersLite.Serialization.xml" />
</ItemGroup>
<!-- **********************************************************************************************
Targets For Build
*********************************************************************************************** -->
<Target Name="_Configured">
<Message Text="Building $(TargetVersion) for configuration $(Configuration), platform $(Platform)" Importance="normal" />
<Error Text="Unknown or missing value for TargetVersion=[value]" Condition=" '$(BuildTools)' == '' " />
</Target>
<Target Name="_Clean" DependsOnTargets="_Configured">
<RemoveDir Directories="@(WorkingDirectories)" Condition="Exists(%(WorkingDirectories.Identity))" />
<MSBuild Targets="Clean" Projects="$(SolutionFile)" ToolsVersion="$(BuildTools)"
Properties="Configuration=$(Configuration);Platform=$(Platform);"
/>
</Target>
<Target Name="_Compile" DependsOnTargets="_Configured">
<MSBuild Targets="Build" Projects="$(SolutionFile)" ToolsVersion="$(BuildTools)"
Properties="Configuration=$(Configuration);Platform=$(Platform);$(BuildParams)"
/>
</Target>
<Target Name="_Publish" DependsOnTargets="_Configured">
<MakeDir Directories="$(BuildOutputDirectory)" />
<Copy SourceFiles="@(PublishItem)" DestinationFolder="$(BuildOutputDirectory)" />
</Target>
<!-- **********************************************************************************************
Targets For Test
*********************************************************************************************** -->
<Target Name="_Test" DependsOnTargets="_Configured">
<MakeDir Directories="$(BuildTempDirectory)" />
<CallTarget Targets="_RunNunit" Condition=" '$(TestFramework)'=='NUNIT' " />
<CallTarget Targets="_RunStatLight" Condition=" '$(TestFramework)'=='SILVERLIGHT' " />
</Target>
<Target Name="_RunNunit">
<Copy SourceFiles="$(LibDirectory)\NUnit-config\nunit-console.$(TargetFrameworkVersion).config" DestinationFiles="$(NUnitExePath).config" />
<Exec Command="&quot;$(NUnitExePath)&quot; /nologo /noshadow &quot;%(TestContainer.Identity)&quot; /xml:&quot;$(BuildTempDirectory)\%(TestContainer.Filename).xml&quot;" />
</Target>
<Target Name="_RunStatLight">
<Exec
Command="&quot;$(StatLightExePath)&quot; -x %(StatLightTestContainer.Identity) --ReportOutputFileType=NUnit --ReportOutputFile=$(BuildTempDirectory)\%(StatLightTestContainer.Filename).xml" />
</Target>
</Project>

@ -0,0 +1,41 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<EnvironmentFlavor>COMPACT_FRAMEWORK</EnvironmentFlavor>
<EnvironmentTemplate>CF20</EnvironmentTemplate>
<ProjectTypeGuids>{4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<PlatformFamilyName>Smartphone</PlatformFamilyName>
<PlatformID>f27da329-3269-4191-98e0-c87d3d7f1db9</PlatformID>
<!--<OSVersion>5.2</OSVersion>-->
<!--<DeployDirSuffix>CF20</DeployDirSuffix>-->
<!--<NativePlatformName>Windows Mobile 6 Standard SDK</NativePlatformName>-->
<!--<FormFactorID></FormFactorID>-->
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\CF20\Debug</OutputPath>
<IntermediateOutputPath>obj\CF20\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOFILEVERSION;NOEXTENSIONS</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\CF20\Release</OutputPath>
<IntermediateOutputPath>obj\CF20\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOFILEVERSION;NOEXTENSIONS</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CompactFramework.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}">
<HostingProcess disable="1" />
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,44 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<EnvironmentFlavor>COMPACT_FRAMEWORK</EnvironmentFlavor>
<EnvironmentTemplate>CF35</EnvironmentTemplate>
<ProjectTypeGuids>{4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<PlatformFamilyName>Smartphone</PlatformFamilyName>
<PlatformID>f27da329-3269-4191-98e0-c87d3d7f1db9</PlatformID>
<!--<OSVersion>5.2</OSVersion>-->
<!--<DeployDirSuffix>CF35</DeployDirSuffix>-->
<!--<NativePlatformName>Windows Mobile 6 Standard SDK</NativePlatformName>-->
<!--<FormFactorID></FormFactorID>-->
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\CF35\Debug</OutputPath>
<IntermediateOutputPath>obj\CF35\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOFILEVERSION</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\CF35\Release</OutputPath>
<IntermediateOutputPath>obj\CF35\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOFILEVERSION</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CompactFramework.CSharp.targets" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}">
<HostingProcess disable="1" />
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,17 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET20</EnvironmentTemplate>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\NET20\Debug</OutputPath>
<IntermediateOutputPath>obj\NET20\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOEXTENSIONS</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\NET20\Release</OutputPath>
<IntermediateOutputPath>obj\NET20\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOEXTENSIONS</DefineConstants>
</PropertyGroup>
</Project>

@ -0,0 +1,20 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
</Project>

@ -0,0 +1,20 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET40</EnvironmentTemplate>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\NET40\Debug</OutputPath>
<IntermediateOutputPath>obj\NET40\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\NET40\Release</OutputPath>
<IntermediateOutputPath>obj\NET40\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants)</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
</Project>

@ -0,0 +1,51 @@
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:cs="urn:schemas-csharp-project:template">
<PropertyGroup>
<MinimumVisualStudioVersion>10.0</MinimumVisualStudioVersion>
<EnvironmentFlavor>PORTABLE_LIBRARY</EnvironmentFlavor>
<EnvironmentTemplate>PL40</EnvironmentTemplate>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Profile1</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\PL40\Debug</OutputPath>
<IntermediateOutputPath>obj\PL40\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\PL40\Release</OutputPath>
<IntermediateOutputPath>obj\PL40\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
<Import cs:Precondition=" '$(EnvironmentProjectType)' != 'TEST' "
Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<!-- Portable Library will be tested as silverlight -->
<PropertyGroup cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' ">
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<ValidateXaml>false</ValidateXaml>
<ThrowErrorsInValidation>false</ThrowErrorsInValidation>
<TargetFrameworkProfile />
</PropertyGroup>
<cs:Import Project="SLTest.targets" cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' " />
<Import cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' "
Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\$(SilverlightVersion)\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' ">
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties />
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

@ -0,0 +1,44 @@
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:cs="urn:schemas-csharp-project:template">
<PropertyGroup>
<EnvironmentFlavor>SILVERLIGHT</EnvironmentFlavor>
<EnvironmentTemplate>SL20</EnvironmentTemplate>
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>false</ValidateXaml>
<ThrowErrorsInValidation>false</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\SL20\Debug</OutputPath>
<IntermediateOutputPath>obj\SL20\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST;NOEXTENSIONS</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\SL20\Release</OutputPath>
<IntermediateOutputPath>obj\SL20\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST;NOEXTENSIONS</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<!-- Preprocess include of silverlight testing -->
<cs:Import Project="SLTest.targets" cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' " />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\v2.0\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties>
<StartAction>OfflineApplication</StartAction>
</SilverlightProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

@ -0,0 +1,47 @@
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:cs="urn:schemas-csharp-project:template">
<PropertyGroup>
<EnvironmentFlavor>SILVERLIGHT</EnvironmentFlavor>
<EnvironmentTemplate>SL30</EnvironmentTemplate>
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>false</ValidateXaml>
<ThrowErrorsInValidation>false</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\SL30\Debug</OutputPath>
<IntermediateOutputPath>obj\SL30\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\SL30\Release</OutputPath>
<IntermediateOutputPath>obj\SL30\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
<!-- Preprocess include of silverlight testing -->
<cs:Import Project="SLTest.targets" cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' " />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties>
<StartAction>OfflineApplication</StartAction>
</SilverlightProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

@ -0,0 +1,48 @@
<Project ToolsVersion="4.0" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:cs="urn:schemas-csharp-project:template">
<PropertyGroup>
<EnvironmentFlavor>SILVERLIGHT</EnvironmentFlavor>
<EnvironmentTemplate>SL40</EnvironmentTemplate>
<ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>false</ValidateXaml>
<ThrowErrorsInValidation>false</ThrowErrorsInValidation>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\SL40\Debug</OutputPath>
<IntermediateOutputPath>obj\SL40\Debug\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\SL40\Release</OutputPath>
<IntermediateOutputPath>obj\SL40\Release\</IntermediateOutputPath>
<DefineConstants>$(DefineConstants);NOSERIALIZABLE;NOSORTEDLIST</DefineConstants>
<NoConfig>true</NoConfig>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Core" />
</ItemGroup>
<!-- Preprocess include of silverlight testing -->
<cs:Import Project="SLTest.targets" cs:Precondition=" '$(EnvironmentProjectType)' == 'TEST' " />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\$(SilverlightVersion)\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{A1591282-1198-4647-A2B1-27E5FF5F6F3B}">
<SilverlightProjectProperties>
<StartAction>OfflineApplication</StartAction>
</SilverlightProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

@ -0,0 +1,34 @@
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:cs="urn:schemas-csharp-project:template">
<PropertyGroup>
<SilverlightApplication>true</SilverlightApplication>
<XapOutputs>true</XapOutputs>
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
<XapFilename>$(AssemblyName).xap</XapFilename>
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
<SilverlightAppEntry>$(RootNamespace).App</SilverlightAppEntry>
<TestPageFileName>TestPage.html</TestPageFileName>
<CreateTestPage>true</CreateTestPage>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<OutOfBrowserSettingsFile>Properties\OutOfBrowserSettings.xml</OutOfBrowserSettingsFile>
<EnableOutOfBrowser>true</EnableOutOfBrowser>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Windows" />
<Reference Include="System.Windows.Browser" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<None Include="Properties\AppManifest.xml" />
<None Include="Properties\OutOfBrowserSettings.xml" />
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
</Project>

@ -0,0 +1,13 @@
@ECHO OFF
IF EXIST "C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe" GOTO FOUND
goto USEPATH
:FOUND
"C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe" -k %~dp0\Google.ProtocolBuffers.snk
GOTO EXIT
:USEPATH
sn.exe -k %~dp0\Google.ProtocolBuffers.snk
GOTO EXIT
:EXIT

@ -0,0 +1,54 @@

using System;
#if CLIENTPROFILE
namespace Microsoft.VisualStudio.TestTools.UnitTesting
{
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class TestClassAttribute : NUnit.Framework.TestFixtureAttribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class TestMethodAttribute : NUnit.Framework.TestAttribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class TestInitializeAttribute : NUnit.Framework.SetUpAttribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class IgnoreAttribute : NUnit.Framework.IgnoreAttribute
{
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class ExpectedExceptionAttribute : NUnit.Framework.ExpectedExceptionAttribute
{
public ExpectedExceptionAttribute(Type type) : base(type)
{ }
}
public class Assert : NUnit.Framework.Assert
{
[Obsolete("Do not use AreEqual on Byte[], use TestUtil.AssertBytesEqual(,)")]
public static void AreEqual(byte[] b1, byte[] b2)
{
NUnit.Framework.Assert.AreEqual(b1, b2);
}
[Obsolete("No not use assert with miss-matched types.")]
public static new void AreEqual(object b1, object b2)
{
NUnit.Framework.Assert.AreEqual(b1, b2);
}
//Allowed if the types match
public static void AreEqual<T>(T b1, T b2)
{
NUnit.Framework.Assert.AreEqual(b1, b2);
}
}
}
#endif

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="Windows-1252"?>
<configuration>
<startup>
<requiredRuntime version="v2.0.50727" />
</startup>
<runtime>
<!-- We need this so test exceptions don't crash NUnit -->
<legacyUnhandledExceptionPolicy enabled="1" />
<!-- Look for addins in the addins directory for now -->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="lib;addins"/>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="Windows-1252"?>
<configuration>
<startup>
<requiredRuntime version="v2.0.50727" />
</startup>
<runtime>
<!-- We need this so test exceptions don't crash NUnit -->
<legacyUnhandledExceptionPolicy enabled="1" />
<!-- Look for addins in the addins directory for now -->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="lib;addins"/>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="Windows-1252"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<requiredRuntime version="v4.0.30319" safemode="true"/>
</startup>
<runtime>
<!-- We need this so test exceptions don't crash NUnit -->
<legacyUnhandledExceptionPolicy enabled="1" />
<!-- Look for addins in the addins directory for now -->
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="lib;addins"/>
</assemblyBinding>
</runtime>
</configuration>

@ -0,0 +1,13 @@
This directory used to contain the binary dependencies, but they were removed during a cleanup associated with importing the project
into google/protobuf repository. Before we figure a better way to manage the dependencies, you will have to manually download the dependencies
to be able to build the test projects:
1. Download https://github.com/jskeet/protobuf-csharp-port/archive/2.4.1.555.zip
2. Open the archive and copy following files into this directory:
* `lib/Microsoft.Silverlight.Testing/`
* `lib/NUnit/`
* `lib/proto.exe`
After that, you should be able to fully build the C# protobufs Visual Studio solutions.
TODO(jtattermusch): the way we pull in dependencies needs to change

@ -0,0 +1,37 @@
#!/bin/bash
# Adjust these to reflect the location of NUnit in your system,
# and how you want NUnit to run
NUNIT=~/protobuf/NUnit-2.5.0.9122/bin/net-2.0/nunit-console.exe
NUNIT_OPTIONS=-noshadow
# The rest should be okay.
SRC=../src
LIB=../lib
KEYFILE=../keys/Google.ProtocolBuffers.snk
rm -rf bin
mkdir bin
# Running the unit tests requires the dependencies are
# in the bin directory too
cp -f $LIB/{Rhino.Mocks.dll,nunit.framework.dll} bin
echo Building main library
gmcs -target:library -out:bin/Google.ProtocolBuffers.dll `find $SRC/ProtocolBuffers -name '*.cs'` -keyfile:$KEYFILE
echo Building main library tests
gmcs -target:library -out:bin/Google.ProtocolBuffers.Test.dll `find $SRC/ProtocolBuffers.Test -name '*.cs'` -keyfile:$KEYFILE -r:bin/Google.ProtocolBuffers.dll -r:$LIB/nunit.framework.dll -r:$LIB/Rhino.Mocks.dll
echo Running main library tests
mono $NUNIT bin/Google.ProtocolBuffers.Test.dll $NUNIT_OPTIONS
echo Building ProtoGen
gmcs -target:exe -out:bin/ProtoGen.exe `find $SRC/ProtoGen -name '*.cs'` -keyfile:$KEYFILE -r:bin/Google.ProtocolBuffers.dll
echo Building ProtoGen tests
gmcs -target:library -out:bin/Google.ProtocolBuffers.ProtoGen.Test.dll `find $SRC/ProtoGen.Test -name '*.cs'` -keyfile:$KEYFILE -r:bin/Google.ProtocolBuffers.dll -r:$LIB/nunit.framework.dll -r:bin/ProtoGen.exe
echo Running ProtoGen tests
mono $NUNIT bin/Google.ProtocolBuffers.ProtoGen.Test.dll $NUNIT_OPTIONS

@ -0,0 +1,29 @@
#!/bin/bash
echo Compiling protobufs
rm -rf tmp
mkdir tmp
PROTOS_DIR=../protos
./protoc --proto_path=$PROTOS_DIR --descriptor_set_out=tmp/compiled.pb \
$PROTOS_DIR/google/protobuf/descriptor.proto \
$PROTOS_DIR/google/protobuf/csharp_options.proto \
$PROTOS_DIR/google/protobuf/unittest.proto \
$PROTOS_DIR/google/protobuf/unittest_csharp_options.proto \
$PROTOS_DIR/google/protobuf/unittest_custom_options.proto \
$PROTOS_DIR/google/protobuf/unittest_embed_optimize_for.proto \
$PROTOS_DIR/google/protobuf/unittest_import.proto \
$PROTOS_DIR/google/protobuf/unittest_mset.proto \
$PROTOS_DIR/google/protobuf/unittest_optimize_for.proto \
$PROTOS_DIR/tutorial/addressbook.proto
cd tmp
echo Generating new source
mono ../bin/ProtoGen.exe compiled.pb
echo Copying source into place
cp DescriptorProtoFile.cs CSharpOptions.cs ../../src/ProtocolBuffers/DescriptorProtos
cp UnitTest*.cs ../../src/ProtocolBuffers.Test/TestProtos
cp AddressBookProtos.cs ../../src/AddressBook
cd ..
rm -rf tmp

@ -0,0 +1,91 @@
Getting started with Protocol Buffers on Mono
---------------------------------------------
Prerequisites:
o Mono 2.4 or higher. Earlier versions of Mono had too
many issues with the weird and wonderful generic type
relationships in Protocol Buffers. (Even Mono 2.4 *did*
have a few compile-time problems, but I've worked round them.)
o Some sort of Linux/Unix system
You can try running with Bash on Windows via MINGW32 or
something similar, but you're on your own :) It's easier
to build and test everything with .NET if you're on
Windows.
o The native Protocol Buffers build for your system.
Get it from http://code.google.com/p/protobuf/
After building it, copy the executable protoc
file into this directory.
o The NUnit binaries from http://nunit.org
I generally just download the latest version, which
may not be the one which goes with nunit.framework.dll
in ../lib, but I've never found this to be a problem.
Building the code with current sources
--------------------------------------
1) Edit buildall.sh to tell it where to find nunit-console.exe
(and possibly change other options)
2) Run buildall.sh from this directory. It should build the
main library code + tests and ProtoGen code + tests, running
each set of tests after building it.
Note that currently one test is ignored in ServiceTest.cs. This
made the Mono VM blow up - I suspect it's some interaction with
Rhino which doesn't quite work on Mono 2.4. If you want to see a
truly nasty stack trace, just comment out the Ignore attribute in
ServiceTest.cs and rerun.
The binaries will be produced in a bin directory under this one. The
build currently starts from scratch each time, cleaning out the bin
directory first. Once I've decided on a full NAnt or xbuild
strategy, I'll do something a little cleaner.
Rebuilding sources for generated code
-------------------------------------
1) Build the current code first. The bootstrapping issue is why
the generated source code is in the source repository :) See
the steps above.
2) Run generatesource.sh from this directory. This will create a
temporary directory, compile the .proto files into a binary
format, then run ProtoGen to generate .cs files from the binary
format. It will copy these files to the right places in the tree,
and finally delete the temporary directory.
3) Rebuild to test that your newly generated sources work. (Optionally
regenerate as well, and hash the generated files to check that
the new build generates the same code as the old build :)
Running the code
----------------
Once you've built the binaries, you should be able to use them just
as if you'd built them with .NET. (And indeed, you should be able to
use binaries built with .NET as if you'd built them with Mono :)
See the getting started guide for more information:
http://code.google.com/p/protobuf-csharp-port/wiki/GettingStarted
FAQ (Frequently Anticipated Questions)
--------------------------------------
Q) This build process sucks! Why aren't you doing X, Y, Z?
A) My Mono skills are limited. My NAnt skills are limited. My
MSBuild/xbuild skils are limited. My shell script skills are
limited. Any help is *very* welcome!
Q) Why doesn't it build ProtoBench etc?
A) This is a first initial "release" I'll add more bits to
the build script. I'll be interested to see the results
of benchmarking it on Mono :)
Any further questions or suggestions? Please email skeet@pobox.com
or leave a request at
http://code.google.com/p/protobuf-csharp-port/issues/list

@ -0,0 +1,140 @@
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.ProtoBench";
option (google.protobuf.csharp_file_options).umbrella_classname = "GoogleSizeProtoFile";
package benchmarks;
option java_outer_classname = "GoogleSize";
option optimize_for = CODE_SIZE;
message SizeMessage1 {
required string field1 = 1;
optional string field9 = 9;
optional string field18 = 18;
optional bool field80 = 80 [default=false];
optional bool field81 = 81 [default=true];
required int32 field2 = 2;
required int32 field3 = 3;
optional int32 field280 = 280;
optional int32 field6 = 6 [default=0];
optional int64 field22 = 22;
optional string field4 = 4;
repeated fixed64 field5 = 5;
optional bool field59 = 59 [default=false];
optional string field7 = 7;
optional int32 field16 = 16;
optional int32 field130 = 130 [default=0];
optional bool field12 = 12 [default=true];
optional bool field17 = 17 [default=true];
optional bool field13 = 13 [default=true];
optional bool field14 = 14 [default=true];
optional int32 field104 = 104 [default=0];
optional int32 field100 = 100 [default=0];
optional int32 field101 = 101 [default=0];
optional string field102 = 102;
optional string field103 = 103;
optional int32 field29 = 29 [default=0];
optional bool field30 = 30 [default=false];
optional int32 field60 = 60 [default=-1];
optional int32 field271 = 271 [default=-1];
optional int32 field272 = 272 [default=-1];
optional int32 field150 = 150;
optional int32 field23 = 23 [default=0];
optional bool field24 = 24 [default=false];
optional int32 field25 = 25 [default=0];
optional SizeMessage1SubMessage field15 = 15;
optional bool field78 = 78;
optional int32 field67 = 67 [default=0];
optional int32 field68 = 68;
optional int32 field128 = 128 [default=0];
optional string field129 = 129 [default="xxxxxxxxxxxxxxxxxxxxx"];
optional int32 field131 = 131 [default=0];
}
message SizeMessage1SubMessage {
optional int32 field1 = 1 [default=0];
optional int32 field2 = 2 [default=0];
optional int32 field3 = 3 [default=0];
optional string field15 = 15;
optional bool field12 = 12 [default=true];
optional int64 field13 = 13;
optional int64 field14 = 14;
optional int32 field16 = 16;
optional int32 field19 = 19 [default=2];
optional bool field20 = 20 [default=true];
optional bool field28 = 28 [default=true];
optional fixed64 field21 = 21;
optional int32 field22 = 22;
optional bool field23 = 23 [ default=false ];
optional bool field206 = 206 [default=false];
optional fixed32 field203 = 203;
optional int32 field204 = 204;
optional string field205 = 205;
optional uint64 field207 = 207;
optional uint64 field300 = 300;
}
message SizeMessage2 {
optional string field1 = 1;
optional int64 field3 = 3;
optional int64 field4 = 4;
optional int64 field30 = 30;
optional bool field75 = 75 [default=false];
optional string field6 = 6;
optional bytes field2 = 2;
optional int32 field21 = 21 [default=0];
optional int32 field71 = 71;
optional float field25 = 25;
optional int32 field109 = 109 [default=0];
optional int32 field210 = 210 [default=0];
optional int32 field211 = 211 [default=0];
optional int32 field212 = 212 [default=0];
optional int32 field213 = 213 [default=0];
optional int32 field216 = 216 [default=0];
optional int32 field217 = 217 [default=0];
optional int32 field218 = 218 [default=0];
optional int32 field220 = 220 [default=0];
optional int32 field221 = 221 [default=0];
optional float field222 = 222 [default=0.0];
optional int32 field63 = 63;
repeated group Group1 = 10 {
required float field11 = 11;
optional float field26 = 26;
optional string field12 = 12;
optional string field13 = 13;
repeated string field14 = 14;
required uint64 field15 = 15;
optional int32 field5 = 5;
optional string field27 = 27;
optional int32 field28 = 28;
optional string field29 = 29;
optional string field16 = 16;
repeated string field22 = 22;
repeated int32 field73 = 73;
optional int32 field20 = 20 [default=0];
optional string field24 = 24;
optional SizeMessage2GroupedMessage field31 = 31;
}
repeated string field128 = 128;
optional int64 field131 = 131;
repeated string field127 = 127;
optional int32 field129 = 129;
repeated int64 field130 = 130;
optional bool field205 = 205 [default=false];
optional bool field206 = 206 [default=false];
}
message SizeMessage2GroupedMessage {
optional float field1 = 1;
optional float field2 = 2;
optional float field3 = 3 [default=0.0];
optional bool field4 = 4;
optional bool field5 = 5;
optional bool field6 = 6 [default=true];
optional bool field7 = 7 [default=false];
optional float field8 = 8;
optional bool field9 = 9;
optional float field10 = 10;
optional int64 field11 = 11;
}

@ -0,0 +1,140 @@
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.ProtoBench";
option (google.protobuf.csharp_file_options).umbrella_classname = "GoogleSpeedProtoFile";
package benchmarks;
option java_outer_classname = "GoogleSpeed";
option optimize_for = SPEED;
message SpeedMessage1 {
required string field1 = 1;
optional string field9 = 9;
optional string field18 = 18;
optional bool field80 = 80 [default=false];
optional bool field81 = 81 [default=true];
required int32 field2 = 2;
required int32 field3 = 3;
optional int32 field280 = 280;
optional int32 field6 = 6 [default=0];
optional int64 field22 = 22;
optional string field4 = 4;
repeated fixed64 field5 = 5;
optional bool field59 = 59 [default=false];
optional string field7 = 7;
optional int32 field16 = 16;
optional int32 field130 = 130 [default=0];
optional bool field12 = 12 [default=true];
optional bool field17 = 17 [default=true];
optional bool field13 = 13 [default=true];
optional bool field14 = 14 [default=true];
optional int32 field104 = 104 [default=0];
optional int32 field100 = 100 [default=0];
optional int32 field101 = 101 [default=0];
optional string field102 = 102;
optional string field103 = 103;
optional int32 field29 = 29 [default=0];
optional bool field30 = 30 [default=false];
optional int32 field60 = 60 [default=-1];
optional int32 field271 = 271 [default=-1];
optional int32 field272 = 272 [default=-1];
optional int32 field150 = 150;
optional int32 field23 = 23 [default=0];
optional bool field24 = 24 [default=false];
optional int32 field25 = 25 [default=0];
optional SpeedMessage1SubMessage field15 = 15;
optional bool field78 = 78;
optional int32 field67 = 67 [default=0];
optional int32 field68 = 68;
optional int32 field128 = 128 [default=0];
optional string field129 = 129 [default="xxxxxxxxxxxxxxxxxxxxx"];
optional int32 field131 = 131 [default=0];
}
message SpeedMessage1SubMessage {
optional int32 field1 = 1 [default=0];
optional int32 field2 = 2 [default=0];
optional int32 field3 = 3 [default=0];
optional string field15 = 15;
optional bool field12 = 12 [default=true];
optional int64 field13 = 13;
optional int64 field14 = 14;
optional int32 field16 = 16;
optional int32 field19 = 19 [default=2];
optional bool field20 = 20 [default=true];
optional bool field28 = 28 [default=true];
optional fixed64 field21 = 21;
optional int32 field22 = 22;
optional bool field23 = 23 [ default=false ];
optional bool field206 = 206 [default=false];
optional fixed32 field203 = 203;
optional int32 field204 = 204;
optional string field205 = 205;
optional uint64 field207 = 207;
optional uint64 field300 = 300;
}
message SpeedMessage2 {
optional string field1 = 1;
optional int64 field3 = 3;
optional int64 field4 = 4;
optional int64 field30 = 30;
optional bool field75 = 75 [default=false];
optional string field6 = 6;
optional bytes field2 = 2;
optional int32 field21 = 21 [default=0];
optional int32 field71 = 71;
optional float field25 = 25;
optional int32 field109 = 109 [default=0];
optional int32 field210 = 210 [default=0];
optional int32 field211 = 211 [default=0];
optional int32 field212 = 212 [default=0];
optional int32 field213 = 213 [default=0];
optional int32 field216 = 216 [default=0];
optional int32 field217 = 217 [default=0];
optional int32 field218 = 218 [default=0];
optional int32 field220 = 220 [default=0];
optional int32 field221 = 221 [default=0];
optional float field222 = 222 [default=0.0];
optional int32 field63 = 63;
repeated group Group1 = 10 {
required float field11 = 11;
optional float field26 = 26;
optional string field12 = 12;
optional string field13 = 13;
repeated string field14 = 14;
required uint64 field15 = 15;
optional int32 field5 = 5;
optional string field27 = 27;
optional int32 field28 = 28;
optional string field29 = 29;
optional string field16 = 16;
repeated string field22 = 22;
repeated int32 field73 = 73;
optional int32 field20 = 20 [default=0];
optional string field24 = 24;
optional SpeedMessage2GroupedMessage field31 = 31;
}
repeated string field128 = 128;
optional int64 field131 = 131;
repeated string field127 = 127;
optional int32 field129 = 129;
repeated int64 field130 = 130;
optional bool field205 = 205 [default=false];
optional bool field206 = 206 [default=false];
}
message SpeedMessage2GroupedMessage {
optional float field1 = 1;
optional float field2 = 2;
optional float field3 = 3 [default=0.0];
optional bool field4 = 4;
optional bool field5 = 5;
optional bool field6 = 6 [default=true];
optional bool field7 = 7 [default=false];
optional float field8 = 8;
optional bool field9 = 9;
optional float field10 = 10;
optional int64 field11 = 11;
}

@ -0,0 +1,37 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasProtoFile";
option (google.protobuf.csharp_file_options).add_serializable = true;
package protobuf_unittest_extra;
option java_package = "com.google.protobuf";
message TestUnpackedExtensions {
extensions 1 to max;
}
extend TestUnpackedExtensions {
repeated int32 unpacked_int32_extension = 90;
repeated int64 unpacked_int64_extension = 91;
repeated uint32 unpacked_uint32_extension = 92;
repeated uint64 unpacked_uint64_extension = 93;
repeated sint32 unpacked_sint32_extension = 94;
repeated sint64 unpacked_sint64_extension = 95;
repeated fixed32 unpacked_fixed32_extension = 96;
repeated fixed64 unpacked_fixed64_extension = 97;
repeated sfixed32 unpacked_sfixed32_extension = 98;
repeated sfixed64 unpacked_sfixed64_extension = 99;
repeated float unpacked_float_extension = 100;
repeated double unpacked_double_extension = 101;
repeated bool unpacked_bool_extension = 102;
repeated UnpackedExtensionsForeignEnum unpacked_enum_extension = 103;
}
enum UnpackedExtensionsForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}

@ -0,0 +1,72 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasFullProtoFile";
package protobuf_unittest_extra;
option optimize_for = CODE_SIZE;
option java_package = "com.google.protobuf";
message TestInteropPerson {
required string name = 1;
required int32 id = 2;
optional string email = 3;
repeated int32 codes = 10 [packed=true];
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
repeated group Addresses = 5 {
required string address = 1;
optional string address2 = 2;
required string city = 3;
required string state = 4;
required fixed32 zip = 5;
}
extensions 100 to 199;
}
message TestInteropEmployeeId {
required string number = 1;
}
extend TestInteropPerson {
required TestInteropEmployeeId employee_id = 126;
}
message TestMissingFieldsA {
required string name = 1;
required int32 id = 2;
optional string email = 3;
message SubA {
required int32 count = 5;
repeated string values = 6;
}
optional SubA testA = 11;
}
message TestMissingFieldsB {
required string name = 1;
required int32 id = 2;
optional string website = 4;
message SubB {
repeated string values = 7;
}
optional SubB testB = 12;
}

@ -0,0 +1,117 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasLiteProtoFile";
option (google.protobuf.csharp_file_options).add_serializable = true;
package protobuf_unittest_extra;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message TestRequiredLite {
required int32 d = 1;
required ExtraEnum en = 2 [default = DEFAULT];
}
enum ExtraEnum {
DEFAULT = 10;
EXLITE_FOO = 7;
EXLITE_BAR = 8;
EXLITE_BAZ = 9;
}
message TestInteropPersonLite {
required string name = 1;
required int32 id = 2;
optional string email = 3;
repeated int32 codes = 10 [packed=true];
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
repeated group Addresses = 5 {
required string address = 1;
optional string address2 = 2;
required string city = 3;
required string state = 4;
required fixed32 zip = 5;
}
extensions 100 to 199;
}
message TestInteropEmployeeIdLite {
required string number = 1;
}
extend TestInteropPersonLite {
required TestInteropEmployeeIdLite employee_id_lite = 126;
}
/* Removed from unittest_lite.proto and added back here */
message TestUnpackedExtensionsLite {
extensions 1 to max;
}
message TestUnpackedTypesLite {
repeated int32 unpacked_int32 = 90;
repeated int64 unpacked_int64 = 91;
repeated uint32 unpacked_uint32 = 92;
repeated uint64 unpacked_uint64 = 93;
repeated sint32 unpacked_sint32 = 94;
repeated sint64 unpacked_sint64 = 95;
repeated fixed32 unpacked_fixed32 = 96;
repeated fixed64 unpacked_fixed64 = 97;
repeated sfixed32 unpacked_sfixed32 = 98;
repeated sfixed64 unpacked_sfixed64 = 99;
repeated float unpacked_float = 100;
repeated double unpacked_double = 101;
repeated bool unpacked_bool = 102;
repeated UnpackedTypesForeignEnumLite unpacked_enum = 103;
}
extend TestUnpackedExtensionsLite {
repeated int32 unpacked_int32_extension_lite = 90;
repeated int64 unpacked_int64_extension_lite = 91;
repeated uint32 unpacked_uint32_extension_lite = 92;
repeated uint64 unpacked_uint64_extension_lite = 93;
repeated sint32 unpacked_sint32_extension_lite = 94;
repeated sint64 unpacked_sint64_extension_lite = 95;
repeated fixed32 unpacked_fixed32_extension_lite = 96;
repeated fixed64 unpacked_fixed64_extension_lite = 97;
repeated sfixed32 unpacked_sfixed32_extension_lite = 98;
repeated sfixed64 unpacked_sfixed64_extension_lite = 99;
repeated float unpacked_float_extension_lite = 100;
repeated double unpacked_double_extension_lite = 101;
repeated bool unpacked_bool_extension_lite = 102;
repeated UnpackedTypesForeignEnumLite unpacked_enum_extension_lite = 103;
}
enum UnpackedTypesForeignEnumLite {
FOREIGN_LITE_FOO = 4;
FOREIGN_LITE_BAR = 5;
FOREIGN_LITE_BAZ = 6;
}
message BucketOfBytes {
optional bytes value = 1;
}
message BucketOfBytesEx {
optional bytes value = 1;
optional bytes value2 = 255;
}

@ -0,0 +1,54 @@
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestXmlSerializerTestProtoFile";
option (google.protobuf.csharp_file_options).add_serializable = true;
package protobuf_unittest_extra;
option optimize_for = SPEED;
enum EnumOptions {
ONE = 0;
TWO = 1;
THREE = 2;
}
message TestXmlChild {
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
message TestXmlNoFields {
}
message TestXmlRescursive {
optional TestXmlRescursive child = 1;
}
message TestXmlMessage {
optional int64 number = 6;
repeated int32 numbers = 2;
optional string text = 3;
repeated string textlines = 700;
optional bool valid = 5;
optional TestXmlChild child = 1;
repeated group Children = 401 {
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
extensions 100 to 199;
}
message TestXmlExtension {
required int32 number = 1;
}
extend TestXmlMessage {
optional EnumOptions extension_enum = 101;
optional string extension_text = 102;
repeated int32 extension_number = 103 [packed = true];
optional TestXmlExtension extension_message = 199;
}

@ -0,0 +1,29 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
import "google/protobuf/unittest.proto";
import "google/protobuf/unittest_custom_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestGenericServices";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
package protobuf_unittest;
option optimize_for = SPEED;
service TestGenericService {
rpc Foo(FooRequest) returns (FooResponse);
rpc Bar(BarRequest) returns (BarResponse);
}
service TestGenericServiceWithCustomOptions {
option (service_opt1) = -9876543210;
rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
option (method_opt1) = METHODOPT1_VAL2;
}
}

@ -0,0 +1,137 @@
// These proto descriptors have at one time been reported as an issue or defect.
// They are kept here to replicate the issue, and continue to verify the fix.
import "google/protobuf/csharp_options.proto";
// Issue: Non-"Google.Protobuffers" namespace will ensure that protobuffer library types are qualified
option (google.protobuf.csharp_file_options).namespace = "UnitTest.Issues.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasIssuesProtoFile";
package unittest_issues;
option optimize_for = SPEED;
// The following is a representative set of features
/*
enum EnumOptions {
ONE = 0;
TWO = 1;
THREE = 2;
}
message TestBasicChild
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
message TestBasicNoFields {
}
message TestBasicRescursive {
optional TestBasicRescursive child = 1;
}
message TestBasicMessage {
optional int64 number = 6;
repeated int32 numbers = 2;
optional string text = 3;
repeated string textlines = 700;
optional bool valid = 5;
optional TestBasicChild child = 1;
repeated group Children = 401
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
extensions 100 to 199;
}
message TestBasicExtension {
required int32 number = 1;
}
extend TestBasicMessage {
optional EnumOptions extension_enum = 101;
optional string extension_text = 102;
repeated int32 extension_number = 103 [packed = true];
optional TestBasicExtension extension_message = 199;
}
// Issue for non-qualified type reference in new services generation
option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH;
service TestGenericService {
rpc Foo(TestBasicNoFields) returns (TestBasicMessage);
rpc Bar(TestBasicNoFields) returns (TestBasicMessage);
}
*/
// Issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13
message A {
optional int32 _A = 1;
}
message B {
optional int32 B_ = 1;
}
message AB {
optional int32 a_b = 1;
}
// Similar issue with numeric names
message NumberField {
optional int32 _01 = 1;
}
// Issue 28: Circular message dependencies result in null defaults for DefaultInstance
message MyMessageAReferenceB {
required MyMessageBReferenceA value = 1;
}
message MyMessageBReferenceA {
required MyMessageAReferenceB value = 1;
}
// issue 19 - negative enum values
enum NegativeEnum {
FiveBelow = -5;
MinusOne = -1;
Zero = 0;
}
message NegativeEnumMessage {
optional NegativeEnum value = 1;
repeated NegativeEnum values = 2;
repeated NegativeEnum packed_values = 3 [packed=true];
}
// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21
// Decorate fields with [deprecated=true] as [System.Obsolete]
message DeprecatedChild {
}
enum DeprecatedEnum {
one = 1;
}
message DeprecatedFieldsMessage {
optional int32 PrimitiveValue = 1 [deprecated = true];
repeated int32 PrimitiveArray = 2 [deprecated = true];
optional DeprecatedChild MessageValue = 3 [deprecated = true];
repeated DeprecatedChild MessageArray = 4 [deprecated = true];
optional DeprecatedEnum EnumValue = 5 [deprecated = true];
repeated DeprecatedEnum EnumArray = 6 [deprecated = true];
}
// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
message ItemField {
optional int32 item = 1;
}

@ -0,0 +1,41 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestRpcInterop";
option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH;
option optimize_for = SPEED;
message SearchRequest {
repeated string Criteria = 1;
}
message SearchResponse {
message ResultItem {
required string url = 1;
optional string name = 2;
}
repeated ResultItem results = 1;
}
message RefineSearchRequest {
repeated string Criteria = 1;
required SearchResponse previous_results = 2;
}
service SearchService {
/*
Add this option to specify the GuidAttribute on the service interface
option (google.protobuf.csharp_service_options).interface_id = "{A65F0925-FD11-4f94-B166-89AC4F027205}";
*/
rpc Search (SearchRequest) returns (SearchResponse)
/*
Add this option to specify the DispIdAttribute on the service interface
{ option (google.protobuf.csharp_method_options).dispatch_id = 5; }
*/ ;
rpc RefineSearch (RefineSearchRequest) returns (SearchResponse);
}

@ -0,0 +1,42 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestRpcInteropLite";
option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH;
option optimize_for = LITE_RUNTIME;
package unittest_rpc_interop_lite;
message SearchRequest {
repeated string Criteria = 1;
}
message SearchResponse {
message ResultItem {
required string url = 1;
optional string name = 2;
}
repeated ResultItem results = 1;
}
message RefineSearchRequest {
repeated string Criteria = 1;
required SearchResponse previous_results = 2;
}
service SearchService {
/*
Add this option to specify the GuidAttribute on the service interface
option (google.protobuf.csharp_service_options).interface_id = "{A65F0925-FD11-4f94-B166-89AC4F027205}";
*/
rpc Search (SearchRequest) returns (SearchResponse)
/*
Add this option to specify the DispIdAttribute on the service interface
{ option (google.protobuf.csharp_method_options).dispatch_id = 5; }
*/ ;
rpc RefineSearch (RefineSearchRequest) returns (SearchResponse);
}

@ -0,0 +1,147 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
// change.
//
// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
// just a program that reads a CodeGeneratorRequest from stdin and writes a
// CodeGeneratorResponse to stdout.
//
// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
// of dealing with the raw protocol defined here.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "protoc-gen-$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to protoc.
package google.protobuf.compiler;
option java_package = "com.google.protobuf.compiler";
option java_outer_classname = "PluginProtos";
import "google/protobuf/descriptor.proto";
// An encoded CodeGeneratorRequest is written to the plugin's stdin.
message CodeGeneratorRequest {
// The .proto files that were explicitly listed on the command-line. The
// code generator should generate code only for these files. Each file's
// descriptor will be included in proto_file, below.
repeated string file_to_generate = 1;
// The generator parameter passed on the command-line.
optional string parameter = 2;
// FileDescriptorProtos for all files in files_to_generate and everything
// they import. The files will appear in topological order, so each file
// appears before any file that imports it.
//
// protoc guarantees that all proto_files will be written after
// the fields above, even though this is not technically guaranteed by the
// protobuf wire format. This theoretically could allow a plugin to stream
// in the FileDescriptorProtos and handle them one by one rather than read
// the entire set into memory at once. However, as of this writing, this
// is not similarly optimized on protoc's end -- it will store all fields in
// memory at once before sending them to the plugin.
repeated FileDescriptorProto proto_file = 15;
}
// The plugin writes an encoded CodeGeneratorResponse to stdout.
message CodeGeneratorResponse {
// Error message. If non-empty, code generation failed. The plugin process
// should exit with status code zero even if it reports an error in this way.
//
// This should be used to indicate errors in .proto files which prevent the
// code generator from generating correct code. Errors which indicate a
// problem in protoc itself -- such as the input CodeGeneratorRequest being
// unparseable -- should be reported by writing a message to stderr and
// exiting with a non-zero status code.
optional string error = 1;
// Represents a single generated file.
message File {
// The file name, relative to the output directory. The name must not
// contain "." or ".." components and must be relative, not be absolute (so,
// the file cannot lie outside the output directory). "/" must be used as
// the path separator, not "\".
//
// If the name is omitted, the content will be appended to the previous
// file. This allows the generator to break large files into small chunks,
// and allows the generated text to be streamed back to protoc so that large
// files need not reside completely in memory at one time. Note that as of
// this writing protoc does not optimize for this -- it will read the entire
// CodeGeneratorResponse before writing files to disk.
optional string name = 1;
// If non-empty, indicates that the named file should already exist, and the
// content here is to be inserted into that file at a defined insertion
// point. This feature allows a code generator to extend the output
// produced by another code generator. The original generator may provide
// insertion points by placing special annotations in the file that look
// like:
// @@protoc_insertion_point(NAME)
// The annotation can have arbitrary text before and after it on the line,
// which allows it to be placed in a comment. NAME should be replaced with
// an identifier naming the point -- this is what other generators will use
// as the insertion_point. Code inserted at this point will be placed
// immediately above the line containing the insertion point (thus multiple
// insertions to the same point will come out in the order they were added).
// The double-@ is intended to make it unlikely that the generated code
// could contain things that look like insertion points by accident.
//
// For example, the C++ code generator places the following line in the
// .pb.h files that it generates:
// // @@protoc_insertion_point(namespace_scope)
// This line appears within the scope of the file's package namespace, but
// outside of any particular class. Another plugin can then specify the
// insertion_point "namespace_scope" to generate additional classes or
// other declarations that should be placed in this scope.
//
// Note that if the line containing the insertion point begins with
// whitespace, the same whitespace will be added to every line of the
// inserted text. This is useful for languages like Python, where
// indentation matters. In these languages, the insertion point comment
// should be indented the same amount as any inserted code will need to be
// in order to work correctly in that context.
//
// The code generator that generates the initial file and the one which
// inserts into it must both run as part of a single invocation of protoc.
// Code generators are executed in the order in which they appear on the
// command line.
//
// If |insertion_point| is present, |name| must also be present.
optional string insertion_point = 2;
// The file contents.
optional string content = 15;
}
repeated File file = 15;
}

@ -0,0 +1,115 @@
// Extra options for C# generator
import "google/protobuf/descriptor.proto";
package google.protobuf;
message CSharpFileOptions {
// Namespace for generated classes; defaults to the package.
optional string namespace = 1;
// Name of the "umbrella" class used for metadata about all
// the messages within this file. Default is based on the name
// of the file.
optional string umbrella_classname = 2;
// Whether classes should be public (true) or internal (false)
optional bool public_classes = 3 [default = true];
// Whether to generate a single file for everything within the
// .proto file (false), or one file per message (true).
// This option is not currently honored; please log a feature
// request if you really want it.
optional bool multiple_files = 4;
// Whether to nest messages within a single umbrella class (true)
// or create the umbrella class as a peer, with messages as
// top-level classes in the namespace (false)
optional bool nest_classes = 5;
// Generate appropriate support for Code Contracts
// (Ongoing; support should improve over time)
optional bool code_contracts = 6;
// Create subdirectories for namespaces, e.g. namespace "Foo.Bar"
// would generate files within [output directory]/Foo/Bar
optional bool expand_namespace_directories = 7;
// Generate attributes indicating non-CLS-compliance
optional bool cls_compliance = 8 [default = true];
// Generate messages/builders with the [Serializable] attribute
optional bool add_serializable = 9 [default = false];
// Generates a private ctor for Message types
optional bool generate_private_ctor = 10 [default = true];
// The extension that should be appended to the umbrella_classname when creating files.
optional string file_extension = 221 [default = ".cs"];
// A nested namespace for the umbrella class. Helpful for name collisions caused by
// umbrella_classname conflicting with an existing type. This will be automatically
// set to 'Proto' if a collision is detected with types being generated. This value
// is ignored when nest_classes == true
optional string umbrella_namespace = 222;
// The output path for the source file(s) generated
optional string output_directory = 223 [default = "."];
// Will ignore the type generations and remove dependencies for the descriptor proto
// files that declare their package to be "google.protobuf"
optional bool ignore_google_protobuf = 224 [default = false];
// Controls how services are generated, GENERIC is the deprecated original implementation
// INTERFACE generates service interfaces only, RPCINTEROP generates interfaces and
// implementations using the included Windows RPC interop libarary.
optional CSharpServiceType service_generator_type = 225 [default = NONE];
// Used to add the System.Runtime.CompilerServices.CompilerGeneratedAttribute and
// System.CodeDom.Compiler.GeneratedCodeAttribute attributes to generated code.
optional bool generated_code_attributes = 226 [default = false];
}
enum CSharpServiceType {
// Services are ignored by the generator
NONE = 0;
// Generates the original Java generic service implementations
GENERIC = 1;
// Generates an interface for the service and nothing else
INTERFACE = 2;
// Generates an interface for the service and client/server wrappers for the interface
IRPCDISPATCH = 3;
}
extend FileOptions {
optional CSharpFileOptions csharp_file_options = 1000;
}
extend FieldOptions {
optional CSharpFieldOptions csharp_field_options = 1000;
}
message CSharpFieldOptions {
// Provides the ability to override the name of the property
// generated for this field. This is applied to all properties
// and methods to do with this field, including HasFoo, FooCount,
// FooList etc.
optional string property_name = 1;
}
message CSharpServiceOptions {
optional string interface_id = 1;
}
extend ServiceOptions {
optional CSharpServiceOptions csharp_service_options = 1000;
}
message CSharpMethodOptions {
optional int32 dispatch_id = 1;
}
extend MethodOptions {
optional CSharpMethodOptions csharp_method_options = 1000;
}

@ -0,0 +1,533 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// The messages in this file describe the definitions found in .proto files.
// A valid .proto file can be translated directly to a FileDescriptorProto
// without any other information (e.g. without reading its imports).
package google.protobuf;
option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
option optimize_for = SPEED;
// The protocol compiler can output a FileDescriptorSet containing the .proto
// files it parses.
message FileDescriptorSet {
repeated FileDescriptorProto file = 1;
}
// Describes a complete .proto file.
message FileDescriptorProto {
optional string name = 1; // file name, relative to root of source tree
optional string package = 2; // e.g. "foo", "foo.bar", etc.
// Names of files imported by this file.
repeated string dependency = 3;
// All top-level definitions in this file.
repeated DescriptorProto message_type = 4;
repeated EnumDescriptorProto enum_type = 5;
repeated ServiceDescriptorProto service = 6;
repeated FieldDescriptorProto extension = 7;
optional FileOptions options = 8;
// This field contains optional information about the original source code.
// You may safely remove this entire field whithout harming runtime
// functionality of the descriptors -- the information is needed only by
// development tools.
optional SourceCodeInfo source_code_info = 9;
}
// Describes a message type.
message DescriptorProto {
optional string name = 1;
repeated FieldDescriptorProto field = 2;
repeated FieldDescriptorProto extension = 6;
repeated DescriptorProto nested_type = 3;
repeated EnumDescriptorProto enum_type = 4;
message ExtensionRange {
optional int32 start = 1;
optional int32 end = 2;
}
repeated ExtensionRange extension_range = 5;
optional MessageOptions options = 7;
}
// Describes a field within a message.
message FieldDescriptorProto {
enum Type {
// 0 is reserved for errors.
// Order is weird for historical reasons.
TYPE_DOUBLE = 1;
TYPE_FLOAT = 2;
TYPE_INT64 = 3; // Not ZigZag encoded. Negative numbers
// take 10 bytes. Use TYPE_SINT64 if negative
// values are likely.
TYPE_UINT64 = 4;
TYPE_INT32 = 5; // Not ZigZag encoded. Negative numbers
// take 10 bytes. Use TYPE_SINT32 if negative
// values are likely.
TYPE_FIXED64 = 6;
TYPE_FIXED32 = 7;
TYPE_BOOL = 8;
TYPE_STRING = 9;
TYPE_GROUP = 10; // Tag-delimited aggregate.
TYPE_MESSAGE = 11; // Length-delimited aggregate.
// New in version 2.
TYPE_BYTES = 12;
TYPE_UINT32 = 13;
TYPE_ENUM = 14;
TYPE_SFIXED32 = 15;
TYPE_SFIXED64 = 16;
TYPE_SINT32 = 17; // Uses ZigZag encoding.
TYPE_SINT64 = 18; // Uses ZigZag encoding.
};
enum Label {
// 0 is reserved for errors
LABEL_OPTIONAL = 1;
LABEL_REQUIRED = 2;
LABEL_REPEATED = 3;
// TODO(sanjay): Should we add LABEL_MAP?
};
optional string name = 1;
optional int32 number = 3;
optional Label label = 4;
// If type_name is set, this need not be set. If both this and type_name
// are set, this must be either TYPE_ENUM or TYPE_MESSAGE.
optional Type type = 5;
// For message and enum types, this is the name of the type. If the name
// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
// rules are used to find the type (i.e. first the nested types within this
// message are searched, then within the parent, on up to the root
// namespace).
optional string type_name = 6;
// For extensions, this is the name of the type being extended. It is
// resolved in the same manner as type_name.
optional string extendee = 2;
// For numeric types, contains the original text representation of the value.
// For booleans, "true" or "false".
// For strings, contains the default text contents (not escaped in any way).
// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
// TODO(kenton): Base-64 encode?
optional string default_value = 7;
optional FieldOptions options = 8;
}
// Describes an enum type.
message EnumDescriptorProto {
optional string name = 1;
repeated EnumValueDescriptorProto value = 2;
optional EnumOptions options = 3;
}
// Describes a value within an enum.
message EnumValueDescriptorProto {
optional string name = 1;
optional int32 number = 2;
optional EnumValueOptions options = 3;
}
// Describes a service.
message ServiceDescriptorProto {
optional string name = 1;
repeated MethodDescriptorProto method = 2;
optional ServiceOptions options = 3;
}
// Describes a method of a service.
message MethodDescriptorProto {
optional string name = 1;
// Input and output type names. These are resolved in the same way as
// FieldDescriptorProto.type_name, but must refer to a message type.
optional string input_type = 2;
optional string output_type = 3;
optional MethodOptions options = 4;
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail kenton@google.com to reserve extension
// numbers. Simply tell me how many you need and I'll send you back a
// set of numbers to use -- there's no need to explain how you intend to
// use them. If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
message FileOptions {
// Sets the Java package where classes generated from this .proto will be
// placed. By default, the proto package is used, but this is often
// inappropriate because proto packages do not normally start with backwards
// domain names.
optional string java_package = 1;
// If set, all the classes from the .proto file are wrapped in a single
// outer class with the given name. This applies to both Proto1
// (equivalent to the old "--one_java_file" option) and Proto2 (where
// a .proto always translates to a single class, but you may want to
// explicitly choose the class name).
optional string java_outer_classname = 8;
// If set true, then the Java code generator will generate a separate .java
// file for each top-level message, enum, and service defined in the .proto
// file. Thus, these types will *not* be nested inside the outer class
// named by java_outer_classname. However, the outer class will still be
// generated to contain the file's getDescriptor() method as well as any
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default=false];
// If set true, then the Java code generator will generate equals() and
// hashCode() methods for all messages defined in the .proto file. This is
// purely a speed optimization, as the AbstractMessage base class includes
// reflection-based implementations of these methods.
optional bool java_generate_equals_and_hash = 20 [default=false];
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default=SPEED];
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of proto2.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. Therefore,
// these default to false. Old code which depends on generic services should
// explicitly set them to true.
optional bool cc_generic_services = 16 [default=false];
optional bool java_generic_services = 17 [default=false];
optional bool py_generic_services = 18 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MessageOptions {
// Set true to use the old proto1 MessageSet wire format for extensions.
// This is provided for backwards-compatibility with the MessageSet wire
// format. You should not use this for any other reason: It's less
// efficient, has fewer features, and is more complicated.
//
// The message must be defined exactly as follows:
// message Foo {
// option message_set_wire_format = true;
// extensions 4 to max;
// }
// Note that the message cannot have any defined fields; MessageSets only
// have extensions.
//
// All extensions of your type must be singular messages; e.g. they cannot
// be int32s, enums, or repeated messages.
//
// Because this is an option, the above two restrictions are not enforced by
// the protocol compiler.
optional bool message_set_wire_format = 1 [default=false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message FieldOptions {
// The ctype option instructs the C++ code generator to use a different
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
}
// The packed option can be enabled for repeated primitive fields to enable
// a more efficient representation on the wire. Rather than repeatedly
// writing the tag and type for each element, the entire array is encoded as
// a single length-delimited blob.
optional bool packed = 2;
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false];
// EXPERIMENTAL. DO NOT USE.
// For "map" fields, the name of the field in the enclosed type that
// is the key for this map. For example, suppose we have:
// message Item {
// required string name = 1;
// required string value = 2;
// }
// message Config {
// repeated Item items = 1 [experimental_map_key="name"];
// }
// In this situation, the map key for Item will be set to "name".
// TODO: Fully-implement this, then remove the "experimental_" prefix.
optional string experimental_map_key = 9;
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message EnumValueOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
message MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
}
// A message representing a option the parser does not recognize. This only
// appears in options protos created by the compiler::Parser class.
// DescriptorPool resolves these when building Descriptor objects. Therefore,
// options protos in descriptor objects (e.g. returned by Descriptor::options(),
// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
// in them.
message UninterpretedOption {
// The name of the uninterpreted option. Each string represents a segment in
// a dot-separated name. is_extension is true iff a segment represents an
// extension (denoted with parentheses in options specs in .proto files).
// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
// "foo.(bar.baz).qux".
message NamePart {
required string name_part = 1;
required bool is_extension = 2;
}
repeated NamePart name = 2;
// The value of the uninterpreted option, in whatever type the tokenizer
// identified it as during parsing. Exactly one of these should be set.
optional string identifier_value = 3;
optional uint64 positive_int_value = 4;
optional int64 negative_int_value = 5;
optional double double_value = 6;
optional bytes string_value = 7;
optional string aggregate_value = 8;
}
// ===================================================================
// Optional source code info
// Encapsulates information about the original source file from which a
// FileDescriptorProto was generated.
message SourceCodeInfo {
// A Location identifies a piece of source code in a .proto file which
// corresponds to a particular definition. This information is intended
// to be useful to IDEs, code indexers, documentation generators, and similar
// tools.
//
// For example, say we have a file like:
// message Foo {
// optional string foo = 1;
// }
// Let's look at just the field definition:
// optional string foo = 1;
// ^ ^^ ^^ ^ ^^^
// a bc de f ghi
// We have the following locations:
// span path represents
// [a,i) [ 4, 0, 2, 0 ] The whole field definition.
// [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
// [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
// [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
// [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
//
// Notes:
// - A location may refer to a repeated field itself (i.e. not to any
// particular index within it). This is used whenever a set of elements are
// logically enclosed in a single code segment. For example, an entire
// extend block (possibly containing multiple extension definitions) will
// have an outer location whose path refers to the "extensions" repeated
// field without an index.
// - Multiple locations may have the same path. This happens when a single
// logical declaration is spread out across multiple places. The most
// obvious example is the "extend" block again -- there may be multiple
// extend blocks in the same scope, each of which will have the same path.
// - A location's span is not always a subset of its parent's span. For
// example, the "extendee" of an extension declaration appears at the
// beginning of the "extend" block and is shared by all extensions within
// the block.
// - Just because a location's span is a subset of some other location's span
// does not mean that it is a descendent. For example, a "group" defines
// both a type and a field in a single declaration. Thus, the locations
// corresponding to the type and field and their components will overlap.
// - Code which tries to interpret locations should probably be designed to
// ignore those that it doesn't understand, as more types of locations could
// be recorded in the future.
repeated Location location = 1;
message Location {
// Identifies which part of the FileDescriptorProto was defined at this
// location.
//
// Each element is a field number or an index. They form a path from
// the root FileDescriptorProto to the place where the definition. For
// example, this path:
// [ 4, 3, 2, 7, 1 ]
// refers to:
// file.message_type(3) // 4, 3
// .field(7) // 2, 7
// .name() // 1
// This is because FileDescriptorProto.message_type has field number 4:
// repeated DescriptorProto message_type = 4;
// and DescriptorProto.field has field number 2:
// repeated FieldDescriptorProto field = 2;
// and FieldDescriptorProto.name has field number 1:
// optional string name = 1;
//
// Thus, the above path gives the location of a field name. If we removed
// the last element:
// [ 4, 3, 2, 7 ]
// this path refers to the whole field declaration (from the beginning
// of the label to the terminating semicolon).
repeated int32 path = 1 [packed=true];
// Always has exactly three or four elements: start line, start column,
// end line (optional, otherwise assumed same as start line), end column.
// These are packed into a single field for efficiency. Note that line
// and column numbers are zero-based -- typically you will want to add
// 1 to each before displaying to a user.
repeated int32 span = 2 [packed=true];
// TODO(kenton): Record comments appearing before and after the
// declaration.
}
}

@ -0,0 +1,636 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file we will use for unit testing.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true; // auto-added
import "google/protobuf/unittest_import.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do "using namespace unittest = protobuf_unittest".
package protobuf_unittest;
// Protos optimized for SPEED use a strict superset of the generated code
// of equivalent ones optimized for CODE_SIZE, so we should optimize all our
// tests for speed unless explicitly testing code size optimization.
option optimize_for = SPEED;
option java_outer_classname = "UnittestProto";
// This proto includes every type of field in both singular and repeated
// forms.
message TestAllTypes {
message NestedMessage {
// The field name "b" fails to compile in proto1 because it conflicts with
// a local variable named "b" in one of the generated methods. Doh.
// This file needs to compile in proto1 to test backwards-compatibility.
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessage optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessage optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnum optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnum optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessage repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnum repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR ];
optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum = 83 [default = IMPORT_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
}
// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
optional int32 c = 1;
}
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
message TestAllExtensions {
extensions 1 to max;
}
extend TestAllExtensions {
// Singular
optional int32 optional_int32_extension = 1;
optional int64 optional_int64_extension = 2;
optional uint32 optional_uint32_extension = 3;
optional uint64 optional_uint64_extension = 4;
optional sint32 optional_sint32_extension = 5;
optional sint64 optional_sint64_extension = 6;
optional fixed32 optional_fixed32_extension = 7;
optional fixed64 optional_fixed64_extension = 8;
optional sfixed32 optional_sfixed32_extension = 9;
optional sfixed64 optional_sfixed64_extension = 10;
optional float optional_float_extension = 11;
optional double optional_double_extension = 12;
optional bool optional_bool_extension = 13;
optional string optional_string_extension = 14;
optional bytes optional_bytes_extension = 15;
optional group OptionalGroup_extension = 16 {
optional int32 a = 17;
}
optional TestAllTypes.NestedMessage optional_nested_message_extension = 18;
optional ForeignMessage optional_foreign_message_extension = 19;
optional protobuf_unittest_import.ImportMessage
optional_import_message_extension = 20;
optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21;
optional ForeignEnum optional_foreign_enum_extension = 22;
optional protobuf_unittest_import.ImportEnum
optional_import_enum_extension = 23;
optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE];
optional string optional_cord_extension = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32_extension = 31;
repeated int64 repeated_int64_extension = 32;
repeated uint32 repeated_uint32_extension = 33;
repeated uint64 repeated_uint64_extension = 34;
repeated sint32 repeated_sint32_extension = 35;
repeated sint64 repeated_sint64_extension = 36;
repeated fixed32 repeated_fixed32_extension = 37;
repeated fixed64 repeated_fixed64_extension = 38;
repeated sfixed32 repeated_sfixed32_extension = 39;
repeated sfixed64 repeated_sfixed64_extension = 40;
repeated float repeated_float_extension = 41;
repeated double repeated_double_extension = 42;
repeated bool repeated_bool_extension = 43;
repeated string repeated_string_extension = 44;
repeated bytes repeated_bytes_extension = 45;
repeated group RepeatedGroup_extension = 46 {
optional int32 a = 47;
}
repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48;
repeated ForeignMessage repeated_foreign_message_extension = 49;
repeated protobuf_unittest_import.ImportMessage
repeated_import_message_extension = 50;
repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51;
repeated ForeignEnum repeated_foreign_enum_extension = 52;
repeated protobuf_unittest_import.ImportEnum
repeated_import_enum_extension = 53;
repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE];
repeated string repeated_cord_extension = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32_extension = 61 [default = 41 ];
optional int64 default_int64_extension = 62 [default = 42 ];
optional uint32 default_uint32_extension = 63 [default = 43 ];
optional uint64 default_uint64_extension = 64 [default = 44 ];
optional sint32 default_sint32_extension = 65 [default = -45 ];
optional sint64 default_sint64_extension = 66 [default = 46 ];
optional fixed32 default_fixed32_extension = 67 [default = 47 ];
optional fixed64 default_fixed64_extension = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension = 70 [default = -50 ];
optional float default_float_extension = 71 [default = 51.5 ];
optional double default_double_extension = 72 [default = 52e3 ];
optional bool default_bool_extension = 73 [default = true ];
optional string default_string_extension = 74 [default = "hello"];
optional bytes default_bytes_extension = 75 [default = "world"];
optional TestAllTypes.NestedEnum
default_nested_enum_extension = 81 [default = BAR];
optional ForeignEnum
default_foreign_enum_extension = 82 [default = FOREIGN_BAR];
optional protobuf_unittest_import.ImportEnum
default_import_enum_extension = 83 [default = IMPORT_BAR];
optional string default_string_piece_extension = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension = 85 [ctype=CORD, default="123"];
}
message TestNestedExtension {
extend TestAllExtensions {
// Check for bug where string extensions declared in tested scope did not
// compile.
optional string test = 1002 [default="test"];
}
}
// We have separate messages for testing required fields because it's
// annoying to have to fill in required fields in TestProto in order to
// do anything with it. Note that we don't need to test every type of
// required filed because the code output is basically identical to
// optional fields for all types.
message TestRequired {
required int32 a = 1;
optional int32 dummy2 = 2;
required int32 b = 3;
extend TestAllExtensions {
optional TestRequired single = 1000;
repeated TestRequired multi = 1001;
}
// Pad the field count to 32 so that we can test that IsInitialized()
// properly checks multiple elements of has_bits_.
optional int32 dummy4 = 4;
optional int32 dummy5 = 5;
optional int32 dummy6 = 6;
optional int32 dummy7 = 7;
optional int32 dummy8 = 8;
optional int32 dummy9 = 9;
optional int32 dummy10 = 10;
optional int32 dummy11 = 11;
optional int32 dummy12 = 12;
optional int32 dummy13 = 13;
optional int32 dummy14 = 14;
optional int32 dummy15 = 15;
optional int32 dummy16 = 16;
optional int32 dummy17 = 17;
optional int32 dummy18 = 18;
optional int32 dummy19 = 19;
optional int32 dummy20 = 20;
optional int32 dummy21 = 21;
optional int32 dummy22 = 22;
optional int32 dummy23 = 23;
optional int32 dummy24 = 24;
optional int32 dummy25 = 25;
optional int32 dummy26 = 26;
optional int32 dummy27 = 27;
optional int32 dummy28 = 28;
optional int32 dummy29 = 29;
optional int32 dummy30 = 30;
optional int32 dummy31 = 31;
optional int32 dummy32 = 32;
required int32 c = 33;
}
message TestRequiredForeign {
optional TestRequired optional_message = 1;
repeated TestRequired repeated_message = 2;
optional int32 dummy = 3;
}
// Test that we can use NestedMessage from outside TestAllTypes.
message TestForeignNested {
optional TestAllTypes.NestedMessage foreign_nested = 1;
}
// TestEmptyMessage is used to test unknown field support.
message TestEmptyMessage {
}
// Like above, but declare all field numbers as potential extensions. No
// actual extensions should ever be defined for this type.
message TestEmptyMessageWithExtensions {
extensions 1 to max;
}
message TestMultipleExtensionRanges {
extensions 42;
extensions 4143 to 4243;
extensions 65536 to max;
}
// Test that really large tag numbers don't break anything.
message TestReallyLargeTagNumber {
// The largest possible tag number is 2^28 - 1, since the wire format uses
// three bits to communicate wire type.
optional int32 a = 1;
optional int32 bb = 268435455;
}
message TestRecursiveMessage {
optional TestRecursiveMessage a = 1;
optional int32 i = 2;
}
// Test that mutual recursion works.
message TestMutualRecursionA {
optional TestMutualRecursionB bb = 1;
}
message TestMutualRecursionB {
optional TestMutualRecursionA a = 1;
optional int32 optional_int32 = 2;
}
// Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only proto2. When attempting
// to compile with proto1, this will emit an error; so we only include it
// in protobuf_unittest_proto.
message TestDupFieldNumber { // NO_PROTO1
optional int32 a = 1; // NO_PROTO1
optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1
optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1
} // NO_PROTO1
// Needed for a Python test.
message TestNestedMessageHasBits {
message NestedMessage {
repeated int32 nestedmessage_repeated_int32 = 1;
repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2;
}
optional NestedMessage optional_nested_message = 1;
}
// Test an enum that has multiple values with the same number.
enum TestEnumWithDupValue {
FOO1 = 1;
BAR1 = 2;
BAZ = 3;
FOO2 = 1;
BAR2 = 2;
}
// Test an enum with large, unordered values.
enum TestSparseEnum {
SPARSE_A = 123;
SPARSE_B = 62374;
SPARSE_C = 12589234;
SPARSE_D = -15;
SPARSE_E = -53452;
SPARSE_F = 0;
SPARSE_G = 2;
}
// Test message with CamelCase field names. This violates Protocol Buffer
// standard style.
message TestCamelCaseFieldNames {
optional int32 PrimitiveField = 1;
optional string StringField = 2;
optional ForeignEnum EnumField = 3;
optional ForeignMessage MessageField = 4;
optional string StringPieceField = 5 [ctype=STRING_PIECE];
optional string CordField = 6 [ctype=CORD];
repeated int32 RepeatedPrimitiveField = 7;
repeated string RepeatedStringField = 8;
repeated ForeignEnum RepeatedEnumField = 9;
repeated ForeignMessage RepeatedMessageField = 10;
repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE];
repeated string RepeatedCordField = 12 [ctype=CORD];
}
// We list fields out of order, to ensure that we're using field number and not
// field index to determine serialization order.
message TestFieldOrderings {
optional string my_string = 11;
extensions 2 to 10;
optional int64 my_int = 1;
extensions 12 to 100;
optional float my_float = 101;
}
extend TestFieldOrderings {
optional string my_extension_string = 50;
optional int32 my_extension_int = 5;
}
message TestExtremeDefaultValues {
optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"];
optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF];
optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF];
optional int32 small_int32 = 4 [default = -0x7FFFFFFF];
optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF];
// The default value here is UTF-8 for "\u1234". (We could also just type
// the UTF-8 text directly into this text file rather than escape it, but
// lots of people use editors that would be confused by this.)
optional string utf8_string = 6 [default = "\341\210\264"];
// Tests for single-precision floating-point values.
optional float zero_float = 7 [default = 0];
optional float one_float = 8 [default = 1];
optional float small_float = 9 [default = 1.5];
optional float negative_one_float = 10 [default = -1];
optional float negative_float = 11 [default = -1.5];
// Using exponents
optional float large_float = 12 [default = 2E8];
optional float small_negative_float = 13 [default = -8e-28];
// Text for nonfinite floating-point values.
optional double inf_double = 14 [default = inf];
optional double neg_inf_double = 15 [default = -inf];
optional double nan_double = 16 [default = nan];
optional float inf_float = 17 [default = inf];
optional float neg_inf_float = 18 [default = -inf];
optional float nan_float = 19 [default = nan];
// Tests for C++ trigraphs.
// Trigraphs should be escaped in C++ generated files, but they should not be
// escaped for other languages.
// Note that in .proto file, "\?" is a valid way to escape ? in string
// literals.
optional string cpp_trigraph = 20 [default = "? \? ?? \?? \??? ??/ ?\?-"];
}
message SparseEnumMessage {
optional TestSparseEnum sparse_enum = 1;
}
// Test String and Bytes: string is for valid UTF-8 strings
message OneString {
optional string data = 1;
}
message OneBytes {
optional bytes data = 1;
}
// Test messages for packed fields
message TestPackedTypes {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnum packed_enum = 103 [packed = true];
}
// A message with the same fields as TestPackedTypes, but without packing. Used
// to test packed <-> unpacked wire compatibility.
message TestUnpackedTypes {
repeated int32 unpacked_int32 = 90 [packed = false];
repeated int64 unpacked_int64 = 91 [packed = false];
repeated uint32 unpacked_uint32 = 92 [packed = false];
repeated uint64 unpacked_uint64 = 93 [packed = false];
repeated sint32 unpacked_sint32 = 94 [packed = false];
repeated sint64 unpacked_sint64 = 95 [packed = false];
repeated fixed32 unpacked_fixed32 = 96 [packed = false];
repeated fixed64 unpacked_fixed64 = 97 [packed = false];
repeated sfixed32 unpacked_sfixed32 = 98 [packed = false];
repeated sfixed64 unpacked_sfixed64 = 99 [packed = false];
repeated float unpacked_float = 100 [packed = false];
repeated double unpacked_double = 101 [packed = false];
repeated bool unpacked_bool = 102 [packed = false];
repeated ForeignEnum unpacked_enum = 103 [packed = false];
}
message TestPackedExtensions {
extensions 1 to max;
}
extend TestPackedExtensions {
repeated int32 packed_int32_extension = 90 [packed = true];
repeated int64 packed_int64_extension = 91 [packed = true];
repeated uint32 packed_uint32_extension = 92 [packed = true];
repeated uint64 packed_uint64_extension = 93 [packed = true];
repeated sint32 packed_sint32_extension = 94 [packed = true];
repeated sint64 packed_sint64_extension = 95 [packed = true];
repeated fixed32 packed_fixed32_extension = 96 [packed = true];
repeated fixed64 packed_fixed64_extension = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension = 99 [packed = true];
repeated float packed_float_extension = 100 [packed = true];
repeated double packed_double_extension = 101 [packed = true];
repeated bool packed_bool_extension = 102 [packed = true];
repeated ForeignEnum packed_enum_extension = 103 [packed = true];
}
// Used by ExtensionSetTest/DynamicExtensions. The test actually builds
// a set of extensions to TestAllExtensions dynamically, based on the fields
// of this message type.
message TestDynamicExtensions {
enum DynamicEnumType {
DYNAMIC_FOO = 2200;
DYNAMIC_BAR = 2201;
DYNAMIC_BAZ = 2202;
}
message DynamicMessageType {
optional int32 dynamic_field = 2100;
}
optional fixed32 scalar_extension = 2000;
optional ForeignEnum enum_extension = 2001;
optional DynamicEnumType dynamic_enum_extension = 2002;
optional ForeignMessage message_extension = 2003;
optional DynamicMessageType dynamic_message_extension = 2004;
repeated string repeated_extension = 2005;
repeated sint32 packed_extension = 2006 [packed = true];
}
message TestRepeatedScalarDifferentTagSizes {
// Parsing repeated fixed size values used to fail. This message needs to be
// used in order to get a tag of the right size; all of the repeated fields
// in TestAllTypes didn't trigger the check.
repeated fixed32 repeated_fixed32 = 12;
// Check for a varint type, just for good measure.
repeated int32 repeated_int32 = 13;
// These have two-byte tags.
repeated fixed64 repeated_fixed64 = 2046;
repeated int64 repeated_int64 = 2047;
// Three byte tags.
repeated float repeated_float = 262142;
repeated uint64 repeated_uint64 = 262143;
}
// Test that RPC services work.
message FooRequest {}
message FooResponse {}
service TestService {
rpc Foo(FooRequest) returns (FooResponse);
rpc Bar(BarRequest) returns (BarResponse);
}
message BarRequest {}
message BarResponse {}

@ -0,0 +1,52 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: jonskeet@google.com (Jon Skeet)
//
// A proto file for unit testing the custom C# options
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestCSharpOptionsProtoFile";
//option (google.protobuf.csharp_file_options).nest_classes = true;
package protobuf_unittest;
message OptionsMessage {
// Will be left as Normal
optional string normal = 1;
// Will be converted to OptionsMessage_
optional string options_message = 2;
// Will be converted to CustomName
optional string customized = 3 [(google.protobuf.csharp_field_options).property_name = "CustomName"];
}

@ -0,0 +1,372 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestCustomOptionsProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: benjy@google.com (Benjy Weinberger)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file used to test the "custom options" feature of proto2.
// Some generic_services option(s) added automatically.
// See: http://go/proto2-generic-services-default
option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added
option py_generic_services = true;
// A custom file option (defined below).
option (file_opt1) = 9876543210;
import "google/protobuf/descriptor.proto";
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
package protobuf_unittest;
// Some simple test custom options of various types.
extend google.protobuf.FileOptions {
optional uint64 file_opt1 = 7736974;
}
extend google.protobuf.MessageOptions {
optional int32 message_opt1 = 7739036;
}
extend google.protobuf.FieldOptions {
optional fixed64 field_opt1 = 7740936;
// This is useful for testing that we correctly register default values for
// extension options.
optional int32 field_opt2 = 7753913 [default=42];
}
extend google.protobuf.EnumOptions {
optional sfixed32 enum_opt1 = 7753576;
}
extend google.protobuf.EnumValueOptions {
optional int32 enum_value_opt1 = 1560678;
}
extend google.protobuf.ServiceOptions {
optional sint64 service_opt1 = 7887650;
}
enum MethodOpt1 {
METHODOPT1_VAL1 = 1;
METHODOPT1_VAL2 = 2;
}
extend google.protobuf.MethodOptions {
optional MethodOpt1 method_opt1 = 7890860;
}
// A test message with custom options at all possible locations (and also some
// regular options, to make sure they interact nicely).
message TestMessageWithCustomOptions {
option message_set_wire_format = false;
option (message_opt1) = -56;
optional string field1 = 1 [ctype=CORD,
(field_opt1)=8765432109];
enum AnEnum {
option (enum_opt1) = -789;
ANENUM_VAL1 = 1;
ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
}
}
// A test RPC service with custom options at all possible locations (and also
// some regular options, to make sure they interact nicely).
message CustomOptionFooRequest {
}
message CustomOptionFooResponse {
}
service TestServiceWithCustomOptions {
option (service_opt1) = -9876543210;
rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) {
option (method_opt1) = METHODOPT1_VAL2;
}
}
// Options of every possible field type, so we can test them all exhaustively.
message DummyMessageContainingEnum {
enum TestEnumType {
TEST_OPTION_ENUM_TYPE1 = 22;
TEST_OPTION_ENUM_TYPE2 = -23;
}
}
message DummyMessageInvalidAsOptionType {
}
extend google.protobuf.MessageOptions {
optional bool bool_opt = 7706090;
optional int32 int32_opt = 7705709;
optional int64 int64_opt = 7705542;
optional uint32 uint32_opt = 7704880;
optional uint64 uint64_opt = 7702367;
optional sint32 sint32_opt = 7701568;
optional sint64 sint64_opt = 7700863;
optional fixed32 fixed32_opt = 7700307;
optional fixed64 fixed64_opt = 7700194;
optional sfixed32 sfixed32_opt = 7698645;
optional sfixed64 sfixed64_opt = 7685475;
optional float float_opt = 7675390;
optional double double_opt = 7673293;
optional string string_opt = 7673285;
optional bytes bytes_opt = 7673238;
optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233;
optional DummyMessageInvalidAsOptionType message_type_opt = 7665967;
}
message CustomOptionMinIntegerValues {
option (bool_opt) = false;
option (int32_opt) = -0x80000000;
option (int64_opt) = -0x8000000000000000;
option (uint32_opt) = 0;
option (uint64_opt) = 0;
option (sint32_opt) = -0x80000000;
option (sint64_opt) = -0x8000000000000000;
option (fixed32_opt) = 0;
option (fixed64_opt) = 0;
option (sfixed32_opt) = -0x80000000;
option (sfixed64_opt) = -0x8000000000000000;
}
message CustomOptionMaxIntegerValues {
option (bool_opt) = true;
option (int32_opt) = 0x7FFFFFFF;
option (int64_opt) = 0x7FFFFFFFFFFFFFFF;
option (uint32_opt) = 0xFFFFFFFF;
option (uint64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sint32_opt) = 0x7FFFFFFF;
option (sint64_opt) = 0x7FFFFFFFFFFFFFFF;
option (fixed32_opt) = 0xFFFFFFFF;
option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF;
option (sfixed32_opt) = 0x7FFFFFFF;
option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF;
}
message CustomOptionOtherValues {
option (int32_opt) = -100; // To test sign-extension.
option (float_opt) = 12.3456789;
option (double_opt) = 1.234567890123456789;
option (string_opt) = "Hello, \"World\"";
option (bytes_opt) = "Hello\0World";
option (enum_opt) = TEST_OPTION_ENUM_TYPE2;
}
message SettingRealsFromPositiveInts {
option (float_opt) = 12;
option (double_opt) = 154;
}
message SettingRealsFromNegativeInts {
option (float_opt) = -12;
option (double_opt) = -154;
}
// Options of complex message types, themselves combined and extended in
// various ways.
message ComplexOptionType1 {
optional int32 foo = 1;
optional int32 foo2 = 2;
optional int32 foo3 = 3;
extensions 100 to max;
}
message ComplexOptionType2 {
optional ComplexOptionType1 bar = 1;
optional int32 baz = 2;
message ComplexOptionType4 {
optional int32 waldo = 1;
extend google.protobuf.MessageOptions {
optional ComplexOptionType4 complex_opt4 = 7633546;
}
}
optional ComplexOptionType4 fred = 3;
extensions 100 to max;
}
message ComplexOptionType3 {
optional int32 qux = 1;
optional group ComplexOptionType5 = 2 {
optional int32 plugh = 3;
}
}
extend ComplexOptionType1 {
optional int32 quux = 7663707;
optional ComplexOptionType3 corge = 7663442;
}
extend ComplexOptionType2 {
optional int32 grault = 7650927;
optional ComplexOptionType1 garply = 7649992;
}
extend google.protobuf.MessageOptions {
optional protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756;
optional ComplexOptionType2 complex_opt2 = 7636949;
optional ComplexOptionType3 complex_opt3 = 7636463;
optional group ComplexOpt6 = 7595468 {
optional int32 xyzzy = 7593951;
}
}
// Note that we try various different ways of naming the same extension.
message VariousComplexOptions {
option (.protobuf_unittest.complex_opt1).foo = 42;
option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324;
option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876;
option (complex_opt2).baz = 987;
option (complex_opt2).(grault) = 654;
option (complex_opt2).bar.foo = 743;
option (complex_opt2).bar.(quux) = 1999;
option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008;
option (complex_opt2).(garply).foo = 741;
option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998;
option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121;
option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971;
option (complex_opt2).fred.waldo = 321;
option (protobuf_unittest.complex_opt3).qux = 9;
option (complex_opt3).complexoptiontype5.plugh = 22;
option (complexopt6).xyzzy = 24;
}
// ------------------------------------------------------
// Definitions for testing aggregate option parsing.
// See descriptor_unittest.cc.
message AggregateMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message AggregateMessageSetElement {
extend AggregateMessageSet {
optional AggregateMessageSetElement message_set_extension = 15447542;
}
optional string s = 1;
}
// A helper type used to test aggregate option parsing
message Aggregate {
optional int32 i = 1;
optional string s = 2;
// A nested object
optional Aggregate sub = 3;
// To test the parsing of extensions inside aggregate values
optional google.protobuf.FileOptions file = 4;
extend google.protobuf.FileOptions {
optional Aggregate nested = 15476903;
}
// An embedded message set
optional AggregateMessageSet mset = 5;
}
// Allow Aggregate to be used as an option at all possible locations
// in the .proto grammer.
extend google.protobuf.FileOptions { optional Aggregate fileopt = 15478479; }
extend google.protobuf.MessageOptions { optional Aggregate msgopt = 15480088; }
extend google.protobuf.FieldOptions { optional Aggregate fieldopt = 15481374; }
extend google.protobuf.EnumOptions { optional Aggregate enumopt_renamed = 15483218; }
extend google.protobuf.EnumValueOptions { optional Aggregate enumvalopt = 15486921; }
extend google.protobuf.ServiceOptions { optional Aggregate serviceopt = 15497145; }
extend google.protobuf.MethodOptions { optional Aggregate methodopt = 15512713; }
// Try using AggregateOption at different points in the proto grammar
option (fileopt) = {
s: 'FileAnnotation'
// Also test the handling of comments
/* of both types */ i: 100
sub { s: 'NestedFileAnnotation' }
// Include a google.protobuf.FileOptions and recursively extend it with
// another fileopt.
file {
[protobuf_unittest.fileopt] {
s:'FileExtensionAnnotation'
}
}
// A message set inside an option value
mset {
[protobuf_unittest.AggregateMessageSetElement.message_set_extension] {
s: 'EmbeddedMessageSetElement'
}
}
};
message AggregateMessage {
option (msgopt) = { i:101 s:'MessageAnnotation' };
optional int32 fieldname = 1 [(fieldopt) = { s:'FieldAnnotation' }];
}
service AggregateService {
option (serviceopt) = { s:'ServiceAnnotation' };
rpc Method (AggregateMessage) returns (AggregateMessage) {
option (methodopt) = { s:'MethodAnnotation' };
}
}
enum AggregateEnum {
option (enumopt_renamed) = { s:'EnumAnnotation' };
VALUE = 1 [(enumvalopt) = { s:'EnumValueAnnotation' }];
}

@ -0,0 +1,56 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestEmbedOptimizeForProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which imports a proto file that uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest_optimize_for.proto";
package protobuf_unittest;
// We optimize for speed here, but we are importing a proto that is optimized
// for code size.
option optimize_for = SPEED;
message TestEmbedOptimizedForSize {
// Test that embedding a message which has optimize_for = CODE_SIZE into
// one optimized for speed works.
optional TestOptimizedForSize optional_message = 1;
repeated TestOptimizedForSize repeated_message = 2;
}

@ -0,0 +1,43 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestEmptyProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file intentionally left blank. (At one point this wouldn't compile
// correctly.)

@ -0,0 +1,67 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestImportProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which is imported by unittest.proto to test importing.
// We don't put this in a package within proto2 because we need to make sure
// that the generated code doesn't depend on being in the proto2 namespace.
// In test_util.h we do
// "using namespace unittest_import = protobuf_unittest_import".
package protobuf_unittest_import;
option optimize_for = SPEED;
// Excercise the java_package option.
option java_package = "com.google.protobuf.test";
// Do not set a java_outer_classname here to verify that Proto2 works without
// one.
message ImportMessage {
optional int32 d = 1;
}
enum ImportEnum {
IMPORT_FOO = 7;
IMPORT_BAR = 8;
IMPORT_BAZ = 9;
}

@ -0,0 +1,55 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestImportLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message ImportMessageLite {
optional int32 d = 1;
}
enum ImportEnumLite {
IMPORT_LITE_FOO = 7;
IMPORT_LITE_BAR = 8;
IMPORT_LITE_BAZ = 9;
}

@ -0,0 +1,318 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest;
import "google/protobuf/unittest_import_lite.proto";
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
// Same as TestAllTypes but with the lite runtime.
message TestAllTypesLite {
message NestedMessage {
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessageLite optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnumLite optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnumLite optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessageLite repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnumLite repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnumLite repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR];
optional ForeignEnumLite default_foreign_enum = 82
[default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message ForeignMessageLite {
optional int32 c = 1;
}
enum ForeignEnumLite {
FOREIGN_LITE_FOO = 4;
FOREIGN_LITE_BAR = 5;
FOREIGN_LITE_BAZ = 6;
}
message TestPackedTypesLite {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnumLite packed_enum = 103 [packed = true];
}
message TestAllExtensionsLite {
extensions 1 to max;
}
extend TestAllExtensionsLite {
// Singular
optional int32 optional_int32_extension_lite = 1;
optional int64 optional_int64_extension_lite = 2;
optional uint32 optional_uint32_extension_lite = 3;
optional uint64 optional_uint64_extension_lite = 4;
optional sint32 optional_sint32_extension_lite = 5;
optional sint64 optional_sint64_extension_lite = 6;
optional fixed32 optional_fixed32_extension_lite = 7;
optional fixed64 optional_fixed64_extension_lite = 8;
optional sfixed32 optional_sfixed32_extension_lite = 9;
optional sfixed64 optional_sfixed64_extension_lite = 10;
optional float optional_float_extension_lite = 11;
optional double optional_double_extension_lite = 12;
optional bool optional_bool_extension_lite = 13;
optional string optional_string_extension_lite = 14;
optional bytes optional_bytes_extension_lite = 15;
optional group OptionalGroup_extension_lite = 16 {
optional int32 a = 17;
}
optional TestAllTypesLite.NestedMessage optional_nested_message_extension_lite
= 18;
optional ForeignMessageLite optional_foreign_message_extension_lite = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message_extension_lite = 20;
optional TestAllTypesLite.NestedEnum optional_nested_enum_extension_lite = 21;
optional ForeignEnumLite optional_foreign_enum_extension_lite = 22;
optional protobuf_unittest_import.ImportEnumLite
optional_import_enum_extension_lite = 23;
optional string optional_string_piece_extension_lite = 24
[ctype=STRING_PIECE];
optional string optional_cord_extension_lite = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32_extension_lite = 31;
repeated int64 repeated_int64_extension_lite = 32;
repeated uint32 repeated_uint32_extension_lite = 33;
repeated uint64 repeated_uint64_extension_lite = 34;
repeated sint32 repeated_sint32_extension_lite = 35;
repeated sint64 repeated_sint64_extension_lite = 36;
repeated fixed32 repeated_fixed32_extension_lite = 37;
repeated fixed64 repeated_fixed64_extension_lite = 38;
repeated sfixed32 repeated_sfixed32_extension_lite = 39;
repeated sfixed64 repeated_sfixed64_extension_lite = 40;
repeated float repeated_float_extension_lite = 41;
repeated double repeated_double_extension_lite = 42;
repeated bool repeated_bool_extension_lite = 43;
repeated string repeated_string_extension_lite = 44;
repeated bytes repeated_bytes_extension_lite = 45;
repeated group RepeatedGroup_extension_lite = 46 {
optional int32 a = 47;
}
repeated TestAllTypesLite.NestedMessage repeated_nested_message_extension_lite
= 48;
repeated ForeignMessageLite repeated_foreign_message_extension_lite = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message_extension_lite = 50;
repeated TestAllTypesLite.NestedEnum repeated_nested_enum_extension_lite = 51;
repeated ForeignEnumLite repeated_foreign_enum_extension_lite = 52;
repeated protobuf_unittest_import.ImportEnumLite
repeated_import_enum_extension_lite = 53;
repeated string repeated_string_piece_extension_lite = 54
[ctype=STRING_PIECE];
repeated string repeated_cord_extension_lite = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32_extension_lite = 61 [default = 41 ];
optional int64 default_int64_extension_lite = 62 [default = 42 ];
optional uint32 default_uint32_extension_lite = 63 [default = 43 ];
optional uint64 default_uint64_extension_lite = 64 [default = 44 ];
optional sint32 default_sint32_extension_lite = 65 [default = -45 ];
optional sint64 default_sint64_extension_lite = 66 [default = 46 ];
optional fixed32 default_fixed32_extension_lite = 67 [default = 47 ];
optional fixed64 default_fixed64_extension_lite = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension_lite = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension_lite = 70 [default = -50 ];
optional float default_float_extension_lite = 71 [default = 51.5 ];
optional double default_double_extension_lite = 72 [default = 52e3 ];
optional bool default_bool_extension_lite = 73 [default = true ];
optional string default_string_extension_lite = 74 [default = "hello"];
optional bytes default_bytes_extension_lite = 75 [default = "world"];
optional TestAllTypesLite.NestedEnum
default_nested_enum_extension_lite = 81 [default = BAR];
optional ForeignEnumLite
default_foreign_enum_extension_lite = 82 [default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum_extension_lite = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece_extension_lite = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension_lite = 85 [ctype=CORD, default="123"];
}
message TestPackedExtensionsLite {
extensions 1 to max;
}
extend TestPackedExtensionsLite {
repeated int32 packed_int32_extension_lite = 90 [packed = true];
repeated int64 packed_int64_extension_lite = 91 [packed = true];
repeated uint32 packed_uint32_extension_lite = 92 [packed = true];
repeated uint64 packed_uint64_extension_lite = 93 [packed = true];
repeated sint32 packed_sint32_extension_lite = 94 [packed = true];
repeated sint64 packed_sint64_extension_lite = 95 [packed = true];
repeated fixed32 packed_fixed32_extension_lite = 96 [packed = true];
repeated fixed64 packed_fixed64_extension_lite = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension_lite = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension_lite = 99 [packed = true];
repeated float packed_float_extension_lite = 100 [packed = true];
repeated double packed_double_extension_lite = 101 [packed = true];
repeated bool packed_bool_extension_lite = 102 [packed = true];
repeated ForeignEnumLite packed_enum_extension_lite = 103 [packed = true];
}
message TestNestedExtensionLite {
extend TestAllExtensionsLite {
optional int32 nested_extension = 12345;
}
}
// Test that deprecated fields work. We only verify that they compile (at one
// point this failed).
message TestDeprecatedLite {
optional int32 deprecated_field = 1 [deprecated = true];
}

@ -0,0 +1,49 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestLiteImportNonLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// Tests that a "lite" message can import a regular message.
package protobuf_unittest;
import "google/protobuf/unittest.proto";
option optimize_for = LITE_RUNTIME;
message TestLiteImportsNonlite {
optional TestAllTypes message = 1;
}

@ -0,0 +1,78 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestMessageSetProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains messages for testing message_set_wire_format.
package protobuf_unittest;
option optimize_for = SPEED;
// A message with message_set_wire_format.
message TestMessageSet {
option message_set_wire_format = true;
extensions 4 to max;
}
message TestMessageSetContainer {
optional TestMessageSet message_set = 1;
}
message TestMessageSetExtension1 {
extend TestMessageSet {
optional TestMessageSetExtension1 message_set_extension = 1545008;
}
optional int32 i = 15;
}
message TestMessageSetExtension2 {
extend TestMessageSet {
optional TestMessageSetExtension2 message_set_extension = 1547769;
}
optional string str = 25;
}
// MessageSet wire format is equivalent to this.
message RawMessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required bytes message = 3;
}
}

@ -0,0 +1,58 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos.NoGenericService";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestNoGenericServicesProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
package google.protobuf.no_generic_services_test;
// *_generic_services are false by default.
message TestMessage {
optional int32 a = 1;
extensions 1000 to max;
}
enum TestEnum {
FOO = 1;
}
extend TestMessage {
optional int32 test_extension = 1000;
}
service TestService {
rpc Foo(TestMessage) returns(TestMessage);
}

@ -0,0 +1,67 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestOptimizeForProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// A proto file which uses optimize_for = CODE_SIZE.
import "google/protobuf/unittest.proto";
package protobuf_unittest;
option optimize_for = CODE_SIZE;
message TestOptimizedForSize {
optional int32 i = 1;
optional ForeignMessage msg = 19;
extensions 1000 to max;
extend TestOptimizedForSize {
optional int32 test_extension = 1234;
optional TestRequiredOptimizedForSize test_extension2 = 1235;
}
}
message TestRequiredOptimizedForSize {
required int32 x = 1;
}
message TestOptionalOptimizedForSize {
optional TestRequiredOptimizedForSize o = 1;
}

@ -0,0 +1,140 @@
package unittest_google_size;
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestGoogleSizeProtoFile";
option java_outer_classname = "GoogleSize";
option optimize_for = CODE_SIZE;
message SizeMessage1 {
required string field1 = 1;
optional string field9 = 9;
optional string field18 = 18;
optional bool field80 = 80 [default=false];
optional bool field81 = 81 [default=true];
required int32 field2 = 2;
required int32 field3 = 3;
optional int32 field280 = 280;
optional int32 field6 = 6 [default=0];
optional int64 field22 = 22;
optional string field4 = 4;
repeated fixed64 field5 = 5;
optional bool field59 = 59 [default=false];
optional string field7 = 7;
optional int32 field16 = 16;
optional int32 field130 = 130 [default=0];
optional bool field12 = 12 [default=true];
optional bool field17 = 17 [default=true];
optional bool field13 = 13 [default=true];
optional bool field14 = 14 [default=true];
optional int32 field104 = 104 [default=0];
optional int32 field100 = 100 [default=0];
optional int32 field101 = 101 [default=0];
optional string field102 = 102;
optional string field103 = 103;
optional int32 field29 = 29 [default=0];
optional bool field30 = 30 [default=false];
optional int32 field60 = 60 [default=-1];
optional int32 field271 = 271 [default=-1];
optional int32 field272 = 272 [default=-1];
optional int32 field150 = 150;
optional int32 field23 = 23 [default=0];
optional bool field24 = 24 [default=false];
optional int32 field25 = 25 [default=0];
optional SizeMessage1SubMessage field15 = 15;
optional bool field78 = 78;
optional int32 field67 = 67 [default=0];
optional int32 field68 = 68;
optional int32 field128 = 128 [default=0];
optional string field129 = 129 [default="xxxxxxxxxxxxxxxxxxxxx"];
optional int32 field131 = 131 [default=0];
}
message SizeMessage1SubMessage {
optional int32 field1 = 1 [default=0];
optional int32 field2 = 2 [default=0];
optional int32 field3 = 3 [default=0];
optional string field15 = 15;
optional bool field12 = 12 [default=true];
optional int64 field13 = 13;
optional int64 field14 = 14;
optional int32 field16 = 16;
optional int32 field19 = 19 [default=2];
optional bool field20 = 20 [default=true];
optional bool field28 = 28 [default=true];
optional fixed64 field21 = 21;
optional int32 field22 = 22;
optional bool field23 = 23 [ default=false ];
optional bool field206 = 206 [default=false];
optional fixed32 field203 = 203;
optional int32 field204 = 204;
optional string field205 = 205;
optional uint64 field207 = 207;
optional uint64 field300 = 300;
}
message SizeMessage2 {
optional string field1 = 1;
optional int64 field3 = 3;
optional int64 field4 = 4;
optional int64 field30 = 30;
optional bool field75 = 75 [default=false];
optional string field6 = 6;
optional bytes field2 = 2;
optional int32 field21 = 21 [default=0];
optional int32 field71 = 71;
optional float field25 = 25;
optional int32 field109 = 109 [default=0];
optional int32 field210 = 210 [default=0];
optional int32 field211 = 211 [default=0];
optional int32 field212 = 212 [default=0];
optional int32 field213 = 213 [default=0];
optional int32 field216 = 216 [default=0];
optional int32 field217 = 217 [default=0];
optional int32 field218 = 218 [default=0];
optional int32 field220 = 220 [default=0];
optional int32 field221 = 221 [default=0];
optional float field222 = 222 [default=0.0];
optional int32 field63 = 63;
repeated group Group1 = 10 {
required float field11 = 11;
optional float field26 = 26;
optional string field12 = 12;
optional string field13 = 13;
repeated string field14 = 14;
required uint64 field15 = 15;
optional int32 field5 = 5;
optional string field27 = 27;
optional int32 field28 = 28;
optional string field29 = 29;
optional string field16 = 16;
repeated string field22 = 22;
repeated int32 field73 = 73;
optional int32 field20 = 20 [default=0];
optional string field24 = 24;
optional SizeMessage2GroupedMessage field31 = 31;
}
repeated string field128 = 128;
optional int64 field131 = 131;
repeated string field127 = 127;
optional int32 field129 = 129;
repeated int64 field130 = 130;
optional bool field205 = 205 [default=false];
optional bool field206 = 206 [default=false];
}
message SizeMessage2GroupedMessage {
optional float field1 = 1;
optional float field2 = 2;
optional float field3 = 3 [default=0.0];
optional bool field4 = 4;
optional bool field5 = 5;
optional bool field6 = 6 [default=true];
optional bool field7 = 7 [default=false];
optional float field8 = 8;
optional bool field9 = 9;
optional float field10 = 10;
optional int64 field11 = 11;
}

@ -0,0 +1,140 @@
package unittest_google_speed;
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestGoogleSpeedProtoFile";
option java_outer_classname = "GoogleSpeed";
option optimize_for = SPEED;
message SpeedMessage1 {
required string field1 = 1;
optional string field9 = 9;
optional string field18 = 18;
optional bool field80 = 80 [default=false];
optional bool field81 = 81 [default=true];
required int32 field2 = 2;
required int32 field3 = 3;
optional int32 field280 = 280;
optional int32 field6 = 6 [default=0];
optional int64 field22 = 22;
optional string field4 = 4;
repeated fixed64 field5 = 5;
optional bool field59 = 59 [default=false];
optional string field7 = 7;
optional int32 field16 = 16;
optional int32 field130 = 130 [default=0];
optional bool field12 = 12 [default=true];
optional bool field17 = 17 [default=true];
optional bool field13 = 13 [default=true];
optional bool field14 = 14 [default=true];
optional int32 field104 = 104 [default=0];
optional int32 field100 = 100 [default=0];
optional int32 field101 = 101 [default=0];
optional string field102 = 102;
optional string field103 = 103;
optional int32 field29 = 29 [default=0];
optional bool field30 = 30 [default=false];
optional int32 field60 = 60 [default=-1];
optional int32 field271 = 271 [default=-1];
optional int32 field272 = 272 [default=-1];
optional int32 field150 = 150;
optional int32 field23 = 23 [default=0];
optional bool field24 = 24 [default=false];
optional int32 field25 = 25 [default=0];
optional SpeedMessage1SubMessage field15 = 15;
optional bool field78 = 78;
optional int32 field67 = 67 [default=0];
optional int32 field68 = 68;
optional int32 field128 = 128 [default=0];
optional string field129 = 129 [default="xxxxxxxxxxxxxxxxxxxxx"];
optional int32 field131 = 131 [default=0];
}
message SpeedMessage1SubMessage {
optional int32 field1 = 1 [default=0];
optional int32 field2 = 2 [default=0];
optional int32 field3 = 3 [default=0];
optional string field15 = 15;
optional bool field12 = 12 [default=true];
optional int64 field13 = 13;
optional int64 field14 = 14;
optional int32 field16 = 16;
optional int32 field19 = 19 [default=2];
optional bool field20 = 20 [default=true];
optional bool field28 = 28 [default=true];
optional fixed64 field21 = 21;
optional int32 field22 = 22;
optional bool field23 = 23 [ default=false ];
optional bool field206 = 206 [default=false];
optional fixed32 field203 = 203;
optional int32 field204 = 204;
optional string field205 = 205;
optional uint64 field207 = 207;
optional uint64 field300 = 300;
}
message SpeedMessage2 {
optional string field1 = 1;
optional int64 field3 = 3;
optional int64 field4 = 4;
optional int64 field30 = 30;
optional bool field75 = 75 [default=false];
optional string field6 = 6;
optional bytes field2 = 2;
optional int32 field21 = 21 [default=0];
optional int32 field71 = 71;
optional float field25 = 25;
optional int32 field109 = 109 [default=0];
optional int32 field210 = 210 [default=0];
optional int32 field211 = 211 [default=0];
optional int32 field212 = 212 [default=0];
optional int32 field213 = 213 [default=0];
optional int32 field216 = 216 [default=0];
optional int32 field217 = 217 [default=0];
optional int32 field218 = 218 [default=0];
optional int32 field220 = 220 [default=0];
optional int32 field221 = 221 [default=0];
optional float field222 = 222 [default=0.0];
optional int32 field63 = 63;
repeated group Group1 = 10 {
required float field11 = 11;
optional float field26 = 26;
optional string field12 = 12;
optional string field13 = 13;
repeated string field14 = 14;
required uint64 field15 = 15;
optional int32 field5 = 5;
optional string field27 = 27;
optional int32 field28 = 28;
optional string field29 = 29;
optional string field16 = 16;
repeated string field22 = 22;
repeated int32 field73 = 73;
optional int32 field20 = 20 [default=0];
optional string field24 = 24;
optional SpeedMessage2GroupedMessage field31 = 31;
}
repeated string field128 = 128;
optional int64 field131 = 131;
repeated string field127 = 127;
optional int32 field129 = 129;
repeated int64 field130 = 130;
optional bool field205 = 205 [default=false];
optional bool field206 = 206 [default=false];
}
message SpeedMessage2GroupedMessage {
optional float field1 = 1;
optional float field2 = 2;
optional float field3 = 3 [default=0.0];
optional bool field4 = 4;
optional bool field5 = 5;
optional bool field6 = 6 [default=true];
optional bool field7 = 7 [default=false];
optional float field8 = 8;
optional bool field9 = 9;
optional float field10 = 10;
optional int64 field11 = 11;
}

@ -0,0 +1,44 @@
<NotepadPlus>
<!--
Defines syntax highlighting for Notepad++.
1. Install Notepad++ from http://notepad-plus-plus.org
2. Open Notepad++, from the View menu, select "User-Defined Dialog..."
3. Click the "Import..." button and select this file
4. Restart Notepad++
5. Open and edit any *.proto file
-->
<UserLang name="Proto Buffer" ext="proto">
<Settings>
<Global caseIgnored="no" />
<TreatAsSymbol comment="no" commentLine="yes" />
<Prefix words1="no" words2="no" words3="no" words4="yes" />
</Settings>
<KeywordLists>
<Keywords name="Delimiters">[00]00</Keywords>
<Keywords name="Folder+">{</Keywords>
<Keywords name="Folder-">}</Keywords>
<Keywords name="Operators">=</Keywords>
<Keywords name="Comment"> 1option 1package 1import 2; 0//</Keywords>
<Keywords name="Words1">message enum service extend</Keywords>
<Keywords name="Words2">required optional repeated extensions to rpc returns</Keywords>
<Keywords name="Words3">double float int32 int64 uint32 uint64 sint32 sint64 fixed32 fixed64 sfixed32 sfixed64 bool string bytes</Keywords>
<Keywords name="Words4"></Keywords>
</KeywordLists>
<Styles>
<WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontStyle="1" />
<WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontStyle="1" />
<WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD2" styleID="6" fgColor="0080C0" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD3" styleID="7" fgColor="0000FF" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="KEYWORD4" styleID="8" fgColor="008040" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="COMMENT" styleID="1" fgColor="008000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="COMMENT LINE" styleID="2" fgColor="949494" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="NUMBER" styleID="4" fgColor="FF0000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="OPERATOR" styleID="10" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER1" styleID="14" fgColor="800080" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER2" styleID="15" fgColor="808080" bgColor="FFFFFF" fontStyle="0" />
<WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontStyle="0" />
</Styles>
</UserLang>
</NotepadPlus>

@ -0,0 +1,31 @@
package tutorial;
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.Examples.AddressBook";
option (google.protobuf.csharp_file_options).umbrella_classname = "AddressBookProtos";
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;
}

@ -0,0 +1,136 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
internal class AddPerson
{
/// <summary>
/// Builds a person based on user input
/// </summary>
private 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;
}
}
}

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<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>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<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\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<ItemGroup>
<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" />
</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>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,103 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
internal class ListPeople
{
/// <summary>
/// Iterates though all people in the AddressBook and prints info about them.
/// </summary>
private 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;
}
}
}

@ -0,0 +1,99 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
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>
internal class Program
{
private 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;
}
}
}

@ -0,0 +1,29 @@
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("")]
// 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("2.4.1.555")]
[assembly: AssemblyVersion("2.4.1.555")]
[assembly: AssemblyFileVersion("2.4.1.555")]

@ -0,0 +1,44 @@
using System;
using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook
{
internal class SampleUsage
{
private 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!");
}
}
}

@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup/></configuration>

@ -0,0 +1,538 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Xml;
using Google.ProtocolBuffers.Serialization;
using Google.ProtocolBuffers.TestProtos;
namespace Google.ProtocolBuffers.ProtoBench
{
/// <summary>
/// Simple benchmarking of arbitrary messages.
/// </summary>
public sealed class Program
{
private static TimeSpan MinSampleTime = TimeSpan.FromSeconds(2);
private static TimeSpan TargetTime = TimeSpan.FromSeconds(30);
private static bool Verbose = false, FastTest = false, OtherFormats = false;
// Avoid a .NET 3.5 dependency
private delegate void Action();
private delegate void BenchmarkTest(string name, long dataSize, Action action);
private static BenchmarkTest RunBenchmark;
private static string _logFile;
static void WriteLine(string format, params object[] arg)
{
if (arg.Length > 0) format = String.Format(format, arg);
Console.Out.WriteLine(format);
if (!String.IsNullOrEmpty(_logFile))
File.AppendAllText(_logFile, format + Environment.NewLine);
}
[STAThread]
public static int Main(string[] args)
{
List<string> temp = new List<string>(args);
Verbose = temp.Remove("/verbose") || temp.Remove("-verbose");
OtherFormats = temp.Remove("/formats") || temp.Remove("-formats");
foreach (string arg in temp)
{
if (arg.StartsWith("/log:", StringComparison.OrdinalIgnoreCase) || arg.StartsWith("-log:", StringComparison.OrdinalIgnoreCase))
{
_logFile = arg.Substring(5);
if (!String.IsNullOrEmpty(_logFile))
File.AppendAllText(_logFile, Environment.NewLine + "Started benchmarks at " + DateTime.Now + Environment.NewLine);
temp.Remove(arg);
break;
}
}
if (true == (FastTest = (temp.Remove("/fast") || temp.Remove("-fast"))))
{
TargetTime = TimeSpan.FromSeconds(10);
}
RunBenchmark = BenchmarkV1;
if (temp.Remove("/v2") || temp.Remove("-v2"))
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunBenchmark = BenchmarkV2;
}
if (temp.Remove("/all") || temp.Remove("-all"))
{
if (FastTest)
{
TargetTime = TimeSpan.FromSeconds(5);
}
foreach (KeyValuePair<string, string> item in MakeTests())
{
temp.Add(item.Key);
temp.Add(item.Value);
}
}
args = temp.ToArray();
if (args.Length < 2 || (args.Length%2) != 0)
{
Console.Error.WriteLine("Usage: ProtoBench [/fast] <descriptor type name> <input data>");
Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,");
Console.Error.WriteLine(
"including assembly - e.g. Google.ProtocolBuffers.BenchmarkProtos.Message1,ProtoBench");
Console.Error.WriteLine("(You can specify multiple pairs of descriptor type name and input data.)");
return 1;
}
bool success = true;
for (int i = 0; i < args.Length; i += 2)
{
success &= RunTest(args[i], args[i + 1], null);
}
return success ? 0 : 1;
}
/// <summary>
/// Runs a single test. Error messages are displayed to Console.Error, and the return value indicates
/// general success/failure.
/// </summary>
public static bool RunTest(string typeName, string file, byte[] inputData)
{
WriteLine("Benchmarking {0} with file {1}", typeName, file);
IMessage defaultMessage;
try
{
defaultMessage = MessageUtil.GetDefaultMessage(typeName);
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
return false;
}
try
{
ExtensionRegistry registry = ExtensionRegistry.Empty;
inputData = inputData ?? File.ReadAllBytes(file);
MemoryStream inputStream = new MemoryStream(inputData);
ByteString inputString = ByteString.CopyFrom(inputData);
IMessage sampleMessage =
defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(inputString, registry).WeakBuild();
IDictionary<string, object> dictionary = null;
byte[] jsonBytes = null, xmlBytes = null; /*no pun intended, well... maybe for xml*/
if (OtherFormats)
{
using (MemoryStream temp = new MemoryStream())
{
XmlFormatWriter.CreateInstance(temp).WriteMessage(sampleMessage);
xmlBytes = temp.ToArray();
}
using (MemoryStream temp = new MemoryStream())
{
JsonFormatWriter.CreateInstance(temp).WriteMessage(sampleMessage);
jsonBytes = temp.ToArray();
}
dictionary = new Dictionary<string, object>(StringComparer.Ordinal);
new DictionaryWriter(dictionary).WriteMessage(sampleMessage);
}
//Serializers
if (!FastTest)
{
RunBenchmark("Serialize to byte string", inputData.Length, () => sampleMessage.ToByteString());
}
RunBenchmark("Serialize to byte array", inputData.Length, () => sampleMessage.ToByteArray());
if (!FastTest)
{
RunBenchmark("Serialize to memory stream", inputData.Length,
() => sampleMessage.WriteTo(new MemoryStream()));
}
if (OtherFormats)
{
RunBenchmark("Serialize to xml", xmlBytes.Length,
() =>
{
XmlFormatWriter.CreateInstance(new MemoryStream(), Encoding.UTF8).WriteMessage(sampleMessage);
});
RunBenchmark("Serialize to json", jsonBytes.Length,
() => { JsonFormatWriter.CreateInstance().WriteMessage(sampleMessage); });
RunBenchmark("Serialize to json via xml", jsonBytes.Length,
() =>
XmlFormatWriter.CreateInstance(
JsonReaderWriterFactory.CreateJsonWriter(new MemoryStream(), Encoding.UTF8))
.SetOptions(XmlWriterOptions.OutputJsonTypes)
.WriteMessage(sampleMessage)
);
RunBenchmark("Serialize to dictionary", sampleMessage.SerializedSize,
() => new DictionaryWriter().WriteMessage(sampleMessage));
}
//Deserializers
if (!FastTest)
{
RunBenchmark("Deserialize from byte string", inputData.Length,
() => defaultMessage.WeakCreateBuilderForType()
.WeakMergeFrom(inputString, registry)
.WeakBuild()
);
}
RunBenchmark("Deserialize from byte array", inputData.Length,
() => defaultMessage.WeakCreateBuilderForType()
.WeakMergeFrom(CodedInputStream.CreateInstance(inputData), registry)
.WeakBuild()
);
if (!FastTest)
{
RunBenchmark("Deserialize from memory stream", inputData.Length,
() =>
{
inputStream.Position = 0;
defaultMessage.WeakCreateBuilderForType().WeakMergeFrom(
CodedInputStream.CreateInstance(inputStream), registry)
.WeakBuild();
});
}
if (OtherFormats)
{
RunBenchmark("Deserialize from xml", xmlBytes.Length,
() =>
XmlFormatReader.CreateInstance(xmlBytes).Merge(
defaultMessage.WeakCreateBuilderForType()).WeakBuild());
RunBenchmark("Deserialize from json", jsonBytes.Length,
() =>
JsonFormatReader.CreateInstance(jsonBytes).Merge(
defaultMessage.WeakCreateBuilderForType()).WeakBuild());
RunBenchmark("Deserialize from json via xml", jsonBytes.Length,
() =>
XmlFormatReader.CreateInstance(JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
.SetOptions(XmlReaderOptions.ReadNestedArrays).Merge(
defaultMessage.WeakCreateBuilderForType()).WeakBuild());
RunBenchmark("Deserialize from dictionary", sampleMessage.SerializedSize,
() =>
new DictionaryReader(dictionary).Merge(defaultMessage.WeakCreateBuilderForType()).
WeakBuild());
}
WriteLine(String.Empty);
return true;
}
catch (Exception e)
{
Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
return false;
}
}
private static void BenchmarkV2(string name, long dataSize, Action action)
{
Thread.BeginThreadAffinity();
TimeSpan elapsed = TimeSpan.Zero;
long runs = 0;
long totalCount = 0;
double best = double.MinValue, worst = double.MaxValue;
action();
// Run it progressively more times until we've got a reasonable sample
int iterations = 100;
elapsed = TimeAction(action, iterations);
while (elapsed.TotalMilliseconds < 1000)
{
elapsed += TimeAction(action, iterations);
iterations *= 2;
}
TimeSpan target = TimeSpan.FromSeconds(1);
elapsed = TimeAction(action, iterations);
iterations = (int) ((target.Ticks*iterations)/(double) elapsed.Ticks);
elapsed = TimeAction(action, iterations);
iterations = (int) ((target.Ticks*iterations)/(double) elapsed.Ticks);
elapsed = TimeAction(action, iterations);
iterations = (int) ((target.Ticks*iterations)/(double) elapsed.Ticks);
double first = (iterations*dataSize)/(elapsed.TotalSeconds*1024*1024);
if (Verbose)
{
WriteLine("Round ---: Count = {1,6}, Bps = {2,8:f3}", 0, iterations, first);
}
elapsed = TimeSpan.Zero;
int max = (int) TargetTime.TotalSeconds;
while (runs < max)
{
TimeSpan cycle = TimeAction(action, iterations);
// Accumulate and scale for next cycle.
double bps = (iterations*dataSize)/(cycle.TotalSeconds*1024*1024);
if (Verbose)
{
WriteLine("Round {1,3}: Count = {2,6}, Bps = {3,8:f3}",
0, runs, iterations, bps);
}
best = Math.Max(best, bps);
worst = Math.Min(worst, bps);
runs++;
elapsed += cycle;
totalCount += iterations;
iterations = (int) ((target.Ticks*totalCount)/(double) elapsed.Ticks);
}
Thread.EndThreadAffinity();
WriteLine(
"{1}: averages {2} per {3:f3}s for {4} runs; avg: {5:f3}mbps; best: {6:f3}mbps; worst: {7:f3}mbps",
0, name, totalCount/runs, elapsed.TotalSeconds/runs, runs,
(totalCount*dataSize)/(elapsed.TotalSeconds*1024*1024), best, worst);
}
private static void BenchmarkV1(string name, long dataSize, Action action)
{
// Make sure it's JITted
action();
// Run it progressively more times until we've got a reasonable sample
int iterations = 1;
TimeSpan elapsed = TimeAction(action, iterations);
while (elapsed < MinSampleTime)
{
iterations *= 2;
elapsed = TimeAction(action, iterations);
}
// Upscale the sample to the target time. Do this in floating point arithmetic
// to avoid overflow issues.
iterations = (int) ((TargetTime.Ticks/(double) elapsed.Ticks)*iterations);
elapsed = TimeAction(action, iterations);
WriteLine("{0}: {1} iterations in {2:f3}s; {3:f3}MB/s",
name, iterations, elapsed.TotalSeconds,
(iterations*dataSize)/(elapsed.TotalSeconds*1024*1024));
}
private static TimeSpan TimeAction(Action action, int iterations)
{
GC.Collect();
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
action();
}
sw.Stop();
return sw.Elapsed;
}
private static IEnumerable<KeyValuePair<string, string>> MakeTests()
{
//Aggregate Tests
yield return MakeWorkItem("all-types", MakeTestAllTypes());
yield return MakeWorkItem("repeated-100", MakeRepeatedTestAllTypes(100));
yield return MakeWorkItem("packed-100", MakeTestPackedTypes(100));
//Discrete Tests
foreach (KeyValuePair<string, Action<TestAllTypes.Builder>> item in MakeTestAllTypes())
{
yield return MakeWorkItem(item.Key, new[] {item});
}
foreach (KeyValuePair<string, Action<TestAllTypes.Builder>> item in MakeRepeatedTestAllTypes(100))
{
yield return MakeWorkItem(item.Key, new[] {item});
}
foreach (KeyValuePair<string, Action<TestPackedTypes.Builder>> item in MakeTestPackedTypes(100))
{
yield return MakeWorkItem(item.Key, new[] {item});
}
}
private static IEnumerable<KeyValuePair<string, Action<TestAllTypes.Builder>>> MakeTestAllTypes()
{
// Many of the raw type serializers below perform poorly due to the numerous fields defined
// in TestAllTypes.
//single values
yield return MakeItem<TestAllTypes.Builder>("int32", 1, x => x.SetOptionalInt32(1001));
yield return MakeItem<TestAllTypes.Builder>("int64", 1, x => x.SetOptionalInt64(1001));
yield return MakeItem<TestAllTypes.Builder>("uint32", 1, x => x.SetOptionalUint32(1001));
yield return MakeItem<TestAllTypes.Builder>("uint64", 1, x => x.SetOptionalUint64(1001));
yield return MakeItem<TestAllTypes.Builder>("sint32", 1, x => x.SetOptionalSint32(-1001));
yield return MakeItem<TestAllTypes.Builder>("sint64", 1, x => x.SetOptionalSint64(-1001));
yield return MakeItem<TestAllTypes.Builder>("fixed32", 1, x => x.SetOptionalFixed32(1001));
yield return MakeItem<TestAllTypes.Builder>("fixed64", 1, x => x.SetOptionalFixed64(1001));
yield return MakeItem<TestAllTypes.Builder>("sfixed32", 1, x => x.SetOptionalSfixed32(-1001));
yield return MakeItem<TestAllTypes.Builder>("sfixed64", 1, x => x.SetOptionalSfixed64(-1001));
yield return MakeItem<TestAllTypes.Builder>("float", 1, x => x.SetOptionalFloat(1001.1001f));
yield return MakeItem<TestAllTypes.Builder>("double", 1, x => x.SetOptionalDouble(1001.1001));
yield return MakeItem<TestAllTypes.Builder>("bool", 1, x => x.SetOptionalBool(true));
yield return MakeItem<TestAllTypes.Builder>("string", 1, x => x.SetOptionalString("this is a string value"))
;
yield return
MakeItem<TestAllTypes.Builder>("bytes", 1,
x =>
x.SetOptionalBytes(ByteString.CopyFromUtf8("this is an array of bytes")))
;
yield return
MakeItem<TestAllTypes.Builder>("group", 1,
x =>
x.SetOptionalGroup(
new TestAllTypes.Types.OptionalGroup.Builder().SetA(1001)));
yield return
MakeItem<TestAllTypes.Builder>("message", 1,
x =>
x.SetOptionalNestedMessage(
new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)));
yield return
MakeItem<TestAllTypes.Builder>("enum", 1,
x => x.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO));
}
private static IEnumerable<KeyValuePair<string, Action<TestAllTypes.Builder>>> MakeRepeatedTestAllTypes(int size)
{
//repeated values
yield return MakeItem<TestAllTypes.Builder>("repeated-int32", size, x => x.AddRepeatedInt32(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-int64", size, x => x.AddRepeatedInt64(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-uint32", size, x => x.AddRepeatedUint32(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-uint64", size, x => x.AddRepeatedUint64(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-sint32", size, x => x.AddRepeatedSint32(-1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-sint64", size, x => x.AddRepeatedSint64(-1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-fixed32", size, x => x.AddRepeatedFixed32(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-fixed64", size, x => x.AddRepeatedFixed64(1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-sfixed32", size, x => x.AddRepeatedSfixed32(-1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-sfixed64", size, x => x.AddRepeatedSfixed64(-1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-float", size, x => x.AddRepeatedFloat(1001.1001f));
yield return MakeItem<TestAllTypes.Builder>("repeated-double", size, x => x.AddRepeatedDouble(1001.1001));
yield return MakeItem<TestAllTypes.Builder>("repeated-bool", size, x => x.AddRepeatedBool(true));
yield return
MakeItem<TestAllTypes.Builder>("repeated-string", size,
x => x.AddRepeatedString("this is a string value"));
yield return
MakeItem<TestAllTypes.Builder>("repeated-bytes", size,
x =>
x.AddRepeatedBytes(ByteString.CopyFromUtf8("this is an array of bytes")))
;
yield return
MakeItem<TestAllTypes.Builder>("repeated-group", size,
x =>
x.AddRepeatedGroup(
new TestAllTypes.Types.RepeatedGroup.Builder().SetA(1001)));
yield return
MakeItem<TestAllTypes.Builder>("repeated-message", size,
x =>
x.AddRepeatedNestedMessage(
new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)));
yield return
MakeItem<TestAllTypes.Builder>("repeated-enum", size,
x => x.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.FOO));
}
private static IEnumerable<KeyValuePair<string, Action<TestPackedTypes.Builder>>> MakeTestPackedTypes(int size)
{
//packed values
yield return MakeItem<TestPackedTypes.Builder>("packed-int32", size, x => x.AddPackedInt32(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-int64", size, x => x.AddPackedInt64(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-uint32", size, x => x.AddPackedUint32(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-uint64", size, x => x.AddPackedUint64(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-sint32", size, x => x.AddPackedSint32(-1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-sint64", size, x => x.AddPackedSint64(-1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-fixed32", size, x => x.AddPackedFixed32(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-fixed64", size, x => x.AddPackedFixed64(1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-sfixed32", size, x => x.AddPackedSfixed32(-1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-sfixed64", size, x => x.AddPackedSfixed64(-1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-float", size, x => x.AddPackedFloat(1001.1001f));
yield return MakeItem<TestPackedTypes.Builder>("packed-double", size, x => x.AddPackedDouble(1001.1001));
yield return MakeItem<TestPackedTypes.Builder>("packed-bool", size, x => x.AddPackedBool(true));
yield return
MakeItem<TestPackedTypes.Builder>("packed-enum", size, x => x.AddPackedEnum(ForeignEnum.FOREIGN_FOO));
}
private static KeyValuePair<string, Action<T>> MakeItem<T>(string name, int repeated, Action<T> build)
where T : IBuilderLite, new()
{
if (repeated == 1)
{
return new KeyValuePair<string, Action<T>>(name, build);
}
return new KeyValuePair<string, Action<T>>(
String.Format("{0}[{1}]", name, repeated),
x =>
{
for (int i = 0; i < repeated; i++)
{
build(x);
}
}
);
}
private static KeyValuePair<string, string> MakeWorkItem<T>(string name,
IEnumerable<KeyValuePair<string, Action<T>>>
builders) where T : IBuilderLite, new()
{
T builder = new T();
foreach (KeyValuePair<string, Action<T>> item in builders)
{
item.Value(builder);
}
IMessageLite msg = builder.WeakBuild();
string fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "unittest_" + name + ".dat");
File.WriteAllBytes(fname, msg.ToByteArray());
return
new KeyValuePair<string, string>(
String.Format("{0},{1}", msg.GetType().FullName, msg.GetType().Assembly.GetName().Name), fname);
}
}
}

@ -0,0 +1,32 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
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("ProtoBench")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProtoBench")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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("2.4.1.555")]
[assembly: AssemblyVersion("2.4.1.555")]
[assembly: AssemblyFileVersion("2.4.1.555")]

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C7A4A435-2813-41C8-AA87-BD914BA5223D}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoBench</RootNamespace>
<AssemblyName>ProtoBench</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestProtos\GoogleSizeProtoFile.cs" />
<Compile Include="TestProtos\GoogleSpeedProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportProtoFile.cs" />
<Compile Include="TestProtos\UnitTestProtoFile.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers.Serialization\ProtocolBuffers.Serialization.csproj">
<Project>{231391AF-449C-4a39-986C-AD7F270F4750}</Project>
<Name>ProtocolBuffers.Serialization</Name>
<Private>True</Private>
</ProjectReference>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
<Private>True</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="google_message1.dat">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="google_message2.dat">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</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>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,346 @@
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT!
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnitTestImportProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_ImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder> internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestImportProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0LnByb3RvEhhwcm90",
"b2J1Zl91bml0dGVzdF9pbXBvcnQaJGdvb2dsZS9wcm90b2J1Zi9jc2hhcnBf",
"b3B0aW9ucy5wcm90byIaCg1JbXBvcnRNZXNzYWdlEgkKAWQYASABKAUqPAoK",
"SW1wb3J0RW51bRIOCgpJTVBPUlRfRk9PEAcSDgoKSU1QT1JUX0JBUhAIEg4K",
"CklNUE9SVF9CQVoQCUJbChhjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3RIAcI+",
"PAohR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9zEhdVbml0VGVz",
"dEltcG9ydFByb3RvRmlsZQ=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_ImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder>(internal__static_protobuf_unittest_import_ImportMessage__Descriptor,
new string[] { "D", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnum {
IMPORT_FOO = 7,
IMPORT_BAR = 8,
IMPORT_BAZ = 9,
}
#endregion
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ImportMessage : pb::GeneratedMessage<ImportMessage, ImportMessage.Builder> {
private ImportMessage() { }
private static readonly ImportMessage defaultInstance = new ImportMessage().MakeReadOnly();
private static readonly string[] _importMessageFieldNames = new string[] { "d" };
private static readonly uint[] _importMessageFieldTags = new uint[] { 8 };
public static ImportMessage DefaultInstance {
get { return defaultInstance; }
}
public override ImportMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ImportMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessage, ImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _importMessageFieldNames;
if (hasD) {
output.WriteInt32(1, field_names[0], D);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasD) {
size += pb::CodedOutputStream.ComputeInt32Size(1, D);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ImportMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ImportMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ImportMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ImportMessage result;
private ImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
ImportMessage original = result;
result = new ImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ImportMessage MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.Descriptor; }
}
public override ImportMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance; }
}
public override ImportMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ImportMessage) {
return MergeFrom((ImportMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasD) {
D = other.D;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_importMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _importMessageFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasD = input.ReadInt32(ref result.d_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasD {
get { return result.hasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
PrepareBuilder();
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
PrepareBuilder();
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

File diff suppressed because it is too large Load Diff

@ -0,0 +1,88 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
namespace Google.ProtocolBuffers.ProtoDump
{
/// <summary>
/// Small utility to load a binary message and dump it in text form
/// </summary>
internal class Program
{
private static int Main(string[] args)
{
if (args.Length != 2)
{
Console.Error.WriteLine("Usage: ProtoDump <descriptor type name> <input data>");
Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,");
Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project");
return 1;
}
IMessage defaultMessage;
try
{
defaultMessage = MessageUtil.GetDefaultMessage(args[0]);
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
return 1;
}
try
{
IBuilder builder = defaultMessage.WeakCreateBuilderForType();
if (builder == null)
{
Console.Error.WriteLine("Unable to create builder");
return 1;
}
byte[] inputData = File.ReadAllBytes(args[1]);
builder.WeakMergeFrom(ByteString.CopyFrom(inputData));
Console.WriteLine(TextFormat.PrintToString(builder.WeakBuild()));
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine("Error: {0}", e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
return 1;
}
}
}
}

@ -0,0 +1,30 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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("ProtoDump")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProtoDump")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("2.4.1.555")]
[assembly: AssemblyVersion("2.4.1.555")]
[assembly: AssemblyFileVersion("2.4.1.555")]

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D7282E99-2DC3-405B-946F-177DB2FD2AE2}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoDump</RootNamespace>
<AssemblyName>ProtoDump</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<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>
<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>

@ -0,0 +1,150 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
using NUnit.Framework;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Tests for the dependency resolution in Generator.
/// </summary>
[TestFixture]
public class DependencyResolutionTest
{
[Test]
public void TwoDistinctFiles()
{
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
var set = new List<FileDescriptorProto> { first, second };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(0, converted[0].Dependencies.Count);
Assert.AreEqual("Second", converted[1].Name);
Assert.AreEqual(0, converted[1].Dependencies.Count);
}
[Test]
public void FirstDependsOnSecond()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second = new FileDescriptorProto.Builder {Name = "Second"}.Build();
var set = new List<FileDescriptorProto> { first, second };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(1, converted[0].Dependencies.Count);
Assert.AreEqual(converted[1], converted[0].Dependencies[0]);
Assert.AreEqual("Second", converted[1].Name);
Assert.AreEqual(0, converted[1].Dependencies.Count);
}
[Test]
public void SecondDependsOnFirst()
{
FileDescriptorProto first = new FileDescriptorProto.Builder {Name = "First"}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
var set = new List<FileDescriptorProto> { first, second };
IList<FileDescriptor> converted = Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.AreEqual(2, converted.Count);
Assert.AreEqual("First", converted[0].Name);
Assert.AreEqual(0, converted[0].Dependencies.Count);
Assert.AreEqual("Second", converted[1].Name);
Assert.AreEqual(1, converted[1].Dependencies.Count);
Assert.AreEqual(converted[0], converted[1].Dependencies[0]);
}
[Test]
public void CircularDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
FileDescriptorProto second =
new FileDescriptorProto.Builder {Name = "Second", DependencyList = {"First"}}.Build();
var set = new List<FileDescriptorProto> { first, second };
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
}
catch (DependencyResolutionException)
{
// Expected
}
}
[Test]
public void MissingDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"Second"}}.Build();
var set = new List<FileDescriptorProto> { first };
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
}
catch (DependencyResolutionException)
{
// Expected
}
}
[Test]
public void SelfDependency()
{
FileDescriptorProto first =
new FileDescriptorProto.Builder {Name = "First", DependencyList = {"First"}}.Build();
var set = new List<FileDescriptorProto> { first };
try
{
Generator.ConvertDescriptors(CSharpFileOptions.DefaultInstance, set);
Assert.Fail("Expected exception");
}
catch (DependencyResolutionException)
{
// Expected
}
}
}
}

@ -0,0 +1,30 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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("ProtoGen.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProtoGen.Test")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("2.4.1.555")]
[assembly: AssemblyVersion("2.4.1.555")]
[assembly: AssemblyFileVersion("2.4.1.555")]

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C268DA4C-4004-47DA-AF23-44C983281A68}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoGen</RootNamespace>
<AssemblyName>Google.ProtocolBuffers.ProtoGen.Test</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE;$(EnvironmentFlavor);$(EnvironmentTemplate)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>TRACE;$(EnvironmentFlavor);$(EnvironmentTemplate)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\NUnit\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DependencyResolutionTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TempFile.cs" />
<Compile Include="TestPreprocessing.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
<ProjectReference Include="..\ProtoGen\ProtoGen.csproj">
<Project>{250ADE34-82FD-4BAE-86D5-985FBE589C4A}</Project>
<Name>ProtoGen</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="..\..\lib\protoc.exe">
<Link>protoc.exe</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="..\..\protos\google\protobuf\csharp_options.proto">
<Link>google\protobuf\csharp_options.proto</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="..\..\protos\google\protobuf\descriptor.proto">
<Link>google\protobuf\descriptor.proto</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</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>
-->
<PropertyGroup>
<StartAction>Program</StartAction>
<StartProgram>$(ProjectDir)..\..\lib\NUnit\tools\nunit-console.exe</StartProgram>
<StartArguments>/nologo /noshadow /labels /wait $(AssemblyName).dll</StartArguments>
<StartWorkingDirectory>$(ProjectDir)$(OutputPath)</StartWorkingDirectory>
</PropertyGroup>
</Project>

@ -0,0 +1,683 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Tests protoc-gen-cs plugin.
/// </summary>
[TestFixture]
[Category("Preprocessor")]
public partial class ProtocGenCsUnittests
{
private static readonly string TempPath = Path.Combine(Path.GetTempPath(), "protoc-gen-cs.Test");
private const string DefaultProto =
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}";
#region TestFixture SetUp/TearDown
private static readonly string OriginalWorkingDirectory = Environment.CurrentDirectory;
private StringBuilder buffer = new StringBuilder();
[TestFixtureSetUp]
public virtual void Setup()
{
Teardown();
Directory.CreateDirectory(TempPath);
Environment.CurrentDirectory = TempPath;
this.buffer.Length = 0;
}
[TestFixtureTearDown]
public virtual void Teardown()
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
if (Directory.Exists(TempPath))
{
Directory.Delete(TempPath, true);
}
}
#endregion
#region Helper Methods RunProtoGen / RunCsc
private void RunProtoc(int expect, string protoFile, params string[] args)
{
string protoPath = string.Format("-I. -I\"{0}\"", OriginalWorkingDirectory);
string plugin = string.Format("--plugin=\"{0}\"", Path.Combine(OriginalWorkingDirectory, "protoc-gen-cs.exe"));
string csOut = args.Length == 0 ? "--cs_out=." : string.Format("--cs_out=\"{0}:.\"", string.Join(" ", args));
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WorkingDirectory = TempPath;
p.StartInfo.FileName = Path.Combine(OriginalWorkingDirectory, "protoc.exe");
p.StartInfo.Arguments = string.Join(" ", new string[] { plugin, csOut, protoPath, protoFile });
p.Start();
// Read the output stream first and then wait.
buffer.AppendLine(string.Format("{0}> \"{1}\" {2}", p.StartInfo.WorkingDirectory, p.StartInfo.FileName, p.StartInfo.Arguments));
buffer.AppendLine(p.StandardError.ReadToEnd());
buffer.AppendLine(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Assert.AreEqual(expect, p.ExitCode, this.buffer.ToString());
}
private Assembly RunCsc(int expect, params string[] sources)
{
using (TempFile tempDll = new TempFile(String.Empty))
{
tempDll.ChangeExtension(".dll");
List<string> args = new List<string>();
args.Add("/nologo");
args.Add("/target:library");
args.Add("/debug-");
args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath));
args.Add("/r:System.dll");
args.Add(String.Format(@"""/r:{0}""",
typeof(Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly.
Location));
args.AddRange(sources);
string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"csc.exe");
ProcessStartInfo psi = new ProcessStartInfo(exe);
psi.WorkingDirectory = TempPath;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.Arguments = string.Join(" ", args.ToArray());
Process p = Process.Start(psi);
buffer.AppendLine(string.Format("{0}> \"{1}\" {2}", p.StartInfo.WorkingDirectory, p.StartInfo.FileName, p.StartInfo.Arguments));
buffer.AppendLine(p.StandardError.ReadToEnd());
buffer.AppendLine(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Assert.AreEqual(expect, p.ExitCode, this.buffer.ToString());
Assembly asm = null;
if (p.ExitCode == 0)
{
byte[] allbytes = File.ReadAllBytes(tempDll.TempPath);
asm = Assembly.Load(allbytes);
foreach (Type t in asm.GetTypes())
{
Debug.WriteLine(t.FullName, asm.FullName);
}
}
return asm;
}
}
#endregion
// *******************************************************************
// The following tests excercise options for protogen.exe
// *******************************************************************
[Test]
public void TestProtoFile()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithConflictingType()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test, true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-namespace=MyNewNamespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaClassName()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrellaClassname", true, true);
}
}
[Test]
public void TestProtoFileWithNestedClass()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-nest_classes=true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExpandedNsDirectories()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-expand_namespace_directories=true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNewExtension()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".Generated.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-file_extension=.Generated.cs");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-umbrella_namespace=MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-nest_classes=true", "-umbrella_namespace=MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExplicitEmptyUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
//Forces the umbrella class to not use a namespace even if a collision with a type is detected.
RunProtoc(0, proto.TempPath, "-umbrella_namespace=");
//error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed
RunCsc(1, source.TempPath);
}
}
[Test]
public void TestProtoFileWithNewOutputFolder()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(1, proto.TempPath, "-output_directory=generated-code");
Directory.CreateDirectory("generated-code");
RunProtoc(0, proto.TempPath, "-output_directory=generated-code");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileAndIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
RunProtoc(0, proto.TempPath);
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithoutIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Without the option this fails due to being unable to resolve google/protobuf descriptors
RunProtoc(0, proto.TempPath);
}
}
// *******************************************************************
// The following tests excercise options for protoc.exe
// *******************************************************************
[Test]
public void TestProtoFileWithIncludeImports()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
} ")
)
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//if you specify the protoc option --include_imports this should build three source files
RunProtoc(0, proto.TempPath);
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
//Seems the --proto_path or -I option is non-functional for me. Maybe others have luck?
[Test]
public void TestProtoFileInDifferentDirectory()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
// *******************************************************************
// Handling of mutliple input files
// *******************************************************************
[Test]
public void TestMultipleProtoFiles()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
RunProtoc(0, proto1.TempPath);
RunProtoc(0, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestOneProtoFileWithBufferFile()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
//build the proto buffer for MyMessage
RunProtoc(0, proto1.TempPath);
//build the MyMessageList proto-buffer and generate code by including MyMessage.pb
RunProtoc(0, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestProtoFileWithService()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoc(0, proto.TempPath, "-nest_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
[Test]
public void TestProtoFileWithServiceInternal()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoc(0, proto.TempPath, "-nest_classes=false", "-public_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
private static void CopyInGoogleProtoFiles()
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
}
}
}

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Google.ProtocolBuffers.ProtoGen
{
internal class ProtoFile : TempFile
{
public ProtoFile(string filename, string contents)
: base(filename, contents)
{
}
}
internal class TempFile : IDisposable
{
private string tempFile;
public static TempFile Attach(string path)
{
return new TempFile(path, null);
}
protected TempFile(string filename, string contents)
{
tempFile = filename;
if (contents != null)
{
File.WriteAllText(tempFile, contents, new UTF8Encoding(false));
}
}
public TempFile(string contents)
: this(Path.GetTempFileName(), contents)
{
}
public string TempPath
{
get { return tempFile; }
}
public void ChangeExtension(string ext)
{
string newFile = Path.ChangeExtension(tempFile, ext);
File.Move(tempFile, newFile);
tempFile = newFile;
}
public void Dispose()
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
}

@ -0,0 +1,733 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace Google.ProtocolBuffers.ProtoGen
{
[TestFixture]
[Category("Preprocessor")]
public partial class TestPreprocessing
{
private static readonly string TempPath = Path.Combine(Path.GetTempPath(), "proto-gen-test");
private const string DefaultProto =
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}";
#region TestFixture SetUp/TearDown
private static readonly string OriginalWorkingDirectory = Environment.CurrentDirectory;
[TestFixtureSetUp]
public virtual void Setup()
{
Teardown();
Directory.CreateDirectory(TempPath);
Environment.CurrentDirectory = TempPath;
}
[TestFixtureTearDown]
public virtual void Teardown()
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
if (Directory.Exists(TempPath))
{
Directory.Delete(TempPath, true);
}
}
#endregion
#region Helper Methods RunProtoGen / RunCsc
private void RunProtoGen(int expect, params string[] args)
{
TextWriter tout = Console.Out, terr = Console.Error;
StringWriter temp = new StringWriter();
Console.SetOut(temp);
Console.SetError(temp);
try
{
Assert.AreEqual(expect, ProgramPreprocess.Run(args), "ProtoGen Failed: {0}", temp);
}
finally
{
Console.SetOut(tout);
Console.SetError(terr);
}
}
private Assembly RunCsc(int expect, params string[] sources)
{
using (TempFile tempDll = new TempFile(String.Empty))
{
tempDll.ChangeExtension(".dll");
List<string> args = new List<string>();
args.Add("/nologo");
args.Add("/target:library");
args.Add("/debug-");
args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath));
args.Add("/r:System.dll");
args.Add(String.Format(@"""/r:{0}""",
typeof(Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly.
Location));
args.AddRange(sources);
string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"csc.exe");
ProcessStartInfo psi = new ProcessStartInfo(exe);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.Arguments = string.Join(" ", args.ToArray());
Process p = Process.Start(psi);
p.WaitForExit();
string errorText = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
Assert.AreEqual(expect, p.ExitCode, "CSC.exe Failed: {0}", errorText);
Assembly asm = null;
if (p.ExitCode == 0)
{
byte[] allbytes = File.ReadAllBytes(tempDll.TempPath);
asm = Assembly.Load(allbytes);
foreach (Type t in asm.GetTypes())
{
Debug.WriteLine(t.FullName, asm.FullName);
}
}
return asm;
}
}
#endregion
// *******************************************************************
// The following tests excercise options for protogen.exe
// *******************************************************************
[Test]
public void TestProtoFile()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithConflictingType()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
RunProtoGen(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test, true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-namespace:MyNewNamespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaClassName()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrellaClassname", true, true);
}
}
[Test]
public void TestProtoFileWithNestedClass()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-nest_classes:true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExpandedNsDirectories()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-expand_namespace_directories:true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNewExtension()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".Generated.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-file_extension:.Generated.cs");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-umbrella_namespace:MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(0, proto.TempPath, "-nest_classes:true", "-umbrella_namespace:MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExplicitEmptyUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
//Forces the umbrella class to not use a namespace even if a collision with a type is detected.
RunProtoGen(0, proto.TempPath, "-umbrella_namespace:");
//error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed
RunCsc(1, source.TempPath);
}
}
[Test]
public void TestProtoFileWithNewOutputFolder()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoGen(1, proto.TempPath, "-output_directory:generated-code");
Directory.CreateDirectory("generated-code");
RunProtoGen(0, proto.TempPath, "-output_directory:generated-code");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileAndIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithoutIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Without the option this fails due to being unable to resolve google/protobuf descriptors
RunProtoGen(1, proto.TempPath, "-ignore_google_protobuf:false");
}
}
// *******************************************************************
// The following tests excercise options for protoc.exe
// *******************************************************************
[Test]
public void TestProtoFileWithIncludeImports()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
} ")
)
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//if you specify the protoc option --include_imports this should build three source files
RunProtoGen(0, proto.TempPath, "--include_imports");
Assert.AreEqual(3, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithIncludeImportsAndIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
} ")
)
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Even with --include_imports, if you provide -ignore_google_protobuf:true you only get the one source file
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "--include_imports");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileKeepingTheProtoBuffer()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile protobuf = TempFile.Attach(test + ".pb"))
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
} ")
)
{
RunProtoGen(0, proto.TempPath, "--descriptor_set_out=" + protobuf.TempPath);
Assert.IsTrue(File.Exists(protobuf.TempPath), "Missing: " + protobuf.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
//Seems the --proto_path or -I option is non-functional for me. Maybe others have luck?
[Test]
public void TestProtoFileInDifferentDirectory()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
RunProtoGen(0, proto.TempPath, "--proto_path=" + TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
// *******************************************************************
// Handling of mutliple input files
// *******************************************************************
[Test]
public void TestMultipleProtoFiles()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
RunProtoGen(0, proto1.TempPath, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestOneProtoFileWithBufferFile()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (TempFile protobuf = TempFile.Attach("MyMessage.pb"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
//build the proto buffer for MyMessage
RunProtoGen(0, proto1.TempPath, "--descriptor_set_out=" + protobuf.TempPath);
//build the MyMessageList proto-buffer and generate code by including MyMessage.pb
RunProtoGen(0, proto2.TempPath, protobuf.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestProtoFileWithService()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "-nest_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
[Test]
public void TestProtoFileWithServiceInternal()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoGen(0, proto.TempPath, "-ignore_google_protobuf:true", "-nest_classes=false", "-public_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
private static void CopyInGoogleProtoFiles()
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
}
}
}

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnvironmentFlavor>CLIENTPROFILE</EnvironmentFlavor>
<EnvironmentTemplate>NET35</EnvironmentTemplate>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C1024C9C-8176-48C3-B547-B9F6DF6B80A6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoGen</RootNamespace>
<AssemblyName>protoc-gen-cs.Test</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\NET35\Debug</OutputPath>
<IntermediateOutputPath>obj\NET35\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE;$(EnvironmentFlavor);$(EnvironmentTemplate)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET35\Release</OutputPath>
<IntermediateOutputPath>obj\NET35\Release\</IntermediateOutputPath>
<DefineConstants>TRACE;$(EnvironmentFlavor);$(EnvironmentTemplate)</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\NUnit\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ProtocGenCsUnittests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TempFile.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908bdce-d925-43f3-94ac-a531e6df2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
<ProjectReference Include="..\ProtoGen\protoc-gen-cs.csproj">
<Project>{250ade34-82fd-4bae-86d5-985fbe589c4b}</Project>
<Name>protoc-gen-cs</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="..\..\lib\protoc.exe">
<Link>protoc.exe</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="..\..\protos\google\protobuf\csharp_options.proto">
<Link>google\protobuf\csharp_options.proto</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="..\..\protos\google\protobuf\descriptor.proto">
<Link>google\protobuf\descriptor.proto</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</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>
-->
<PropertyGroup>
<StartAction>Program</StartAction>
<StartProgram>$(ProjectDir)..\..\lib\NUnit\tools\nunit-console.exe</StartProgram>
<StartArguments>/nologo /noshadow /labels /wait $(AssemblyName).dll</StartArguments>
<StartWorkingDirectory>$(ProjectDir)$(OutputPath)</StartWorkingDirectory>
</PropertyGroup>
</Project>

@ -0,0 +1,55 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Exception thrown when dependencies within a descriptor set can't be resolved.
/// </summary>
public sealed class DependencyResolutionException : Exception
{
public DependencyResolutionException(string message) : base(message)
{
}
public DependencyResolutionException(string format, params object[] args)
: base(string.Format(format, args))
{
}
}
}

@ -0,0 +1,106 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Utility class for determining namespaces etc.
/// </summary>
internal static class DescriptorUtil
{
internal static string GetFullUmbrellaClassName(IDescriptor descriptor)
{
CSharpFileOptions options = descriptor.File.CSharpOptions;
string result = options.Namespace;
if (result != "")
{
result += '.';
}
result += GetQualifiedUmbrellaClassName(options);
return "global::" + result;
}
/// <summary>
/// Evaluates the options and returns the qualified name of the umbrella class
/// relative to the descriptor type's namespace. Basically concatenates the
/// UmbrellaNamespace + UmbrellaClassname fields.
/// </summary>
internal static string GetQualifiedUmbrellaClassName(CSharpFileOptions options)
{
string fullName = options.UmbrellaClassname;
if (!options.NestClasses && options.UmbrellaNamespace != "")
{
fullName = String.Format("{0}.{1}", options.UmbrellaNamespace, options.UmbrellaClassname);
}
return fullName;
}
internal static string GetMappedTypeName(MappedType type)
{
switch (type)
{
case MappedType.Int32:
return "int";
case MappedType.Int64:
return "long";
case MappedType.UInt32:
return "uint";
case MappedType.UInt64:
return "ulong";
case MappedType.Single:
return "float";
case MappedType.Double:
return "double";
case MappedType.Boolean:
return "bool";
case MappedType.String:
return "string";
case MappedType.ByteString:
return "pb::ByteString";
case MappedType.Enum:
return null;
case MappedType.Message:
return null;
default:
throw new ArgumentOutOfRangeException("Unknown mapped type " + type);
}
}
}
}

@ -0,0 +1,148 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal class EnumFieldGenerator : FieldGeneratorBase, IFieldSourceGenerator
{
internal EnumFieldGenerator(FieldDescriptor descriptor, int fieldOrdinal)
: base(descriptor, fieldOrdinal)
{
}
public void GenerateMembers(TextGenerator writer)
{
writer.WriteLine("private bool has{0};", PropertyName);
writer.WriteLine("private {0} {1}_ = {2};", TypeName, Name, DefaultValue);
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return has{0}; }}", PropertyName);
writer.WriteLine("}");
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return {0}_; }}", Name);
writer.WriteLine("}");
}
public void GenerateBuilderMembers(TextGenerator writer)
{
AddDeprecatedFlag(writer);
writer.WriteLine("public bool Has{0} {{", PropertyName);
writer.WriteLine(" get {{ return result.has{0}; }}", PropertyName);
writer.WriteLine("}");
AddPublicMemberAttributes(writer);
writer.WriteLine("public {0} {1} {{", TypeName, PropertyName);
writer.WriteLine(" get {{ return result.{0}; }}", PropertyName);
writer.WriteLine(" set {{ Set{0}(value); }}", PropertyName);
writer.WriteLine("}");
AddPublicMemberAttributes(writer);
writer.WriteLine("public Builder Set{0}({1} value) {{", PropertyName, TypeName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine(" result.{0}_ = value;", Name);
writer.WriteLine(" return this;");
writer.WriteLine("}");
AddDeprecatedFlag(writer);
writer.WriteLine("public Builder Clear{0}() {{", PropertyName);
writer.WriteLine(" PrepareBuilder();");
writer.WriteLine(" result.has{0} = false;", PropertyName);
writer.WriteLine(" result.{0}_ = {1};", Name, DefaultValue);
writer.WriteLine(" return this;");
writer.WriteLine("}");
}
public void GenerateMergingCode(TextGenerator writer)
{
writer.WriteLine("if (other.Has{0}) {{", PropertyName);
writer.WriteLine(" {0} = other.{0};", PropertyName);
writer.WriteLine("}");
}
public void GenerateBuildingCode(TextGenerator writer)
{
// Nothing to do here for enum types
}
public void GenerateParsingCode(TextGenerator writer)
{
writer.WriteLine("object unknown;");
writer.WriteLine("if(input.ReadEnum(ref result.{0}_, out unknown)) {{", Name);
writer.WriteLine(" result.has{0} = true;", PropertyName);
writer.WriteLine("} else if(unknown is int) {");
if (!UseLiteRuntime)
{
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong)(int)unknown);", Number);
}
writer.WriteLine("}");
}
public void GenerateSerializationCode(TextGenerator writer)
{
writer.WriteLine("if (has{0}) {{", PropertyName);
writer.WriteLine(" output.WriteEnum({0}, field_names[{2}], (int) {1}, {1});", Number, PropertyName,
FieldOrdinal);
writer.WriteLine("}");
}
public void GenerateSerializedSizeCode(TextGenerator writer)
{
writer.WriteLine("if (has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.ComputeEnumSize({0}, (int) {1});", Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer)
{
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer)
{
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;",
PropertyName, Name);
}
public override void WriteToString(TextGenerator writer)
{
writer.WriteLine("PrintField(\"{0}\", has{1}, {2}_, writer);", Descriptor.Name, PropertyName, Name);
}
}
}

@ -0,0 +1,62 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal class EnumGenerator : SourceGeneratorBase<EnumDescriptor>, ISourceGenerator
{
internal EnumGenerator(EnumDescriptor descriptor) : base(descriptor)
{
}
// TODO(jonskeet): Write out enum descriptors? Can be retrieved from file...
public void Generate(TextGenerator writer)
{
WriteGeneratedCodeAttributes(writer);
writer.WriteLine("{0} enum {1} {{", ClassAccessLevel, Descriptor.Name);
writer.Indent();
foreach (EnumValueDescriptor value in Descriptor.Values)
{
writer.WriteLine("{0} = {1},", value.Name, value.Number);
}
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
}
}
}

@ -0,0 +1,183 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal class ExtensionGenerator : FieldGeneratorBase, ISourceGenerator
{
private readonly string extends;
private readonly string scope;
private readonly string type;
private readonly string name;
internal ExtensionGenerator(FieldDescriptor descriptor)
: base(descriptor, 0)
{
if (Descriptor.ExtensionScope != null)
{
scope = GetClassName(Descriptor.ExtensionScope);
}
else
{
scope = DescriptorUtil.GetFullUmbrellaClassName(Descriptor.File);
}
switch (Descriptor.MappedType)
{
case MappedType.Message:
type = GetClassName(Descriptor.MessageType);
break;
case MappedType.Enum:
type = GetClassName(Descriptor.EnumType);
break;
default:
type = DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
break;
}
extends = GetClassName(Descriptor.ContainingType);
name = Descriptor.CSharpOptions.PropertyName;
}
public void Generate(TextGenerator writer)
{
if (Descriptor.File.CSharpOptions.ClsCompliance && GetFieldConstantName(Descriptor).StartsWith("_"))
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber);
if (UseLiteRuntime)
{
if (Descriptor.MappedType == MappedType.Message && Descriptor.MessageType.Options.MessageSetWireFormat)
{
throw new ArgumentException(
"option message_set_wire_format = true; is not supported in Lite runtime extensions.");
}
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::{4}<{1}, {2}> {3};", ClassAccessLevel, extends, type, name,
Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite");
}
else if (Descriptor.IsRepeated)
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type,
name);
}
else
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::GeneratedExtensionBase<{1}> {2};", ClassAccessLevel, type, name);
}
}
internal void GenerateStaticVariableInitializers(TextGenerator writer)
{
if (UseLiteRuntime)
{
writer.WriteLine("{0}.{1} = ", scope, name);
writer.Indent();
writer.WriteLine("new pb::{0}<{1}, {2}>(",
Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite",
extends, type);
writer.Indent();
writer.WriteLine("\"{0}\",", Descriptor.FullName);
writer.WriteLine("{0}.DefaultInstance,", extends);
if (!Descriptor.IsRepeated)
{
writer.WriteLine("{0},",
Descriptor.HasDefaultValue
? DefaultValue
: IsNullableType ? "null" : "default(" + type + ")");
}
writer.WriteLine("{0},",
(Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null");
writer.WriteLine("{0},",
(Descriptor.MappedType == MappedType.Enum) ? "new EnumLiteMap<" + type + ">()" : "null");
writer.WriteLine("{0}.{1}FieldNumber,", scope, name);
writer.Write("pbd::FieldType.{0}", Descriptor.FieldType);
if (Descriptor.IsRepeated)
{
writer.WriteLine(",");
writer.Write(Descriptor.IsPacked ? "true" : "false");
}
writer.Outdent();
writer.WriteLine(");");
writer.Outdent();
}
else if (Descriptor.IsRepeated)
{
writer.WriteLine(
"{0}.{1} = pb::GeneratedRepeatExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope,
name, type, Descriptor.Index);
}
else
{
writer.WriteLine(
"{0}.{1} = pb::GeneratedSingleExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope,
name, type, Descriptor.Index);
}
}
internal void GenerateExtensionRegistrationCode(TextGenerator writer)
{
writer.WriteLine("registry.Add({0}.{1});", scope, name);
}
public override void WriteHash(TextGenerator writer)
{
}
public override void WriteEquals(TextGenerator writer)
{
}
public override void WriteToString(TextGenerator writer)
{
}
}
}

@ -0,0 +1,389 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Globalization;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
internal abstract class FieldGeneratorBase : SourceGeneratorBase<FieldDescriptor>
{
private readonly int _fieldOrdinal;
protected FieldGeneratorBase(FieldDescriptor descriptor, int fieldOrdinal)
: base(descriptor)
{
_fieldOrdinal = fieldOrdinal;
}
public abstract void WriteHash(TextGenerator writer);
public abstract void WriteEquals(TextGenerator writer);
public abstract void WriteToString(TextGenerator writer);
public int FieldOrdinal
{
get { return _fieldOrdinal; }
}
private static bool AllPrintableAscii(string text)
{
foreach (char c in text)
{
if (c < 0x20 || c > 0x7e)
{
return false;
}
}
return true;
}
/// <summary>
/// This returns true if the field has a non-default default value. For instance this returns
/// false for numerics with a default of zero '0', or booleans with a default of false.
/// </summary>
protected bool HasDefaultValue
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
{
IConvertible value = (IConvertible) Descriptor.DefaultValue;
return value.ToString(CultureInfo.InvariantCulture) != "0";
}
case FieldType.Bool:
return ((bool) Descriptor.DefaultValue) == true;
default:
return true;
}
}
}
/// <remarks>Copy exists in ExtensionGenerator.cs</remarks>
protected string DefaultValue
{
get
{
string suffix = "";
switch (Descriptor.FieldType)
{
case FieldType.Float:
suffix = "F";
break;
case FieldType.Double:
suffix = "D";
break;
case FieldType.Int64:
suffix = "L";
break;
case FieldType.UInt64:
suffix = "UL";
break;
}
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
{
// The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable.
IConvertible value = (IConvertible) Descriptor.DefaultValue;
//a few things that must be handled explicitly
if (Descriptor.FieldType == FieldType.Double && value is double)
{
if (double.IsNaN((double) value))
{
return "double.NaN";
}
if (double.IsPositiveInfinity((double) value))
{
return "double.PositiveInfinity";
}
if (double.IsNegativeInfinity((double) value))
{
return "double.NegativeInfinity";
}
}
else if (Descriptor.FieldType == FieldType.Float && value is float)
{
if (float.IsNaN((float) value))
{
return "float.NaN";
}
if (float.IsPositiveInfinity((float) value))
{
return "float.PositiveInfinity";
}
if (float.IsNegativeInfinity((float) value))
{
return "float.NegativeInfinity";
}
}
return value.ToString(CultureInfo.InvariantCulture) + suffix;
}
case FieldType.Bool:
return (bool) Descriptor.DefaultValue ? "true" : "false";
case FieldType.Bytes:
if (!Descriptor.HasDefaultValue)
{
return "pb::ByteString.Empty";
}
if (UseLiteRuntime && Descriptor.DefaultValue is ByteString)
{
string temp = (((ByteString) Descriptor.DefaultValue).ToBase64());
return String.Format("pb::ByteString.FromBase64(\"{0}\")", temp);
}
return string.Format("(pb::ByteString) {0}.Descriptor.Fields[{1}].DefaultValue",
GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.String:
if (AllPrintableAscii(Descriptor.Proto.DefaultValue))
{
// All chars are ASCII and printable. In this case we only
// need to escape quotes and backslashes.
return "\"" + Descriptor.Proto.DefaultValue
.Replace("\\", "\\\\")
.Replace("'", "\\'")
.Replace("\"", "\\\"")
+ "\"";
}
if (UseLiteRuntime && Descriptor.DefaultValue is String)
{
string temp = Convert.ToBase64String(
Encoding.UTF8.GetBytes((String) Descriptor.DefaultValue));
return String.Format("pb::ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp);
}
return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue",
GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.Enum:
return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name;
case FieldType.Message:
case FieldType.Group:
return TypeName + ".DefaultInstance";
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected string PropertyName
{
get { return Descriptor.CSharpOptions.PropertyName; }
}
protected string Name
{
get { return NameHelpers.UnderscoresToCamelCase(GetFieldName(Descriptor)); }
}
protected int Number
{
get { return Descriptor.FieldNumber; }
}
protected void AddNullCheck(TextGenerator writer)
{
AddNullCheck(writer, "value");
}
protected void AddNullCheck(TextGenerator writer, string name)
{
if (IsNullableType)
{
writer.WriteLine(" pb::ThrowHelper.ThrowIfNull({0}, \"{0}\");", name);
}
}
protected void AddPublicMemberAttributes(TextGenerator writer)
{
AddDeprecatedFlag(writer);
AddClsComplianceCheck(writer);
}
protected void AddClsComplianceCheck(TextGenerator writer)
{
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
}
protected bool IsObsolete { get { return Descriptor.Options.Deprecated; } }
/// <summary>
/// Writes [global::System.ObsoleteAttribute()] if the member is obsolete
/// </summary>
protected void AddDeprecatedFlag(TextGenerator writer)
{
if (IsObsolete)
{
writer.WriteLine("[global::System.ObsoleteAttribute()]");
}
}
/// <summary>
/// For encodings with fixed sizes, returns that size in bytes. Otherwise
/// returns -1. TODO(jonskeet): Make this less ugly.
/// </summary>
protected int FixedSize
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.Enum:
case FieldType.Bytes:
case FieldType.String:
case FieldType.Message:
case FieldType.Group:
return -1;
case FieldType.Float:
return WireFormat.FloatSize;
case FieldType.SFixed32:
return WireFormat.SFixed32Size;
case FieldType.Fixed32:
return WireFormat.Fixed32Size;
case FieldType.Double:
return WireFormat.DoubleSize;
case FieldType.SFixed64:
return WireFormat.SFixed64Size;
case FieldType.Fixed64:
return WireFormat.Fixed64Size;
case FieldType.Bool:
return WireFormat.BoolSize;
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected bool IsNullableType
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Float:
case FieldType.Double:
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
case FieldType.Bool:
case FieldType.Enum:
return false;
case FieldType.Bytes:
case FieldType.String:
case FieldType.Message:
case FieldType.Group:
return true;
default:
throw new InvalidOperationException("Invalid field descriptor type");
}
}
}
protected string TypeName
{
get
{
switch (Descriptor.FieldType)
{
case FieldType.Enum:
return GetClassName(Descriptor.EnumType);
case FieldType.Message:
case FieldType.Group:
return GetClassName(Descriptor.MessageType);
default:
return DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
}
}
}
protected string MessageOrGroup
{
get { return Descriptor.FieldType == FieldType.Group ? "Group" : "Message"; }
}
/// <summary>
/// Returns the type name as used in CodedInputStream method names: SFixed32, UInt32 etc.
/// </summary>
protected string CapitalizedTypeName
{
get
{
// Our enum names match perfectly. How serendipitous.
return Descriptor.FieldType.ToString();
}
}
}
}

@ -0,0 +1,267 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Compiler.PluginProto;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Code generator for protocol buffers. Only C# is supported at the moment.
/// </summary>
public sealed class Generator
{
private readonly GeneratorOptions options;
private Generator(GeneratorOptions options)
{
options.Validate();
this.options = options;
}
/// <summary>
/// Returns a generator configured with the specified options.
/// </summary>
public static Generator CreateGenerator(GeneratorOptions options)
{
return new Generator(options);
}
public void Generate(CodeGeneratorRequest request, CodeGeneratorResponse.Builder response)
{
IList<FileDescriptor> descriptors = ConvertDescriptors(options.FileOptions, request.ProtoFileList);
// Combine with options from command line
foreach (FileDescriptor descriptor in descriptors)
{
descriptor.ConfigureWithDefaultOptions(options.FileOptions);
}
bool duplicates = false;
Dictionary<string, bool> names = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (FileDescriptor descriptor in descriptors)
{
string file = GetOutputFile(descriptor, false);
if (names.ContainsKey(file))
{
duplicates = true;
break;
}
names.Add(file, true);
}
//ROK - Changed to dictionary from HashSet to allow 2.0 compile
var filesToGenerate = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in request.FileToGenerateList)
{
filesToGenerate[item] = null;
}
foreach (FileDescriptor descriptor in descriptors)
{
// Optionally exclude descriptors in google.protobuf
if (descriptor.CSharpOptions.IgnoreGoogleProtobuf && descriptor.Package == "google.protobuf")
{
continue;
}
if (filesToGenerate.ContainsKey(descriptor.Name))
{
Generate(descriptor, duplicates, response);
}
}
}
/// <summary>
/// Generates code for a particular file. All dependencies must
/// already have been resolved.
/// </summary>
private void Generate(FileDescriptor descriptor, bool duplicates, CodeGeneratorResponse.Builder response)
{
var code = new StringBuilder();
var ucg = new UmbrellaClassGenerator(descriptor);
using (StringWriter textWriter = new StringWriter(code))
{
TextGenerator writer = new TextGenerator(textWriter, options.LineBreak);
ucg.Generate(writer);
}
response.AddFile(new CodeGeneratorResponse.Types.File.Builder
{
Name = GetOutputFile(descriptor, duplicates),
Content = code.ToString(),
}.Build());
}
private string GetOutputFile(FileDescriptor descriptor, bool duplicates)
{
CSharpFileOptions fileOptions = descriptor.CSharpOptions;
string filename = descriptor.CSharpOptions.UmbrellaClassname + descriptor.CSharpOptions.FileExtension;
if (duplicates)
{
string namepart;
if (String.IsNullOrEmpty(descriptor.Name) || String.IsNullOrEmpty(namepart = Path.GetFileNameWithoutExtension(descriptor.Name)))
throw new ApplicationException("Duplicate UmbrellaClassname options created a file name collision.");
filename = namepart + descriptor.CSharpOptions.FileExtension;
}
string outputDirectory = descriptor.CSharpOptions.OutputDirectory;
if (fileOptions.ExpandNamespaceDirectories)
{
string package = fileOptions.Namespace;
if (!string.IsNullOrEmpty(package))
{
string[] bits = package.Split('.');
foreach (string bit in bits)
{
outputDirectory = Path.Combine(outputDirectory, bit);
}
}
}
// As the directory can be explicitly specified in options, we need to make sure it exists
Directory.CreateDirectory(outputDirectory);
return Path.Combine(outputDirectory, filename);
}
/// <summary>
/// Resolves any dependencies and converts FileDescriptorProtos into FileDescriptors.
/// The list returned is in the same order as the protos are listed in the descriptor set.
/// Note: this method is internal rather than private to allow testing.
/// </summary>
/// <exception cref="DependencyResolutionException">Not all dependencies could be resolved.</exception>
public static IList<FileDescriptor> ConvertDescriptors(CSharpFileOptions options,
IList<FileDescriptorProto> fileList)
{
FileDescriptor[] converted = new FileDescriptor[fileList.Count];
Dictionary<string, FileDescriptor> convertedMap = new Dictionary<string, FileDescriptor>();
int totalConverted = 0;
bool madeProgress = true;
while (madeProgress && totalConverted < converted.Length)
{
madeProgress = false;
for (int i = 0; i < converted.Length; i++)
{
if (converted[i] != null)
{
// Already done this one
continue;
}
FileDescriptorProto candidate = fileList[i];
FileDescriptor[] dependencies = new FileDescriptor[candidate.DependencyList.Count];
CSharpFileOptions.Builder builder = options.ToBuilder();
if (candidate.Options.HasExtension(CSharpOptions.CSharpFileOptions))
{
builder.MergeFrom(
candidate.Options.GetExtension(CSharpOptions.CSharpFileOptions));
}
CSharpFileOptions localOptions = builder.Build();
bool foundAllDependencies = true;
for (int j = 0; j < dependencies.Length; j++)
{
if (!convertedMap.TryGetValue(candidate.DependencyList[j], out dependencies[j]))
{
// We can auto-magically resolve these since we already have their description
// This way if the file is only referencing options it does not need to be built with the
// --include_imports definition.
if (localOptions.IgnoreGoogleProtobuf &&
(candidate.DependencyList[j] == "google/protobuf/csharp_options.proto"))
{
dependencies[j] = CSharpOptions.Descriptor;
continue;
}
if (localOptions.IgnoreGoogleProtobuf &&
(candidate.DependencyList[j] == "google/protobuf/descriptor.proto"))
{
dependencies[j] = DescriptorProtoFile.Descriptor;
continue;
}
foundAllDependencies = false;
break;
}
}
if (!foundAllDependencies)
{
continue;
}
madeProgress = true;
totalConverted++;
converted[i] = FileDescriptor.BuildFrom(candidate, dependencies);
convertedMap[candidate.Name] = converted[i];
}
}
if (!madeProgress)
{
StringBuilder remaining = new StringBuilder();
for (int i = 0; i < converted.Length; i++)
{
if (converted[i] == null)
{
if (remaining.Length != 0)
{
remaining.Append(", ");
}
FileDescriptorProto failure = fileList[i];
remaining.Append(failure.Name);
remaining.Append(":");
foreach (string dependency in failure.DependencyList)
{
if (!convertedMap.ContainsKey(dependency))
{
remaining.Append(" ");
remaining.Append(dependency);
}
}
remaining.Append(";");
}
}
throw new DependencyResolutionException("Unable to resolve all dependencies: " + remaining);
}
return Lists.AsReadOnly(converted);
}
}
}

@ -0,0 +1,330 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// All the configuration required for the generator - where to generate
/// output files, the location of input files etc. While this isn't immutable
/// in practice, the contents shouldn't be changed after being passed to
/// the generator.
/// </summary>
public sealed class GeneratorOptions
{
private static Dictionary<string, string> LineBreaks =
new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
{"Windows", "\r\n"},
{"Unix", "\n"},
{"Default", Environment.NewLine}
};
public IList<string> InputFiles { get; set; }
public GeneratorOptions()
{
LineBreak = Environment.NewLine;
}
/// <summary>
/// Attempts to validate the options, but doesn't throw an exception if they're invalid.
/// Instead, when this method returns false, the output variable will contain a collection
/// of reasons for the validation failure.
/// </summary>
/// <param name="reasons">Variable to receive a list of reasons in case of validation failure.</param>
/// <returns>true if the options are valid; false otherwise</returns>
public bool TryValidate(out IList<string> reasons)
{
List<string> tmpReasons = new List<string>();
ParseArguments(tmpReasons);
// Output directory validation
if (string.IsNullOrEmpty(FileOptions.OutputDirectory))
{
tmpReasons.Add("No output directory specified");
}
else
{
if (!Directory.Exists(FileOptions.OutputDirectory))
{
tmpReasons.Add("Specified output directory (" + FileOptions.OutputDirectory + " doesn't exist.");
}
}
// Input file validation (just in terms of presence)
if (InputFiles == null || InputFiles.Count == 0)
{
tmpReasons.Add("No input files specified");
}
else
{
foreach (string input in InputFiles)
{
FileInfo fi = new FileInfo(input);
if (!fi.Exists)
{
tmpReasons.Add("Input file " + input + " doesn't exist.");
}
}
}
if (tmpReasons.Count != 0)
{
reasons = tmpReasons;
return false;
}
reasons = null;
return true;
}
/// <summary>
/// Validates that all the options have been set and are valid,
/// throwing an exception if they haven't.
/// </summary>
/// <exception cref="InvalidOptionsException">The options are invalid.</exception>
public void Validate()
{
IList<string> reasons;
if (!TryValidate(out reasons))
{
throw new InvalidOptionsException(reasons);
}
}
// Raw arguments, used to provide defaults for proto file options
public IList<string> Arguments { get; set; }
[Obsolete("Please use GeneratorOptions.FileOptions.OutputDirectory instead")]
public string OutputDirectory
{
get { return FileOptions.OutputDirectory; }
set
{
CSharpFileOptions.Builder bld = FileOptions.ToBuilder();
bld.OutputDirectory = value;
FileOptions = bld.Build();
}
}
private static readonly Regex ArgMatch = new Regex(@"^[-/](?<name>[\w_]+?)[:=](?<value>.*)$");
private CSharpFileOptions fileOptions;
public CSharpFileOptions FileOptions
{
get { return fileOptions ?? (fileOptions = CSharpFileOptions.DefaultInstance); }
set { fileOptions = value; }
}
public string LineBreak { get; set; }
private void ParseArguments(IList<string> tmpReasons)
{
bool doHelp = Arguments.Count == 0;
InputFiles = new List<string>();
CSharpFileOptions.Builder builder = FileOptions.ToBuilder();
Dictionary<string, FieldDescriptor> fields =
new Dictionary<string, FieldDescriptor>(StringComparer.OrdinalIgnoreCase);
foreach (FieldDescriptor fld in builder.DescriptorForType.Fields)
{
fields.Add(fld.Name, fld);
}
foreach (string argument in Arguments)
{
if (StringComparer.OrdinalIgnoreCase.Equals("-help", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("/help", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("-?", argument) ||
StringComparer.OrdinalIgnoreCase.Equals("/?", argument))
{
doHelp = true;
break;
}
Match m = ArgMatch.Match(argument);
if (m.Success)
{
FieldDescriptor fld;
string name = m.Groups["name"].Value;
string value = m.Groups["value"].Value;
if (fields.TryGetValue(name, out fld))
{
object obj;
if (TryCoerceType(value, fld, out obj, tmpReasons))
{
builder[fld] = obj;
}
}
else if (name == "line_break")
{
string tmp;
if (LineBreaks.TryGetValue(value, out tmp))
{
LineBreak = tmp;
}
else
{
tmpReasons.Add("Invalid value for 'line_break': " + value + ".");
}
}
else if (!File.Exists(argument))
{
doHelp = true;
tmpReasons.Add("Unknown argument '" + name + "'.");
}
else
{
InputFiles.Add(argument);
}
}
else
{
InputFiles.Add(argument);
}
}
if (doHelp || InputFiles.Count == 0)
{
tmpReasons.Add("Arguments:");
foreach (KeyValuePair<string, FieldDescriptor> field in fields)
{
tmpReasons.Add(String.Format("-{0}=[{1}]", field.Key, field.Value.FieldType));
}
tmpReasons.Add("-line_break=[" + string.Join("|", new List<string>(LineBreaks.Keys).ToArray()) + "]");
tmpReasons.Add("followed by one or more file paths.");
}
else
{
FileOptions = builder.Build();
}
}
private static bool TryCoerceType(string text, FieldDescriptor field, out object value, IList<string> tmpReasons)
{
value = null;
switch (field.FieldType)
{
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
value = Int32.Parse(text);
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
value = Int64.Parse(text);
break;
case FieldType.UInt32:
case FieldType.Fixed32:
value = UInt32.Parse(text);
break;
case FieldType.UInt64:
case FieldType.Fixed64:
value = UInt64.Parse(text);
break;
case FieldType.Float:
value = float.Parse(text);
break;
case FieldType.Double:
value = Double.Parse(text);
break;
case FieldType.Bool:
value = Boolean.Parse(text);
break;
case FieldType.String:
value = text;
break;
case FieldType.Enum:
{
EnumDescriptor enumType = field.EnumType;
int number;
if (int.TryParse(text, out number))
{
value = enumType.FindValueByNumber(number);
if (value == null)
{
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value with number " + number + ".");
return false;
}
}
else
{
value = enumType.FindValueByName(text);
if (value == null)
{
tmpReasons.Add(
"Enum type \"" + enumType.FullName +
"\" has no value named \"" + text + "\".");
return false;
}
}
break;
}
case FieldType.Bytes:
case FieldType.Message:
case FieldType.Group:
tmpReasons.Add("Unhandled field type " + field.FieldType.ToString() + ".");
return false;
}
return true;
}
}
}

@ -0,0 +1,45 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Helpers to resolve class names etc.
/// </summary>
internal static class Helpers
{
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save