Commit b08b6bf6 authored by Jon Skeet's avatar Jon Skeet

Merge pull request #544 from jskeet/csharp-cleanup

Clean up C# code
parents 6b01539d fb77cc9d
...@@ -4,7 +4,6 @@ package benchmarks; ...@@ -4,7 +4,6 @@ package benchmarks;
option java_outer_classname = "GoogleSize"; option java_outer_classname = "GoogleSize";
option optimize_for = CODE_SIZE; option optimize_for = CODE_SIZE;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message SizeMessage1 { message SizeMessage1 {
required string field1 = 1; required string field1 = 1;
......
...@@ -4,7 +4,6 @@ package benchmarks; ...@@ -4,7 +4,6 @@ package benchmarks;
option java_outer_classname = "GoogleSpeed"; option java_outer_classname = "GoogleSpeed";
option optimize_for = SPEED; option optimize_for = SPEED;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message SpeedMessage1 { message SpeedMessage1 {
required string field1 = 1; required string field1 = 1;
......
@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
<?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>
\ No newline at end of file
<?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>
<?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>
@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
@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%"
<?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>
#!/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())
<?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>
<?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>
<?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>
...@@ -11,13 +11,8 @@ SRC=$(dirname $0)/src ...@@ -11,13 +11,8 @@ SRC=$(dirname $0)/src
set -ex set -ex
# echo Building the solution. echo Building the solution.
# TODO(jonskeet): Re-enable building the whole solution when we have ProtoBench et al xbuild /p:Configuration=$CONFIG $SRC/ProtocolBuffers.sln
# working again.
# xbuild /p:Configuration=$CONFIG $SRC/ProtocolBuffers.sln
xbuild /p:Configuration=$CONFIG $SRC/ProtocolBuffers/ProtocolBuffers.csproj
xbuild /p:Configuration=$CONFIG $SRC/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj
echo Running tests. echo Running tests.
$NUNIT_CONSOLE $SRC/ProtocolBuffers.Test/bin/$CONFIG/Google.Protobuf.Test.dll $NUNIT_CONSOLE $SRC/ProtocolBuffers.Test/bin/$CONFIG/Google.Protobuf.Test.dll
syntax = "proto2";
package protobuf_unittest_extra;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
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 {
// Note: changed from required to optional, as required fields are not
// permitted in extensions. (The fact that this was allowed in protogen
// before was almost certainly a bug.)
optional 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;
}
syntax = "proto2";
package protobuf_unittest_extra;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
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 {
// Note: changed from required to optional, as required fields are not
// permitted in extensions. (The fact that this was allowed in protogen
// before was almost certainly a bug.)
optional 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;
}
\ No newline at end of file
syntax = "proto2";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
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;
}
...@@ -36,9 +36,8 @@ ...@@ -36,9 +36,8 @@
using System; using System;
using System.IO; using System.IO;
using Google.Protobuf;
namespace Google.ProtocolBuffers.Examples.AddressBook namespace Google.Protobuf.Examples.AddressBook
{ {
internal class AddPerson internal class AddPerson
{ {
......
...@@ -8,11 +8,11 @@ ...@@ -8,11 +8,11 @@
<ProjectGuid>{A31F5FB2-4FF3-432A-B35B-5CD203606311}</ProjectGuid> <ProjectGuid>{A31F5FB2-4FF3-432A-B35B-5CD203606311}</ProjectGuid>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.Examples.AddressBook</RootNamespace> <RootNamespace>Google.Protobuf.Examples.AddressBook</RootNamespace>
<AssemblyName>AddressBook</AssemblyName> <AssemblyName>AddressBook</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<StartupObject>Google.ProtocolBuffers.Examples.AddressBook.Program</StartupObject> <StartupObject>Google.Protobuf.Examples.AddressBook.Program</StartupObject>
<TargetFrameworkProfile>Client</TargetFrameworkProfile> <TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
......
...@@ -7,18 +7,18 @@ using pb = global::Google.Protobuf; ...@@ -7,18 +7,18 @@ using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections; using pbc = global::Google.Protobuf.Collections;
using pbd = global::Google.Protobuf.Descriptors; using pbd = global::Google.Protobuf.Descriptors;
using scg = global::System.Collections.Generic; using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.Examples.AddressBook { namespace Google.Protobuf.Examples.AddressBook {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Addressbook { public static partial class Addressbook {
#region Static variables #region Static variables
internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor; internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person> internal__static_tutorial_Person__FieldAccessorTable; internal static pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.Person> internal__static_tutorial_Person__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor; internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; internal static pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor; internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook> internal__static_tutorial_AddressBook__FieldAccessorTable; internal static pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.AddressBook> internal__static_tutorial_AddressBook__FieldAccessorTable;
#endregion #endregion
#region Descriptor #region Descriptor
public static pbd::FileDescriptor Descriptor { public static pbd::FileDescriptor Descriptor {
...@@ -35,22 +35,22 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -35,22 +35,22 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
"TnVtYmVyEg4KBm51bWJlchgBIAIoCRIuCgR0eXBlGAIgASgOMhoudHV0b3Jp", "TnVtYmVyEg4KBm51bWJlchgBIAIoCRIuCgR0eXBlGAIgASgOMhoudHV0b3Jp",
"YWwuUGVyc29uLlBob25lVHlwZToESE9NRSIrCglQaG9uZVR5cGUSCgoGTU9C", "YWwuUGVyc29uLlBob25lVHlwZToESE9NRSIrCglQaG9uZVR5cGUSCgoGTU9C",
"SUxFEAASCAoESE9NRRABEggKBFdPUksQAiIvCgtBZGRyZXNzQm9vaxIgCgZw", "SUxFEAASCAoESE9NRRABEggKBFdPUksQAiIvCgtBZGRyZXNzQm9vaxIgCgZw",
"ZXJzb24YASADKAsyEC50dXRvcmlhbC5QZXJzb25CVwoUY29tLmV4YW1wbGUu", "ZXJzb24YASADKAsyEC50dXRvcmlhbC5QZXJzb25CUAoUY29tLmV4YW1wbGUu",
"dHV0b3JpYWxCEUFkZHJlc3NCb29rUHJvdG9zqgIrR29vZ2xlLlByb3RvY29s", "dHV0b3JpYWxCEUFkZHJlc3NCb29rUHJvdG9zqgIkR29vZ2xlLlByb3RvYnVm",
"QnVmZmVycy5FeGFtcGxlcy5BZGRyZXNzQm9vaw==")); "LkV4YW1wbGVzLkFkZHJlc3NCb29r"));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root; descriptor = root;
internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0]; internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0];
internal__static_tutorial_Person__FieldAccessorTable = internal__static_tutorial_Person__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person>(internal__static_tutorial_Person__Descriptor, new pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.Person>(internal__static_tutorial_Person__Descriptor,
new string[] { "Name", "Id", "Email", "Phone", }); new string[] { "Name", "Id", "Email", "Phone", });
internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0]; internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0];
internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable = internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber>(internal__static_tutorial_Person_PhoneNumber__Descriptor, new pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber>(internal__static_tutorial_Person_PhoneNumber__Descriptor,
new string[] { "Number", "Type", }); new string[] { "Number", "Type", });
internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1]; internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1];
internal__static_tutorial_AddressBook__FieldAccessorTable = internal__static_tutorial_AddressBook__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook>(internal__static_tutorial_AddressBook__Descriptor, new pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.Examples.AddressBook.AddressBook>(internal__static_tutorial_AddressBook__Descriptor,
new string[] { "Person", }); new string[] { "Person", });
}; };
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
...@@ -69,11 +69,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -69,11 +69,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
private static readonly string[] _fieldNames = new string[] { "email", "id", "name", "phone" }; private static readonly string[] _fieldNames = new string[] { "email", "id", "name", "phone" };
private static readonly uint[] _fieldTags = new uint[] { 26, 16, 10, 34 }; private static readonly uint[] _fieldTags = new uint[] { 26, 16, 10, 34 };
public static pbd::MessageDescriptor Descriptor { public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__Descriptor; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__Descriptor; }
} }
public pb::FieldAccess.FieldAccessorTable<Person> Fields { public pb::FieldAccess.FieldAccessorTable<Person> Fields {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__FieldAccessorTable; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__FieldAccessorTable; }
} }
private bool _frozen = false; private bool _frozen = false;
...@@ -131,8 +131,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -131,8 +131,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
} }
public const int PhoneFieldNumber = 4; public const int PhoneFieldNumber = 4;
private readonly pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> phone_ = new pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber>(); private readonly pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> phone_ = new pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber>();
public pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> Phone { public pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> Phone {
get { return phone_; } get { return phone_; }
} }
...@@ -193,7 +193,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -193,7 +193,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); size += 1 + pb::CodedOutputStream.ComputeStringSize(Email);
} }
if (phone_.Count > 0) { if (phone_.Count > 0) {
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in phone_) { foreach (global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber element in phone_) {
size += pb::CodedOutputStream.ComputeMessageSize(element); size += pb::CodedOutputStream.ComputeMessageSize(element);
} }
size += 1 * phone_.Count; size += 1 * phone_.Count;
...@@ -241,7 +241,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -241,7 +241,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
break; break;
} }
case 34: { case 34: {
input.ReadMessageArray(phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Parser); input.ReadMessageArray(phone_, global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser);
break; break;
} }
} }
...@@ -265,11 +265,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -265,11 +265,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
private static readonly string[] _fieldNames = new string[] { "number", "type" }; private static readonly string[] _fieldNames = new string[] { "number", "type" };
private static readonly uint[] _fieldTags = new uint[] { 10, 16 }; private static readonly uint[] _fieldTags = new uint[] { 10, 16 };
public static pbd::MessageDescriptor Descriptor { public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__Descriptor; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__Descriptor; }
} }
public pb::FieldAccess.FieldAccessorTable<PhoneNumber> Fields { public pb::FieldAccess.FieldAccessorTable<PhoneNumber> Fields {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; }
} }
private bool _frozen = false; private bool _frozen = false;
...@@ -304,8 +304,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -304,8 +304,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
} }
public const int TypeFieldNumber = 2; public const int TypeFieldNumber = 2;
private global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; private global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.HOME;
public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { public global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType Type {
get { return type_; } get { return type_; }
set { set {
pb::Freezable.CheckMutable(this); pb::Freezable.CheckMutable(this);
...@@ -332,7 +332,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -332,7 +332,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
public override int GetHashCode() { public override int GetHashCode() {
int hash = 1; int hash = 1;
if (Number.Length != 0) hash ^= Number.GetHashCode(); if (Number.Length != 0) hash ^= Number.GetHashCode();
if (Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) hash ^= Type.GetHashCode(); if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.HOME) hash ^= Type.GetHashCode();
return hash; return hash;
} }
...@@ -341,7 +341,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -341,7 +341,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
output.WriteRawTag(10); output.WriteRawTag(10);
output.WriteString(Number); output.WriteString(Number);
} }
if (Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) { if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.HOME) {
output.WriteRawTag(16); output.WriteRawTag(16);
output.WriteEnum((int) Type); output.WriteEnum((int) Type);
} }
...@@ -352,7 +352,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -352,7 +352,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
if (Number.Length != 0) { if (Number.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Number); size += 1 + pb::CodedOutputStream.ComputeStringSize(Number);
} }
if (Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) { if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.HOME) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
} }
return size; return size;
...@@ -365,7 +365,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -365,7 +365,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
if (other.Number.Length != 0) { if (other.Number.Length != 0) {
Number = other.Number; Number = other.Number;
} }
if (other.Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) { if (other.Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.HOME) {
Type = other.Type; Type = other.Type;
} }
} }
...@@ -386,7 +386,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -386,7 +386,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
break; break;
} }
case 16: { case 16: {
type_ = (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType) input.ReadEnum(); type_ = (global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) input.ReadEnum();
break; break;
} }
} }
...@@ -408,11 +408,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -408,11 +408,11 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
private static readonly string[] _fieldNames = new string[] { "person" }; private static readonly string[] _fieldNames = new string[] { "person" };
private static readonly uint[] _fieldTags = new uint[] { 10 }; private static readonly uint[] _fieldTags = new uint[] { 10 };
public static pbd::MessageDescriptor Descriptor { public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__Descriptor; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__Descriptor; }
} }
public pb::FieldAccess.FieldAccessorTable<AddressBook> Fields { public pb::FieldAccess.FieldAccessorTable<AddressBook> Fields {
get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__FieldAccessorTable; } get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__FieldAccessorTable; }
} }
private bool _frozen = false; private bool _frozen = false;
...@@ -437,8 +437,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -437,8 +437,8 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
} }
public const int PersonFieldNumber = 1; public const int PersonFieldNumber = 1;
private readonly pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person> person_ = new pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person>(); private readonly pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person> person_ = new pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person>();
public pbc::RepeatedField<global::Google.ProtocolBuffers.Examples.AddressBook.Person> Person { public pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person> Person {
get { return person_; } get { return person_; }
} }
...@@ -472,7 +472,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -472,7 +472,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
public int CalculateSize() { public int CalculateSize() {
int size = 0; int size = 0;
if (person_.Count > 0) { if (person_.Count > 0) {
foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in person_) { foreach (global::Google.Protobuf.Examples.AddressBook.Person element in person_) {
size += pb::CodedOutputStream.ComputeMessageSize(element); size += pb::CodedOutputStream.ComputeMessageSize(element);
} }
size += 1 * person_.Count; size += 1 * person_.Count;
...@@ -499,7 +499,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { ...@@ -499,7 +499,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook {
} }
break; break;
case 10: { case 10: {
input.ReadMessageArray(person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Parser); input.ReadMessageArray(person_, global::Google.Protobuf.Examples.AddressBook.Person.Parser);
break; break;
} }
} }
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
using System; using System;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook namespace Google.Protobuf.Examples.AddressBook
{ {
internal class ListPeople internal class ListPeople
{ {
......
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
using System; using System;
namespace Google.ProtocolBuffers.Examples.AddressBook namespace Google.Protobuf.Examples.AddressBook
{ {
/// <summary> /// <summary>
/// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour /// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour
......
using Google.Protobuf; using System;
using System;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers.Examples.AddressBook namespace Google.Protobuf.Examples.AddressBook
{ {
internal class SampleUsage internal class SampleUsage
{ {
......
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
#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);
}
}
}
\ No newline at end of file
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("")]
// 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")]
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C7A4A435-2813-41C8-AA87-BD914BA5223D}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoBench</RootNamespace>
<AssemblyName>ProtoBench</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<IntermediateOutputPath>obj\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<IntermediateOutputPath>obj\Release\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<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.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="GoogleSize.cs" />
<Compile Include="GoogleSpeed.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Unittest.cs" />
<Compile Include="UnittestImport.cs" />
<Compile Include="UnittestImportPublic.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="app.config" />
<None Include="google_message1.dat">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="google_message2.dat">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="TestProtos\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import.proto
#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 UnittestImport {
#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 UnittestImport() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0LnByb3RvEhhwcm90",
"b2J1Zl91bml0dGVzdF9pbXBvcnQaLGdvb2dsZS9wcm90b2J1Zi91bml0dGVz",
"dF9pbXBvcnRfcHVibGljLnByb3RvIhoKDUltcG9ydE1lc3NhZ2USCQoBZBgB",
"IAEoBSo8CgpJbXBvcnRFbnVtEg4KCklNUE9SVF9GT08QBxIOCgpJTVBPUlRf",
"QkFSEAgSDgoKSU1QT1JUX0JBWhAJQkMKGGNvbS5nb29nbGUucHJvdG9idWYu",
"dGVzdEgB+AEBqgIhR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9z",
"UAA="));
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.TestProtos.UnittestImportPublic.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.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.UnittestImport.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessage, ImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImport.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.UnittestImport.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import_public.proto
#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 UnittestImportPublic {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.PublicImportMessage, global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.Builder> internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestImportPublic() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cixnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3B1YmxpYy5wcm90",
"bxIYcHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0IiAKE1B1YmxpY0ltcG9ydE1l",
"c3NhZ2USCQoBZRgBIAEoBUI+Chhjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3Sq",
"AiFHb29nbGUuUHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90b3M="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.PublicImportMessage, global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.Builder>(internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor,
new string[] { "E", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PublicImportMessage : pb::GeneratedMessage<PublicImportMessage, PublicImportMessage.Builder> {
private PublicImportMessage() { }
private static readonly PublicImportMessage defaultInstance = new PublicImportMessage().MakeReadOnly();
private static readonly string[] _publicImportMessageFieldNames = new string[] { "e" };
private static readonly uint[] _publicImportMessageFieldTags = new uint[] { 8 };
public static PublicImportMessage DefaultInstance {
get { return defaultInstance; }
}
public override PublicImportMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override PublicImportMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PublicImportMessage, PublicImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable; }
}
public const int EFieldNumber = 1;
private bool hasE;
private int e_;
public bool HasE {
get { return hasE; }
}
public int E {
get { return e_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _publicImportMessageFieldNames;
if (hasE) {
output.WriteInt32(1, field_names[0], E);
}
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 (hasE) {
size += pb::CodedOutputStream.ComputeInt32Size(1, E);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static PublicImportMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PublicImportMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PublicImportMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PublicImportMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private PublicImportMessage 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(PublicImportMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<PublicImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(PublicImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private PublicImportMessage result;
private PublicImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
PublicImportMessage original = result;
result = new PublicImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override PublicImportMessage 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.PublicImportMessage.Descriptor; }
}
public override PublicImportMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.DefaultInstance; }
}
public override PublicImportMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PublicImportMessage) {
return MergeFrom((PublicImportMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PublicImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasE) {
E = other.E;
}
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(_publicImportMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _publicImportMessageFieldTags[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.hasE = input.ReadInt32(ref result.e_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasE {
get { return result.hasE; }
}
public int E {
get { return result.E; }
set { SetE(value); }
}
public Builder SetE(int value) {
PrepareBuilder();
result.hasE = true;
result.e_ = value;
return this;
}
public Builder ClearE() {
PrepareBuilder();
result.hasE = false;
result.e_ = 0;
return this;
}
}
static PublicImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
using System; using System;
using System.IO; using System.IO;
namespace Google.ProtocolBuffers.ProtoDump namespace Google.Protobuf.ProtoDump
{ {
/// <summary> /// <summary>
/// Small utility to load a binary message and dump it in text form /// Small utility to load a binary message and dump it in text form
...@@ -53,36 +53,24 @@ namespace Google.ProtocolBuffers.ProtoDump ...@@ -53,36 +53,24 @@ namespace Google.ProtocolBuffers.ProtoDump
Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project"); Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project");
return 1; return 1;
} }
IMessage defaultMessage; Type type = Type.GetType(args[0]);
try if (type == null)
{ {
defaultMessage = MessageUtil.GetDefaultMessage(args[0]); Console.Error.WriteLine("Unable to load type {0}.", args[0]);
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
return 1; return 1;
} }
try if (!typeof(IMessage).IsAssignableFrom(type))
{ {
IBuilder builder = defaultMessage.WeakCreateBuilderForType(); Console.Error.WriteLine("Type {0} doesn't implement IMessage.", args[0]);
if (builder == null) return 1;
{
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) IMessage message = (IMessage) Activator.CreateInstance(type);
using (var input = File.OpenRead(args[1]))
{ {
Console.Error.WriteLine("Error: {0}", e.Message); message.MergeFrom(input);
Console.Error.WriteLine();
Console.Error.WriteLine("Detailed exception information: {0}", e);
return 1;
} }
Console.WriteLine(message);
return 0;
} }
} }
} }
\ No newline at end of file
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
<ProjectGuid>{D7282E99-2DC3-405B-946F-177DB2FD2AE2}</ProjectGuid> <ProjectGuid>{D7282E99-2DC3-405B-946F-177DB2FD2AE2}</ProjectGuid>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoDump</RootNamespace> <RootNamespace>Google.Protobuf.ProtoDump</RootNamespace>
<AssemblyName>ProtoDump</AssemblyName> <AssemblyName>ProtoDump</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
......
#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;
using System.Collections.Generic;
using System.IO;
using Google.Protobuf;
using Google.Protobuf.Descriptors;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoMunge
{
/// <summary>
/// Utility console application which takes a message descriptor and a corresponding message,
/// and produces a new message with similar but random data. The data is the same length
/// as the original, but with random values within appropriate bands. (For instance, a compressed
/// integer in the range 0-127 will end up as another integer in the same range, to keep the length
/// the same.)
/// TODO(jonskeet): Potentially refactor to use an instance instead, making it simpler to
/// be thread-safe for external use.
/// </summary>
public sealed class Program
{
private static readonly Random rng = new Random();
private static int Main(string[] args)
{
if (args.Length != 3)
{
Console.Error.WriteLine("Usage: ProtoMunge <descriptor type name> <input data> <output file>");
Console.Error.WriteLine(
"The descriptor type name is the fully-qualified message name, including assembly.");
Console.Error.WriteLine(
"(At a future date it may be possible to do this without building the .NET assembly at all.)");
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();
byte[] inputData = File.ReadAllBytes(args[1]);
builder.WeakMergeFrom(ByteString.CopyFrom(inputData));
IMessage original = builder.WeakBuild();
IMessage munged = Munge(original);
if (original.SerializedSize != munged.SerializedSize)
{
throw new Exception("Serialized sizes don't match");
}
File.WriteAllBytes(args[2], munged.ToByteArray());
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;
}
}
/// <summary>
/// Munges a message recursively.
/// </summary>
/// <returns>A new message of the same type as the original message,
/// but munged so that all the data is desensitised.</returns>
private static IMessage Munge(IMessage message)
{
IBuilder builder = message.WeakCreateBuilderForType();
foreach (var pair in message.AllFields)
{
if (pair.Key.IsRepeated)
{
foreach (object singleValue in (IEnumerable) pair.Value)
{
builder.WeakAddRepeatedField(pair.Key, CheckedMungeValue(pair.Key, singleValue));
}
}
else
{
builder[pair.Key] = CheckedMungeValue(pair.Key, pair.Value);
}
}
IMessage munged = builder.WeakBuild();
if (message.SerializedSize != munged.SerializedSize)
{
Console.WriteLine("Sub message sizes: {0}/{1}", message.SerializedSize, munged.SerializedSize);
}
return munged;
}
/// <summary>
/// Munges a single value and checks that the length ends up the same as it was before.
/// </summary>
private static object CheckedMungeValue(FieldDescriptor fieldDescriptor, object value)
{
int currentSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber,
value);
object mungedValue = MungeValue(fieldDescriptor, value);
int mungedSize = CodedOutputStream.ComputeFieldSize(fieldDescriptor.FieldType, fieldDescriptor.FieldNumber,
mungedValue);
// Exceptions log more easily than assertions
if (currentSize != mungedSize)
{
throw new Exception("Munged value had wrong size. Field type: " + fieldDescriptor.FieldType
+ "; old value: " + value + "; new value: " + mungedValue);
}
return mungedValue;
}
/// <summary>
/// Munges a single value of the specified field descriptor. (i.e. if the field is
/// actually a repeated int, this method receives a single int value to munge, and
/// is called multiple times).
/// </summary>
private static object MungeValue(FieldDescriptor fieldDescriptor, object value)
{
switch (fieldDescriptor.FieldType)
{
case FieldType.SInt64:
case FieldType.Int64:
return (long) MungeVarint64((ulong) (long) value);
case FieldType.UInt64:
return MungeVarint64((ulong) value);
case FieldType.SInt32:
return (int) MungeVarint32((uint) (int) value);
case FieldType.Int32:
return MungeInt32((int) value);
case FieldType.UInt32:
return MungeVarint32((uint) value);
case FieldType.Double:
return rng.NextDouble();
case FieldType.Float:
return (float) rng.NextDouble();
case FieldType.Fixed64:
{
byte[] data = new byte[8];
rng.NextBytes(data);
return BitConverter.ToUInt64(data, 0);
}
case FieldType.Fixed32:
{
byte[] data = new byte[4];
rng.NextBytes(data);
return BitConverter.ToUInt32(data, 0);
}
case FieldType.Bool:
return rng.Next(2) == 1;
case FieldType.String:
return MungeString((string) value);
case FieldType.Group:
case FieldType.Message:
return Munge((IMessage) value);
case FieldType.Bytes:
return MungeByteString((ByteString) value);
case FieldType.SFixed64:
{
byte[] data = new byte[8];
rng.NextBytes(data);
return BitConverter.ToInt64(data, 0);
}
case FieldType.SFixed32:
{
byte[] data = new byte[4];
rng.NextBytes(data);
return BitConverter.ToInt32(data, 0);
}
case FieldType.Enum:
return MungeEnum(fieldDescriptor, (EnumValueDescriptor) value);
default:
// TODO(jonskeet): Different exception?
throw new ArgumentException("Invalid field descriptor");
}
}
private static object MungeString(string original)
{
foreach (char c in original)
{
if (c > 127)
{
throw new ArgumentException("Can't handle non-ascii yet");
}
}
char[] chars = new char[original.Length];
// Convert to pure ASCII - no control characters.
for (int i = 0; i < chars.Length; i++)
{
chars[i] = (char) rng.Next(32, 127);
}
return new string(chars);
}
/// <summary>
/// Int32 fields are slightly strange - we need to keep the sign the same way it is:
/// negative numbers can munge to any other negative number (it'll always take
/// 10 bytes) but positive numbers have to stay positive, so we can't use the
/// full range of 32 bits.
/// </summary>
private static int MungeInt32(int value)
{
if (value < 0)
{
return rng.Next(int.MinValue, 0);
}
int length = CodedOutputStream.ComputeRawVarint32Size((uint) value);
uint min = length == 1 ? 0 : 1U << ((length - 1)*7);
uint max = length == 5 ? int.MaxValue : (1U << (length*7)) - 1;
return (int) NextRandomUInt64(min, max);
}
private static uint MungeVarint32(uint original)
{
int length = CodedOutputStream.ComputeRawVarint32Size(original);
uint min = length == 1 ? 0 : 1U << ((length - 1)*7);
uint max = length == 5 ? uint.MaxValue : (1U << (length*7)) - 1;
return (uint) NextRandomUInt64(min, max);
}
private static ulong MungeVarint64(ulong original)
{
int length = CodedOutputStream.ComputeRawVarint64Size(original);
ulong min = length == 1 ? 0 : 1UL << ((length - 1)*7);
ulong max = length == 10 ? ulong.MaxValue : (1UL << (length*7)) - 1;
return NextRandomUInt64(min, max);
}
/// <summary>
/// Returns a random number in the range [min, max] (both inclusive).
/// </summary>
private static ulong NextRandomUInt64(ulong min, ulong max)
{
if (min > max)
{
throw new ArgumentException("min must be <= max; min=" + min + "; max = " + max);
}
ulong range = max - min;
// This isn't actually terribly good at very large ranges - but it doesn't really matter for the sake
// of this program.
return min + (ulong) (range*rng.NextDouble());
}
private static object MungeEnum(FieldDescriptor fieldDescriptor, EnumValueDescriptor original)
{
// Find all the values which get encoded to the same size as the current value, and pick one at random
int originalSize = CodedOutputStream.ComputeRawVarint32Size((uint) original.Number);
List<EnumValueDescriptor> sameSizeValues = new List<EnumValueDescriptor>();
foreach (EnumValueDescriptor candidate in fieldDescriptor.EnumType.Values)
{
if (CodedOutputStream.ComputeRawVarint32Size((uint) candidate.Number) == originalSize)
{
sameSizeValues.Add(candidate);
}
}
return sameSizeValues[rng.Next(sameSizeValues.Count)];
}
private static object MungeByteString(ByteString byteString)
{
byte[] data = new byte[byteString.Length];
rng.NextBytes(data);
return ByteString.CopyFrom(data);
}
}
}
\ No newline at end of file
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("ProtoMunge")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProtoMunge")]
[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")]
\ No newline at end of file
<?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>{8F09AF72-3327-4FA7-BC09-070B80221AB9}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers.ProtoMunge</RootNamespace>
<AssemblyName>ProtoMunge</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<IntermediateOutputPath>obj\Debug\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<IntermediateOutputPath>obj\Release\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<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>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ProtocolBuffers.SilverlightTest.App"
>
<Application.Resources>
</Application.Resources>
</Application>
using System;
using System.Windows;
using Microsoft.Silverlight.Testing;
namespace Google.ProtocolBuffers
{
public partial class App : Application
{
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
//InitializeComponent();
}
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = UnitTestSystem.CreateTestPage();
}
private void Application_Exit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// If the app is running outside of the debugger then report the exception using
// the browser's exception mechanism. On IE this will display it a yellow alert
// icon in the status bar and Firefox will display a script error.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(
new EventHandler<ApplicationUnhandledExceptionEventArgs>(ReportErrorToDOM),
new object[] { sender, e } );
}
}
private void ReportErrorToDOM(object sender, ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
}
}
\ No newline at end of file
...@@ -40,7 +40,6 @@ using NUnit.Framework; ...@@ -40,7 +40,6 @@ using NUnit.Framework;
namespace Google.Protobuf namespace Google.Protobuf
{ {
[TestFixture]
public class ByteStringTest public class ByteStringTest
{ {
[Test] [Test]
......
...@@ -147,17 +147,14 @@ namespace Google.Protobuf ...@@ -147,17 +147,14 @@ namespace Google.Protobuf
Assert.AreEqual(messageType, primitiveField.ContainingType); Assert.AreEqual(messageType, primitiveField.ContainingType);
Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File); Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File);
Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
Assert.AreEqual(MappedType.Int32, primitiveField.MappedType);
Assert.IsNull(primitiveField.Options); Assert.IsNull(primitiveField.Options);
Assert.AreEqual("single_nested_enum", enumField.Name); Assert.AreEqual("single_nested_enum", enumField.Name);
Assert.AreEqual(FieldType.Enum, enumField.FieldType); Assert.AreEqual(FieldType.Enum, enumField.FieldType);
Assert.AreEqual(MappedType.Enum, enumField.MappedType);
// Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType); // Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType);
Assert.AreEqual("single_foreign_message", messageField.Name); Assert.AreEqual("single_foreign_message", messageField.Name);
Assert.AreEqual(FieldType.Message, messageField.FieldType); Assert.AreEqual(FieldType.Message, messageField.FieldType);
Assert.AreEqual(MappedType.Message, messageField.MappedType);
Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType); Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType);
} }
...@@ -169,9 +166,7 @@ namespace Google.Protobuf ...@@ -169,9 +166,7 @@ namespace Google.Protobuf
FieldDescriptor repeatedField = FieldDescriptor repeatedField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32"); TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
Assert.IsFalse(singleField.IsRequired);
Assert.IsFalse(singleField.IsRepeated); Assert.IsFalse(singleField.IsRepeated);
Assert.IsFalse(repeatedField.IsRequired);
Assert.IsTrue(repeatedField.IsRepeated); Assert.IsTrue(repeatedField.IsRepeated);
} }
......
...@@ -89,7 +89,6 @@ ...@@ -89,7 +89,6 @@
<Compile Include="IssuesTest.cs" /> <Compile Include="IssuesTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestCornerCases.cs" /> <Compile Include="TestCornerCases.cs" />
<Compile Include="WireFormatTest.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj"> <ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
......
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Reflection;
using Google.Protobuf.Descriptors;
using NUnit.Framework;
namespace Google.Protobuf
{
public class WireFormatTest
{
/// <summary>
/// Keeps the attributes on FieldType and the switch statement in WireFormat in sync.
/// </summary>
[Test]
public void FieldTypeToWireTypeMapping()
{
foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
{
FieldType fieldType = (FieldType) field.GetValue(null);
FieldMappingAttribute mapping =
(FieldMappingAttribute) field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
Assert.AreEqual(mapping.WireType, WireFormat.GetWireType(fieldType));
}
}
}
}
\ No newline at end of file
...@@ -10,10 +10,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddressBook", "AddressBook\ ...@@ -10,10 +10,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddressBook", "AddressBook\
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoDump", "ProtoDump\ProtoDump.csproj", "{D7282E99-2DC3-405B-946F-177DB2FD2AE2}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoDump", "ProtoDump\ProtoDump.csproj", "{D7282E99-2DC3-405B-946F-177DB2FD2AE2}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoMunge", "ProtoMunge\ProtoMunge.csproj", "{8F09AF72-3327-4FA7-BC09-070B80221AB9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoBench", "ProtoBench\ProtoBench.csproj", "{C7A4A435-2813-41C8-AA87-BD914BA5223D}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -36,14 +32,6 @@ Global ...@@ -36,14 +32,6 @@ Global
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Debug|Any CPU.Build.0 = Debug|Any CPU {D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.ActiveCfg = Release|Any CPU {D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.Build.0 = Release|Any CPU {D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.Build.0 = Release|Any CPU
{8F09AF72-3327-4FA7-BC09-070B80221AB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F09AF72-3327-4FA7-BC09-070B80221AB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F09AF72-3327-4FA7-BC09-070B80221AB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F09AF72-3327-4FA7-BC09-070B80221AB9}.Release|Any CPU.Build.0 = Release|Any CPU
{C7A4A435-2813-41C8-AA87-BD914BA5223D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7A4A435-2813-41C8-AA87-BD914BA5223D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7A4A435-2813-41C8-AA87-BD914BA5223D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7A4A435-2813-41C8-AA87-BD914BA5223D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
......
...@@ -59,19 +59,11 @@ namespace Google.Protobuf ...@@ -59,19 +59,11 @@ namespace Google.Protobuf
} }
else else
{ {
ByteCopy(src, srcOffset, dst, dstOffset, count); int stop = srcOffset + count;
} for (int i = srcOffset; i < stop; i++)
} {
dst[dstOffset++] = src[i];
/// <summary> }
/// Copy the bytes provided with a for loop, faster when there are only a few bytes to copy
/// </summary>
internal static void ByteCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count)
{
int stop = srcOffset + count;
for (int i = srcOffset; i < stop; i++)
{
dst[dstOffset++] = src[i];
} }
} }
......
...@@ -264,38 +264,6 @@ namespace Google.Protobuf ...@@ -264,38 +264,6 @@ namespace Google.Protobuf
return true; return true;
} }
/// <summary>
/// Builder for ByteStrings which allows them to be created without extra
/// copying being involved. This has to be a nested type in order to have access
/// to the private ByteString constructor.
/// </summary>
internal sealed class CodedBuilder
{
private readonly CodedOutputStream output;
private readonly byte[] buffer;
internal CodedBuilder(int size)
{
buffer = new byte[size];
output = CodedOutputStream.CreateInstance(buffer);
}
internal ByteString Build()
{
output.CheckNoSpaceLeft();
// We can be confident that the CodedOutputStream will not modify the
// underlying bytes anymore because it already wrote all of them. So,
// no need to make a copy.
return new ByteString(buffer);
}
internal CodedOutputStream CodedOutput
{
get { return output; }
}
}
/// <summary> /// <summary>
/// Used internally by CodedOutputStream to avoid creating a copy for the write /// Used internally by CodedOutputStream to avoid creating a copy for the write
/// </summary> /// </summary>
......
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for dictionaries.
/// </summary>
public static class Dictionaries
{
/// <summary>
/// Compares two dictionaries for equality. Each value is compared with equality using Equals
/// for non-IEnumerable implementations, and using EnumerableEquals otherwise.
/// TODO(jonskeet): This is clearly pretty slow, and involves lots of boxing/unboxing...
/// </summary>
public static bool Equals<TKey, TValue>(IDictionary<TKey, TValue> left, IDictionary<TKey, TValue> right)
{
if (left.Count != right.Count)
{
return false;
}
foreach (KeyValuePair<TKey, TValue> leftEntry in left)
{
TValue rightValue;
if (!right.TryGetValue(leftEntry.Key, out rightValue))
{
return false;
}
IEnumerable leftEnumerable = leftEntry.Value as IEnumerable;
IEnumerable rightEnumerable = rightValue as IEnumerable;
if (leftEnumerable == null || rightEnumerable == null)
{
if (!Equals(leftEntry.Value, rightValue))
{
return false;
}
}
else
{
if (!Enumerables.Equals(leftEnumerable, rightEnumerable))
{
return false;
}
}
}
return true;
}
public static IDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
return dictionary.IsReadOnly ? dictionary : new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
/// <summary>
/// Creates a hashcode for a dictionary by XORing the hashcodes of all the fields
/// and values. (By XORing, we avoid ordering issues.)
/// TODO(jonskeet): Currently XORs other stuff too, and assumes non-null values.
/// </summary>
public static int GetHashCode<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
int ret = 31;
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
{
int hash = entry.Key.GetHashCode() ^ GetDeepHashCode(entry.Value);
ret ^= hash;
}
return ret;
}
/// <summary>
/// Determines the hash of a value by either taking it directly or hashing all the elements
/// for IEnumerable implementations.
/// </summary>
private static int GetDeepHashCode(object value)
{
IEnumerable iterable = value as IEnumerable;
if (iterable == null)
{
return value.GetHashCode();
}
int hash = 29;
foreach (object element in iterable)
{
hash = hash*37 + element.GetHashCode();
}
return hash;
}
}
}
\ No newline at end of file
// 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.
using System;
using System.Collections;
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for IEnumerable (and potentially the generic version in the future).
/// </summary>
public static class Enumerables
{
public static bool Equals(IEnumerable left, IEnumerable right)
{
IEnumerator leftEnumerator = left.GetEnumerator();
try
{
foreach (object rightObject in right)
{
if (!leftEnumerator.MoveNext())
{
return false;
}
if (!Equals(leftEnumerator.Current, rightObject))
{
return false;
}
}
if (leftEnumerator.MoveNext())
{
return false;
}
}
finally
{
IDisposable leftEnumeratorDisposable = leftEnumerator as IDisposable;
if (leftEnumeratorDisposable != null)
{
leftEnumeratorDisposable.Dispose();
}
}
return true;
}
}
}
\ No newline at end of file
// 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.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility non-generic class for calling into Lists{T} using type inference.
/// </summary>
public static class Lists
{
/// <summary>
/// Returns a read-only view of the specified list.
/// </summary>
public static IList<T> AsReadOnly<T>(IList<T> list)
{
return Lists<T>.AsReadOnly(list);
}
public static bool Equals<T>(IList<T> left, IList<T> right)
{
if (left == right)
{
return true;
}
if (left == null || right == null)
{
return false;
}
if (left.Count != right.Count)
{
return false;
}
IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < left.Count; i++)
{
if (!comparer.Equals(left[i], right[i]))
{
return false;
}
}
return true;
}
public static int GetHashCode<T>(IList<T> list)
{
int hash = 31;
foreach (T element in list)
{
hash = hash*29 + element.GetHashCode();
}
return hash;
}
}
/// <summary>
/// Utility class for dealing with lists.
/// </summary>
public static class Lists<T>
{
private static readonly ReadOnlyCollection<T> empty = new ReadOnlyCollection<T>(new T[0]);
/// <summary>
/// Returns an immutable empty list.
/// </summary>
public static ReadOnlyCollection<T> Empty
{
get { return empty; }
}
/// <summary>
/// Returns either the original reference if it's already read-only,
/// or a new ReadOnlyCollection wrapping the original list.
/// </summary>
public static IList<T> AsReadOnly(IList<T> list)
{
return list.IsReadOnly ? list : new ReadOnlyCollection<T>(list);
}
}
}
\ No newline at end of file
...@@ -298,6 +298,16 @@ namespace Google.Protobuf.Collections ...@@ -298,6 +298,16 @@ namespace Google.Protobuf.Collections
} }
} }
internal uint CalculateSize(Func<T, int> sizeComputer)
{
int size = 0;
for (int i = 0; i < count; i++)
{
size += sizeComputer(array[i]);
}
return (uint)size;
}
public struct Enumerator : IEnumerator<T> public struct Enumerator : IEnumerator<T>
{ {
private int index; private int index;
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Google.Protobuf.Collections
{
public static class RepeatedFieldExtensions
{
internal static uint CalculateSize<T>(this RepeatedField<T> list, Func<T, int> sizeComputer)
{
int size = 0;
foreach (var item in list)
{
size += sizeComputer(item);
}
return (uint)size;
}
/*
/// <summary>
/// Calculates the serialized data size, including one tag per value.
/// </summary>
public static int CalculateTotalSize<T>(this RepeatedField<T> list, int tagSize, Func<T, int> sizeComputer)
{
if (list.Count == 0)
{
return 0;
}
return (int)(dataSize + tagSize * list.Count);
}
/// <summary>
/// Calculates the serialized data size, as a packed array (tag, length, data).
/// </summary>
public static int CalculateTotalPackedSize(int tagSize)
{
if (Count == 0)
{
return 0;
}
uint dataSize = CalculateSize();
return tagSize + CodedOutputStream.ComputeRawVarint32Size(dataSize) + (int)dataSize;
}
*/
}
}
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic; using System.Collections.Generic;
using Google.Protobuf.Collections; using System.Collections.ObjectModel;
namespace Google.Protobuf.Descriptors namespace Google.Protobuf.Descriptors
{ {
...@@ -58,7 +58,7 @@ namespace Google.Protobuf.Descriptors ...@@ -58,7 +58,7 @@ namespace Google.Protobuf.Descriptors
{ {
array[i] = converter(input[i], i); array[i] = converter(input[i], i);
} }
return Lists<TOutput>.AsReadOnly(array); return new ReadOnlyCollection<TOutput>(array);
} }
} }
} }
\ No newline at end of file
...@@ -43,24 +43,21 @@ namespace Google.Protobuf.Descriptors ...@@ -43,24 +43,21 @@ namespace Google.Protobuf.Descriptors
public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>, public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>,
IComparable<FieldDescriptor> IComparable<FieldDescriptor>
{ {
private readonly MessageDescriptor extensionScope;
private EnumDescriptor enumType; private EnumDescriptor enumType;
private MessageDescriptor messageType; private MessageDescriptor messageType;
private MessageDescriptor containingType; private MessageDescriptor containingType;
private OneofDescriptor containingOneof; private OneofDescriptor containingOneof;
private FieldType fieldType; private FieldType fieldType;
private MappedType mappedType;
private readonly object optionsLock = new object(); private readonly object optionsLock = new object();
internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file, internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file,
MessageDescriptor parent, int index, bool isExtension) MessageDescriptor parent, int index)
: base(proto, file, ComputeFullName(file, parent, proto.Name), index) : base(proto, file, ComputeFullName(file, parent, proto.Name), index)
{ {
if (proto.Type != 0) if (proto.Type != 0)
{ {
fieldType = GetFieldTypeFromProtoType(proto.Type); fieldType = GetFieldTypeFromProtoType(proto.Type);
mappedType = FieldTypeToMappedTypeMap[fieldType];
} }
if (FieldNumber <= 0) if (FieldNumber <= 0)
...@@ -68,38 +65,16 @@ namespace Google.Protobuf.Descriptors ...@@ -68,38 +65,16 @@ namespace Google.Protobuf.Descriptors
throw new DescriptorValidationException(this, throw new DescriptorValidationException(this,
"Field numbers must be positive integers."); "Field numbers must be positive integers.");
} }
containingType = parent;
if (isExtension) if (proto.OneofIndex != 0)
{ {
if (proto.Extendee != "") if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count)
{ {
throw new DescriptorValidationException(this, throw new DescriptorValidationException(this,
"FieldDescriptorProto.Extendee not set for extension field."); "FieldDescriptorProto.oneof_index is out of range for type " + parent.Name);
}
containingType = null; // Will be filled in when cross-linking
if (parent != null)
{
extensionScope = parent;
}
else
{
extensionScope = null;
} }
} containingOneof = parent.Oneofs[proto.OneofIndex];
else containingOneof.fieldCount ++;
{
containingType = parent;
if (proto.OneofIndex != 0)
{
if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count)
{
throw new DescriptorValidationException(this,
"FieldDescriptorProto.oneof_index is out of range for type " + parent.Name);
}
containingOneof = parent.Oneofs[proto.OneofIndex];
containingOneof.fieldCount ++;
}
extensionScope = null;
} }
file.DescriptorPool.AddSymbol(this); file.DescriptorPool.AddSymbol(this);
...@@ -151,51 +126,7 @@ namespace Google.Protobuf.Descriptors ...@@ -151,51 +126,7 @@ namespace Google.Protobuf.Descriptors
default: default:
throw new ArgumentException("Invalid type specified"); throw new ArgumentException("Invalid type specified");
} }
} }
/// <summary>
/// Returns the default value for a mapped type.
/// </summary>
private static object GetDefaultValueForMappedType(MappedType type)
{
switch (type)
{
case MappedType.Int32:
return 0;
case MappedType.Int64:
return (long) 0;
case MappedType.UInt32:
return (uint) 0;
case MappedType.UInt64:
return (ulong) 0;
case MappedType.Single:
return (float) 0;
case MappedType.Double:
return (double) 0;
case MappedType.Boolean:
return false;
case MappedType.String:
return "";
case MappedType.ByteString:
return ByteString.Empty;
case MappedType.Message:
return null;
case MappedType.Enum:
return null;
default:
throw new ArgumentException("Invalid type specified");
}
}
public bool IsRequired
{
get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REQUIRED; }
}
public bool IsOptional
{
get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_OPTIONAL; }
}
public bool IsRepeated public bool IsRepeated
{ {
...@@ -205,16 +136,7 @@ namespace Google.Protobuf.Descriptors ...@@ -205,16 +136,7 @@ namespace Google.Protobuf.Descriptors
public bool IsPacked public bool IsPacked
{ {
get { return Proto.Options.Packed; } get { return Proto.Options.Packed; }
} }
/// <value>
/// Indicates whether or not this field is an extension. (Only relevant when parsing
/// the proto2 descriptor...)
/// </value>
internal bool IsExtension
{
get { return Proto.Extendee != ""; }
}
/// <summary> /// <summary>
/// Get the field's containing type. For extensions, this is the type being /// Get the field's containing type. For extensions, this is the type being
...@@ -229,46 +151,7 @@ namespace Google.Protobuf.Descriptors ...@@ -229,46 +151,7 @@ namespace Google.Protobuf.Descriptors
public OneofDescriptor ContainingOneof public OneofDescriptor ContainingOneof
{ {
get { return containingOneof; } get { return containingOneof; }
} }
/// <summary>
/// For extensions defined nested within message types, gets
/// the outer type. Not valid for non-extension fields.
/// </summary>
/// <example>
/// <code>
/// message Foo {
/// extensions 1000 to max;
/// }
/// extend Foo {
/// optional int32 baz = 1234;
/// }
/// message Bar {
/// extend Foo {
/// optional int32 qux = 4321;
/// }
/// }
/// </code>
/// The containing type for both <c>baz</c> and <c>qux</c> is <c>Foo</c>.
/// However, the extension scope for <c>baz</c> is <c>null</c> while
/// the extension scope for <c>qux</c> is <c>Bar</c>.
/// </example>
public MessageDescriptor ExtensionScope
{
get
{
if (!IsExtension)
{
throw new InvalidOperationException("This field is not an extension.");
}
return extensionScope;
}
}
public MappedType MappedType
{
get { return mappedType; }
}
public FieldType FieldType public FieldType FieldType
{ {
...@@ -303,7 +186,7 @@ namespace Google.Protobuf.Descriptors ...@@ -303,7 +186,7 @@ namespace Google.Protobuf.Descriptors
{ {
get get
{ {
if (MappedType != MappedType.Enum) if (fieldType != FieldType.Enum)
{ {
throw new InvalidOperationException("EnumType is only valid for enum fields."); throw new InvalidOperationException("EnumType is only valid for enum fields.");
} }
...@@ -318,7 +201,7 @@ namespace Google.Protobuf.Descriptors ...@@ -318,7 +201,7 @@ namespace Google.Protobuf.Descriptors
{ {
get get
{ {
if (MappedType != MappedType.Message) if (fieldType != FieldType.Message)
{ {
throw new InvalidOperationException("MessageType is only valid for enum fields."); throw new InvalidOperationException("MessageType is only valid for enum fields.");
} }
...@@ -326,25 +209,6 @@ namespace Google.Protobuf.Descriptors ...@@ -326,25 +209,6 @@ namespace Google.Protobuf.Descriptors
} }
} }
/// <summary>
/// Immutable mapping from field type to mapped type. Built using the attributes on
/// FieldType values.
/// </summary>
public static readonly IDictionary<FieldType, MappedType> FieldTypeToMappedTypeMap = MapFieldTypes();
private static IDictionary<FieldType, MappedType> MapFieldTypes()
{
var map = new Dictionary<FieldType, MappedType>();
foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
{
FieldType fieldType = (FieldType) field.GetValue(null);
FieldMappingAttribute mapping =
(FieldMappingAttribute) field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
map[fieldType] = mapping.MappedType;
}
return Dictionaries.AsReadOnly(map);
}
/// <summary> /// <summary>
/// Look up and cross-link all field types etc. /// Look up and cross-link all field types etc.
/// </summary> /// </summary>
...@@ -361,12 +225,10 @@ namespace Google.Protobuf.Descriptors ...@@ -361,12 +225,10 @@ namespace Google.Protobuf.Descriptors
if (typeDescriptor is MessageDescriptor) if (typeDescriptor is MessageDescriptor)
{ {
fieldType = FieldType.Message; fieldType = FieldType.Message;
mappedType = MappedType.Message;
} }
else if (typeDescriptor is EnumDescriptor) else if (typeDescriptor is EnumDescriptor)
{ {
fieldType = FieldType.Enum; fieldType = FieldType.Enum;
mappedType = MappedType.Enum;
} }
else else
{ {
...@@ -374,7 +236,7 @@ namespace Google.Protobuf.Descriptors ...@@ -374,7 +236,7 @@ namespace Google.Protobuf.Descriptors
} }
} }
if (MappedType == MappedType.Message) if (fieldType == FieldType.Message)
{ {
if (!(typeDescriptor is MessageDescriptor)) if (!(typeDescriptor is MessageDescriptor))
{ {
...@@ -388,7 +250,7 @@ namespace Google.Protobuf.Descriptors ...@@ -388,7 +250,7 @@ namespace Google.Protobuf.Descriptors
throw new DescriptorValidationException(this, "Messages can't have default values."); throw new DescriptorValidationException(this, "Messages can't have default values.");
} }
} }
else if (MappedType == Descriptors.MappedType.Enum) else if (fieldType == FieldType.Enum)
{ {
if (!(typeDescriptor is EnumDescriptor)) if (!(typeDescriptor is EnumDescriptor))
{ {
...@@ -403,7 +265,7 @@ namespace Google.Protobuf.Descriptors ...@@ -403,7 +265,7 @@ namespace Google.Protobuf.Descriptors
} }
else else
{ {
if (MappedType == MappedType.Message || MappedType == MappedType.Enum) if (fieldType == FieldType.Message || fieldType == FieldType.Enum)
{ {
throw new DescriptorValidationException(this, "Field with message or enum type missing type_name."); throw new DescriptorValidationException(this, "Field with message or enum type missing type_name.");
} }
...@@ -411,25 +273,11 @@ namespace Google.Protobuf.Descriptors ...@@ -411,25 +273,11 @@ namespace Google.Protobuf.Descriptors
// Note: no attempt to perform any default value parsing // Note: no attempt to perform any default value parsing
if (!IsExtension) File.DescriptorPool.AddFieldByNumber(this);
{
File.DescriptorPool.AddFieldByNumber(this);
}
if (containingType != null && containingType.Options != null && containingType.Options.MessageSetWireFormat) if (containingType != null && containingType.Options != null && containingType.Options.MessageSetWireFormat)
{ {
if (IsExtension) throw new DescriptorValidationException(this, "MessageSet format is not supported.");
{
if (!IsOptional || FieldType != FieldType.Message)
{
throw new DescriptorValidationException(this,
"Extensions of MessageSets must be optional messages.");
}
}
else
{
throw new DescriptorValidationException(this, "MessageSets cannot have fields, only extensions.");
}
} }
} }
} }
......
// 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.
using System;
using System.Collections.Generic;
using System.Reflection;
using Google.Protobuf.Collections;
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Defined specifically for the <see cref="FieldType" /> enumeration,
/// this allows each field type to specify the mapped type and wire type.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldMappingAttribute : Attribute
{
public FieldMappingAttribute(MappedType mappedType, WireFormat.WireType wireType)
{
MappedType = mappedType;
WireType = wireType;
}
public MappedType MappedType { get; private set; }
public WireFormat.WireType WireType { get; private set; }
/// <summary>
/// Immutable mapping from field type to mapped type. Built using the attributes on
/// FieldType values.
/// </summary>
private static readonly IDictionary<FieldType, FieldMappingAttribute> FieldTypeToMappedTypeMap = MapFieldTypes();
private static IDictionary<FieldType, FieldMappingAttribute> MapFieldTypes()
{
var map = new Dictionary<FieldType, FieldMappingAttribute>();
foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public))
{
FieldType fieldType = (FieldType) field.GetValue(null);
FieldMappingAttribute mapping =
(FieldMappingAttribute) field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
map[fieldType] = mapping;
}
return Dictionaries.AsReadOnly(map);
}
internal static MappedType MappedTypeFromFieldType(FieldType type)
{
return FieldTypeToMappedTypeMap[type].MappedType;
}
internal static WireFormat.WireType WireTypeFromFieldType(FieldType type, bool packed)
{
return packed ? WireFormat.WireType.LengthDelimited : FieldTypeToMappedTypeMap[type].WireType;
}
}
}
\ No newline at end of file
...@@ -38,23 +38,23 @@ namespace Google.Protobuf.Descriptors ...@@ -38,23 +38,23 @@ namespace Google.Protobuf.Descriptors
/// </summary> /// </summary>
public enum FieldType public enum FieldType
{ {
[FieldMapping(MappedType.Double, WireFormat.WireType.Fixed64)] Double, Double,
[FieldMapping(MappedType.Single, WireFormat.WireType.Fixed32)] Float, Float,
[FieldMapping(MappedType.Int64, WireFormat.WireType.Varint)] Int64, Int64,
[FieldMapping(MappedType.UInt64, WireFormat.WireType.Varint)] UInt64, UInt64,
[FieldMapping(MappedType.Int32, WireFormat.WireType.Varint)] Int32, Int32,
[FieldMapping(MappedType.UInt64, WireFormat.WireType.Fixed64)] Fixed64, Fixed64,
[FieldMapping(MappedType.UInt32, WireFormat.WireType.Fixed32)] Fixed32, Fixed32,
[FieldMapping(MappedType.Boolean, WireFormat.WireType.Varint)] Bool, Bool,
[FieldMapping(MappedType.String, WireFormat.WireType.LengthDelimited)] String, String,
[FieldMapping(MappedType.Message, WireFormat.WireType.StartGroup)] Group, Group,
[FieldMapping(MappedType.Message, WireFormat.WireType.LengthDelimited)] Message, Message,
[FieldMapping(MappedType.ByteString, WireFormat.WireType.LengthDelimited)] Bytes, Bytes,
[FieldMapping(MappedType.UInt32, WireFormat.WireType.Varint)] UInt32, UInt32,
[FieldMapping(MappedType.Int32, WireFormat.WireType.Fixed32)] SFixed32, SFixed32,
[FieldMapping(MappedType.Int64, WireFormat.WireType.Fixed64)] SFixed64, SFixed64,
[FieldMapping(MappedType.Int32, WireFormat.WireType.Varint)] SInt32, SInt32,
[FieldMapping(MappedType.Int64, WireFormat.WireType.Varint)] SInt64, SInt64,
[FieldMapping(MappedType.Enum, WireFormat.WireType.Varint)] Enum Enum
} }
} }
\ No newline at end of file
...@@ -45,11 +45,10 @@ namespace Google.Protobuf.Descriptors ...@@ -45,11 +45,10 @@ namespace Google.Protobuf.Descriptors
/// </summary> /// </summary>
public sealed class FileDescriptor : IDescriptor<FileDescriptorProto> public sealed class FileDescriptor : IDescriptor<FileDescriptorProto>
{ {
private FileDescriptorProto proto; private readonly FileDescriptorProto proto;
private readonly IList<MessageDescriptor> messageTypes; private readonly IList<MessageDescriptor> messageTypes;
private readonly IList<EnumDescriptor> enumTypes; private readonly IList<EnumDescriptor> enumTypes;
private readonly IList<ServiceDescriptor> services; private readonly IList<ServiceDescriptor> services;
private readonly IList<FieldDescriptor> extensions;
private readonly IList<FileDescriptor> dependencies; private readonly IList<FileDescriptor> dependencies;
private readonly IList<FileDescriptor> publicDependencies; private readonly IList<FileDescriptor> publicDependencies;
private readonly DescriptorPool pool; private readonly DescriptorPool pool;
...@@ -86,10 +85,6 @@ namespace Google.Protobuf.Descriptors ...@@ -86,10 +85,6 @@ namespace Google.Protobuf.Descriptors
services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service, services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) => (service, index) =>
new ServiceDescriptor(service, this, index)); new ServiceDescriptor(service, this, index));
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.Extension,
(field, index) =>
new FieldDescriptor(field, this, null, index, true));
} }
/// <summary> /// <summary>
...@@ -129,9 +124,6 @@ namespace Google.Protobuf.Descriptors ...@@ -129,9 +124,6 @@ namespace Google.Protobuf.Descriptors
return new ReadOnlyCollection<FileDescriptor>(publicDependencies); return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
} }
static readonly char[] PathSeperators = new char[] { '/', '\\' };
/// <value> /// <value>
/// The descriptor in its protocol message representation. /// The descriptor in its protocol message representation.
/// </value> /// </value>
...@@ -189,14 +181,6 @@ namespace Google.Protobuf.Descriptors ...@@ -189,14 +181,6 @@ namespace Google.Protobuf.Descriptors
get { return services; } get { return services; }
} }
/// <value>
/// Unmodifiable list of top-level extensions declared in this file.
/// </value>
public IList<FieldDescriptor> Extensions
{
get { return extensions; }
}
/// <value> /// <value>
/// Unmodifiable list of this file's dependencies (imports). /// Unmodifiable list of this file's dependencies (imports).
/// </value> /// </value>
...@@ -350,16 +334,6 @@ namespace Google.Protobuf.Descriptors ...@@ -350,16 +334,6 @@ namespace Google.Protobuf.Descriptors
{ {
service.CrossLink(); service.CrossLink();
} }
foreach (FieldDescriptor extension in extensions)
{
extension.CrossLink();
}
foreach (MessageDescriptor message in messageTypes)
{
message.CheckRequiredFields();
}
} }
/// <summary> /// <summary>
...@@ -415,42 +389,7 @@ namespace Google.Protobuf.Descriptors ...@@ -415,42 +389,7 @@ namespace Google.Protobuf.Descriptors
descriptorAssigner(result); descriptorAssigner(result);
return result; return result;
} }
/// <summary>
/// Replace our FileDescriptorProto with the given one, which is
/// identical except that it might contain extensions that weren't present
/// in the original. This method is needed for bootstrapping when a file
/// defines custom options. The options may be defined in the file itself,
/// so we can't actually parse them until we've constructed the descriptors,
/// but to construct the decsriptors we have to have parsed the descriptor
/// protos. So, we have to parse the descriptor protos a second time after
/// constructing the descriptors.
/// </summary>
private void ReplaceProto(FileDescriptorProto newProto)
{
proto = newProto;
for (int i = 0; i < messageTypes.Count; i++)
{
messageTypes[i].ReplaceProto(proto.MessageType[i]);
}
for (int i = 0; i < enumTypes.Count; i++)
{
enumTypes[i].ReplaceProto(proto.EnumType[i]);
}
for (int i = 0; i < services.Count; i++)
{
services[i].ReplaceProto(proto.Service[i]);
}
for (int i = 0; i < extensions.Count; i++)
{
extensions[i].ReplaceProto(proto.Extension[i]);
}
}
public override string ToString() public override string ToString()
{ {
return "FileDescriptor for " + proto.Name; return "FileDescriptor for " + proto.Name;
......
// 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.
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Type as it's mapped onto a .NET type.
/// </summary>
public enum MappedType
{
Int32,
Int64,
UInt32,
UInt64,
Single,
Double,
Boolean,
String,
ByteString,
Message,
Enum
}
}
\ No newline at end of file
...@@ -44,10 +44,8 @@ namespace Google.Protobuf.Descriptors ...@@ -44,10 +44,8 @@ namespace Google.Protobuf.Descriptors
private readonly IList<MessageDescriptor> nestedTypes; private readonly IList<MessageDescriptor> nestedTypes;
private readonly IList<EnumDescriptor> enumTypes; private readonly IList<EnumDescriptor> enumTypes;
private readonly IList<FieldDescriptor> fields; private readonly IList<FieldDescriptor> fields;
private readonly IList<FieldDescriptor> extensions;
private readonly IList<OneofDescriptor> oneofs; private readonly IList<OneofDescriptor> oneofs;
private bool hasRequiredFields;
internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex) internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex)
: base(proto, file, ComputeFullName(file, parent, proto.Name), typeIndex) : base(proto, file, ComputeFullName(file, parent, proto.Name), typeIndex)
{ {
...@@ -68,11 +66,7 @@ namespace Google.Protobuf.Descriptors ...@@ -68,11 +66,7 @@ namespace Google.Protobuf.Descriptors
// TODO(jonskeet): Sort fields first? // TODO(jonskeet): Sort fields first?
fields = DescriptorUtil.ConvertAndMakeReadOnly(proto.Field, fields = DescriptorUtil.ConvertAndMakeReadOnly(proto.Field,
(field, index) => (field, index) =>
new FieldDescriptor(field, file, this, index, false)); new FieldDescriptor(field, file, this, index));
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.Extension,
(field, index) =>
new FieldDescriptor(field, file, this, index, true));
for (int i = 0; i < proto.OneofDecl.Count; i++) for (int i = 0; i < proto.OneofDecl.Count; i++)
{ {
...@@ -106,14 +100,6 @@ namespace Google.Protobuf.Descriptors ...@@ -106,14 +100,6 @@ namespace Google.Protobuf.Descriptors
get { return fields; } get { return fields; }
} }
/// <value>
/// An unmodifiable list of this message type's extensions.
/// </value>
public IList<FieldDescriptor> Extensions
{
get { return extensions; }
}
/// <value> /// <value>
/// An unmodifiable list of this message type's nested types. /// An unmodifiable list of this message type's nested types.
/// </value> /// </value>
...@@ -135,32 +121,6 @@ namespace Google.Protobuf.Descriptors ...@@ -135,32 +121,6 @@ namespace Google.Protobuf.Descriptors
get { return oneofs; } get { return oneofs; }
} }
/// <summary>
/// Returns a pre-computed result as to whether this message
/// has required fields. This includes optional fields which are
/// message types which in turn have required fields, and any
/// extension fields.
/// </summary>
internal bool HasRequiredFields
{
get { return hasRequiredFields; }
}
/// <summary>
/// Determines if the given field number is an extension.
/// </summary>
public bool IsExtensionNumber(int number)
{
foreach (DescriptorProto.Types.ExtensionRange range in Proto.ExtensionRange)
{
if (range.Start <= number && number < range.End)
{
return true;
}
}
return false;
}
/// <summary> /// <summary>
/// Finds a field by field name. /// Finds a field by field name.
/// </summary> /// </summary>
...@@ -194,7 +154,7 @@ namespace Google.Protobuf.Descriptors ...@@ -194,7 +154,7 @@ namespace Google.Protobuf.Descriptors
} }
/// <summary> /// <summary>
/// Looks up and cross-links all fields, nested types, and extensions. /// Looks up and cross-links all fields and nested types.
/// </summary> /// </summary>
internal void CrossLink() internal void CrossLink()
{ {
...@@ -208,62 +168,11 @@ namespace Google.Protobuf.Descriptors ...@@ -208,62 +168,11 @@ namespace Google.Protobuf.Descriptors
field.CrossLink(); field.CrossLink();
} }
foreach (FieldDescriptor extension in extensions)
{
extension.CrossLink();
}
foreach (OneofDescriptor oneof in oneofs) foreach (OneofDescriptor oneof in oneofs)
{ {
// oneof.C // TODO(jonskeet): Do we need to do this?
} // oneof.C
}
internal void CheckRequiredFields()
{
IDictionary<MessageDescriptor, byte> alreadySeen = new Dictionary<MessageDescriptor, byte>();
hasRequiredFields = CheckRequiredFields(alreadySeen);
}
private bool CheckRequiredFields(IDictionary<MessageDescriptor, byte> alreadySeen)
{
if (alreadySeen.ContainsKey(this))
{
// The type is already in the cache. This means that either:
// a. The type has no required fields.
// b. We are in the midst of checking if the type has required fields,
// somewhere up the stack. In this case, we know that if the type
// has any required fields, they'll be found when we return to it,
// and the whole call to HasRequiredFields() will return true.
// Therefore, we don't have to check if this type has required fields
// here.
return false;
}
alreadySeen[this] = 0; // Value is irrelevant; we want set semantics
// If the type allows extensions, an extension with message type could contain
// required fields, so we have to be conservative and assume such an
// extension exists.
if (Proto.ExtensionRange.Count != 0)
{
return true;
} }
foreach (FieldDescriptor field in Fields)
{
if (field.IsRequired)
{
return true;
}
if (field.MappedType == MappedType.Message)
{
if (field.MessageType.CheckRequiredFields(alreadySeen))
{
return true;
}
}
}
return false;
} }
/// <summary> /// <summary>
...@@ -287,11 +196,6 @@ namespace Google.Protobuf.Descriptors ...@@ -287,11 +196,6 @@ namespace Google.Protobuf.Descriptors
{ {
fields[i].ReplaceProto(newProto.Field[i]); fields[i].ReplaceProto(newProto.Field[i]);
} }
for (int i = 0; i < extensions.Count; i++)
{
extensions[i].ReplaceProto(newProto.Extension[i]);
}
} }
} }
} }
\ No newline at end of file
...@@ -69,7 +69,6 @@ namespace Google.Protobuf.FieldAccess ...@@ -69,7 +69,6 @@ namespace Google.Protobuf.FieldAccess
get get
{ {
FieldDescriptor field = descriptor.FindFieldByNumber(fieldNumber); FieldDescriptor field = descriptor.FindFieldByNumber(fieldNumber);
// TODO: Handle extensions.
return accessors[field.Index]; return accessors[field.Index];
} }
} }
...@@ -82,12 +81,6 @@ namespace Google.Protobuf.FieldAccess ...@@ -82,12 +81,6 @@ namespace Google.Protobuf.FieldAccess
{ {
throw new ArgumentException("FieldDescriptor does not match message type."); throw new ArgumentException("FieldDescriptor does not match message type.");
} }
else if (field.IsExtension)
{
// If this type had extensions, it would subclass ExtendableMessage,
// which overrides the reflection interface to handle extensions.
throw new ArgumentException("This type does not have extensions.");
}
return accessors[field.Index]; return accessors[field.Index];
} }
} }
......
...@@ -54,16 +54,12 @@ ...@@ -54,16 +54,12 @@
<ItemGroup> <ItemGroup>
<Compile Include="ByteArray.cs" /> <Compile Include="ByteArray.cs" />
<Compile Include="ByteString.cs" /> <Compile Include="ByteString.cs" />
<Compile Include="Collections\Enumerables.cs" />
<Compile Include="CodedOutputStream.ComputeSize.cs" /> <Compile Include="CodedOutputStream.ComputeSize.cs" />
<Compile Include="CodedInputStream.cs" /> <Compile Include="CodedInputStream.cs" />
<Compile Include="CodedOutputStream.cs" /> <Compile Include="CodedOutputStream.cs" />
<Compile Include="Collections\Dictionaries.cs" />
<Compile Include="Collections\Lists.cs" />
<Compile Include="Collections\MapField.cs" /> <Compile Include="Collections\MapField.cs" />
<Compile Include="Collections\ReadOnlyDictionary.cs" /> <Compile Include="Collections\ReadOnlyDictionary.cs" />
<Compile Include="Collections\RepeatedField.cs" /> <Compile Include="Collections\RepeatedField.cs" />
<Compile Include="Collections\RepeatedFieldExtensions.cs" />
<Compile Include="DescriptorProtos\DescriptorProtoFile.cs" /> <Compile Include="DescriptorProtos\DescriptorProtoFile.cs" />
<Compile Include="DescriptorProtos\IDescriptorProto.cs" /> <Compile Include="DescriptorProtos\IDescriptorProto.cs" />
<Compile Include="DescriptorProtos\PartialClasses.cs" /> <Compile Include="DescriptorProtos\PartialClasses.cs" />
...@@ -74,13 +70,11 @@ ...@@ -74,13 +70,11 @@
<Compile Include="Descriptors\EnumDescriptor.cs" /> <Compile Include="Descriptors\EnumDescriptor.cs" />
<Compile Include="Descriptors\EnumValueDescriptor.cs" /> <Compile Include="Descriptors\EnumValueDescriptor.cs" />
<Compile Include="Descriptors\FieldDescriptor.cs" /> <Compile Include="Descriptors\FieldDescriptor.cs" />
<Compile Include="Descriptors\FieldMappingAttribute.cs" />
<Compile Include="Descriptors\FieldType.cs" /> <Compile Include="Descriptors\FieldType.cs" />
<Compile Include="Descriptors\FileDescriptor.cs" /> <Compile Include="Descriptors\FileDescriptor.cs" />
<Compile Include="Descriptors\OneofDescriptor.cs" /> <Compile Include="Descriptors\OneofDescriptor.cs" />
<Compile Include="Descriptors\IDescriptor.cs" /> <Compile Include="Descriptors\IDescriptor.cs" />
<Compile Include="Descriptors\IndexedDescriptorBase.cs" /> <Compile Include="Descriptors\IndexedDescriptorBase.cs" />
<Compile Include="Descriptors\MappedType.cs" />
<Compile Include="Descriptors\MessageDescriptor.cs" /> <Compile Include="Descriptors\MessageDescriptor.cs" />
<Compile Include="Descriptors\MethodDescriptor.cs" /> <Compile Include="Descriptors\MethodDescriptor.cs" />
<Compile Include="Descriptors\PackageDescriptor.cs" /> <Compile Include="Descriptors\PackageDescriptor.cs" />
...@@ -101,7 +95,6 @@ ...@@ -101,7 +95,6 @@
<Compile Include="LimitedInputStream.cs" /> <Compile Include="LimitedInputStream.cs" />
<Compile Include="MessageParser.cs" /> <Compile Include="MessageParser.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TextGenerator.cs" />
<Compile Include="ThrowHelper.cs" /> <Compile Include="ThrowHelper.cs" />
<Compile Include="WireFormat.cs" /> <Compile Include="WireFormat.cs" />
</ItemGroup> </ItemGroup>
......
#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;
using System.Text;
namespace Google.Protobuf
{
/// <summary>
/// Helper class to control indentation. Used for TextFormat and by ProtoGen.
/// </summary>
public sealed class TextGenerator
{
/// <summary>
/// The string to use at the end of each line. We assume that "Print" is only called using \n
/// to indicate a line break; that's what we use to detect when we need to indent etc, and
/// *just* the \n is replaced with the contents of lineBreak.
/// </summary>
private readonly string lineBreak;
/// <summary>
/// Writer to write formatted text to.
/// </summary>
private readonly TextWriter writer;
/// <summary>
/// Keeps track of whether the next piece of text should be indented
/// </summary>
private bool atStartOfLine = true;
/// <summary>
/// Keeps track of the current level of indentation
/// </summary>
private readonly StringBuilder indent = new StringBuilder();
/// <summary>
/// Creates a generator writing to the given writer. The writer
/// is not closed by this class.
/// </summary>
public TextGenerator(TextWriter writer, string lineBreak)
{
this.writer = writer;
this.lineBreak = lineBreak;
}
/// <summary>
/// Indents text by two spaces. After calling Indent(), two spaces
/// will be inserted at the beginning of each line of text. Indent() may
/// be called multiple times to produce deeper indents.
/// </summary>
public void Indent()
{
indent.Append(" ");
}
/// <summary>
/// Reduces the current indent level by two spaces.
/// </summary>
public void Outdent()
{
if (indent.Length == 0)
{
throw new InvalidOperationException("Too many calls to Outdent()");
}
indent.Length -= 2;
}
public void WriteLine(string text)
{
Print(text);
Print("\n");
}
public void WriteLine(string format, params object[] args)
{
WriteLine(string.Format(format, args));
}
public void WriteLine()
{
WriteLine("");
}
/// <summary>
/// Prints the given text to the output stream, indenting at line boundaries.
/// </summary>
/// <param name="text"></param>
public void Print(string text)
{
int pos = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
// Strip off the \n from what we write
Write(text.Substring(pos, i - pos));
Write(lineBreak);
pos = i + 1;
atStartOfLine = true;
}
}
Write(text.Substring(pos));
}
public void Write(string format, params object[] args)
{
Write(string.Format(format, args));
}
private void Write(string data)
{
if (data.Length == 0)
{
return;
}
if (atStartOfLine)
{
atStartOfLine = false;
writer.Write(indent);
}
writer.Write(data);
}
}
}
\ No newline at end of file
...@@ -35,7 +35,6 @@ ...@@ -35,7 +35,6 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
namespace Google.Protobuf namespace Google.Protobuf
{ {
...@@ -54,30 +53,5 @@ namespace Google.Protobuf ...@@ -54,30 +53,5 @@ namespace Google.Protobuf
throw new ArgumentNullException(name); throw new ArgumentNullException(name);
} }
} }
/// <summary>
/// Throws an ArgumentNullException if the given value is null.
/// </summary>
internal static void ThrowIfNull(object value)
{
if (value == null)
{
throw new ArgumentNullException();
}
}
/// <summary>
/// Throws an ArgumentNullException if the given value or any element within it is null.
/// </summary>
internal static void ThrowIfAnyNull<T>(IEnumerable<T> sequence)
{
foreach (T t in sequence)
{
if (t == null)
{
throw new ArgumentNullException();
}
}
}
} }
} }
\ No newline at end of file
...@@ -114,7 +114,6 @@ namespace Google.Protobuf ...@@ -114,7 +114,6 @@ namespace Google.Protobuf
/// <summary> /// <summary>
/// Makes a tag value given a field number and wire type. /// Makes a tag value given a field number and wire type.
/// TODO(jonskeet): Should we just have a Tag structure?
/// </summary> /// </summary>
public static uint MakeTag(int fieldNumber, WireType wireType) public static uint MakeTag(int fieldNumber, WireType wireType)
{ {
......
optional_int32: 101
optional_int64: 102
optional_uint32: 103
optional_uint64: 104
optional_sint32: 105
optional_sint64: 106
optional_fixed32: 107
optional_fixed64: 108
optional_sfixed32: 109
optional_sfixed64: 110
optional_float: 111
optional_double: 112
optional_bool: true
optional_string: "115"
optional_bytes: "116"
OptionalGroup {
a: 117
}
optional_nested_message {
bb: 118
}
optional_foreign_message {
c: 119
}
optional_import_message {
d: 120
}
optional_nested_enum: BAZ
optional_foreign_enum: FOREIGN_BAZ
optional_import_enum: IMPORT_BAZ
optional_string_piece: "124"
optional_cord: "125"
repeated_int32: 201
repeated_int32: 301
repeated_int64: 202
repeated_int64: 302
repeated_uint32: 203
repeated_uint32: 303
repeated_uint64: 204
repeated_uint64: 304
repeated_sint32: 205
repeated_sint32: 305
repeated_sint64: 206
repeated_sint64: 306
repeated_fixed32: 207
repeated_fixed32: 307
repeated_fixed64: 208
repeated_fixed64: 308
repeated_sfixed32: 209
repeated_sfixed32: 309
repeated_sfixed64: 210
repeated_sfixed64: 310
repeated_float: 211
repeated_float: 311
repeated_double: 212
repeated_double: 312
repeated_bool: true
repeated_bool: false
repeated_string: "215"
repeated_string: "315"
repeated_bytes: "216"
repeated_bytes: "316"
RepeatedGroup {
a: 217
}
RepeatedGroup {
a: 317
}
repeated_nested_message {
bb: 218
}
repeated_nested_message {
bb: 318
}
repeated_foreign_message {
c: 219
}
repeated_foreign_message {
c: 319
}
repeated_import_message {
d: 220
}
repeated_import_message {
d: 320
}
repeated_nested_enum: BAR
repeated_nested_enum: BAZ
repeated_foreign_enum: FOREIGN_BAR
repeated_foreign_enum: FOREIGN_BAZ
repeated_import_enum: IMPORT_BAR
repeated_import_enum: IMPORT_BAZ
repeated_string_piece: "224"
repeated_string_piece: "324"
repeated_cord: "225"
repeated_cord: "325"
default_int32: 401
default_int64: 402
default_uint32: 403
default_uint64: 404
default_sint32: 405
default_sint64: 406
default_fixed32: 407
default_fixed64: 408
default_sfixed32: 409
default_sfixed64: 410
default_float: 411
default_double: 412
default_bool: false
default_string: "415"
default_bytes: "416"
default_nested_enum: FOO
default_foreign_enum: FOREIGN_FOO
default_import_enum: IMPORT_FOO
default_string_piece: "424"
default_cord: "425"
[protobuf_unittest.optional_int32_extension]: 101
[protobuf_unittest.optional_int64_extension]: 102
[protobuf_unittest.optional_uint32_extension]: 103
[protobuf_unittest.optional_uint64_extension]: 104
[protobuf_unittest.optional_sint32_extension]: 105
[protobuf_unittest.optional_sint64_extension]: 106
[protobuf_unittest.optional_fixed32_extension]: 107
[protobuf_unittest.optional_fixed64_extension]: 108
[protobuf_unittest.optional_sfixed32_extension]: 109
[protobuf_unittest.optional_sfixed64_extension]: 110
[protobuf_unittest.optional_float_extension]: 111
[protobuf_unittest.optional_double_extension]: 112
[protobuf_unittest.optional_bool_extension]: true
[protobuf_unittest.optional_string_extension]: "115"
[protobuf_unittest.optional_bytes_extension]: "116"
[protobuf_unittest.optionalgroup_extension] {
a: 117
}
[protobuf_unittest.optional_nested_message_extension] {
bb: 118
}
[protobuf_unittest.optional_foreign_message_extension] {
c: 119
}
[protobuf_unittest.optional_import_message_extension] {
d: 120
}
[protobuf_unittest.optional_nested_enum_extension]: BAZ
[protobuf_unittest.optional_foreign_enum_extension]: FOREIGN_BAZ
[protobuf_unittest.optional_import_enum_extension]: IMPORT_BAZ
[protobuf_unittest.optional_string_piece_extension]: "124"
[protobuf_unittest.optional_cord_extension]: "125"
[protobuf_unittest.repeated_int32_extension]: 201
[protobuf_unittest.repeated_int32_extension]: 301
[protobuf_unittest.repeated_int64_extension]: 202
[protobuf_unittest.repeated_int64_extension]: 302
[protobuf_unittest.repeated_uint32_extension]: 203
[protobuf_unittest.repeated_uint32_extension]: 303
[protobuf_unittest.repeated_uint64_extension]: 204
[protobuf_unittest.repeated_uint64_extension]: 304
[protobuf_unittest.repeated_sint32_extension]: 205
[protobuf_unittest.repeated_sint32_extension]: 305
[protobuf_unittest.repeated_sint64_extension]: 206
[protobuf_unittest.repeated_sint64_extension]: 306
[protobuf_unittest.repeated_fixed32_extension]: 207
[protobuf_unittest.repeated_fixed32_extension]: 307
[protobuf_unittest.repeated_fixed64_extension]: 208
[protobuf_unittest.repeated_fixed64_extension]: 308
[protobuf_unittest.repeated_sfixed32_extension]: 209
[protobuf_unittest.repeated_sfixed32_extension]: 309
[protobuf_unittest.repeated_sfixed64_extension]: 210
[protobuf_unittest.repeated_sfixed64_extension]: 310
[protobuf_unittest.repeated_float_extension]: 211
[protobuf_unittest.repeated_float_extension]: 311
[protobuf_unittest.repeated_double_extension]: 212
[protobuf_unittest.repeated_double_extension]: 312
[protobuf_unittest.repeated_bool_extension]: true
[protobuf_unittest.repeated_bool_extension]: false
[protobuf_unittest.repeated_string_extension]: "215"
[protobuf_unittest.repeated_string_extension]: "315"
[protobuf_unittest.repeated_bytes_extension]: "216"
[protobuf_unittest.repeated_bytes_extension]: "316"
[protobuf_unittest.repeatedgroup_extension] {
a: 217
}
[protobuf_unittest.repeatedgroup_extension] {
a: 317
}
[protobuf_unittest.repeated_nested_message_extension] {
bb: 218
}
[protobuf_unittest.repeated_nested_message_extension] {
bb: 318
}
[protobuf_unittest.repeated_foreign_message_extension] {
c: 219
}
[protobuf_unittest.repeated_foreign_message_extension] {
c: 319
}
[protobuf_unittest.repeated_import_message_extension] {
d: 220
}
[protobuf_unittest.repeated_import_message_extension] {
d: 320
}
[protobuf_unittest.repeated_nested_enum_extension]: BAR
[protobuf_unittest.repeated_nested_enum_extension]: BAZ
[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAR
[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAZ
[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAR
[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAZ
[protobuf_unittest.repeated_string_piece_extension]: "224"
[protobuf_unittest.repeated_string_piece_extension]: "324"
[protobuf_unittest.repeated_cord_extension]: "225"
[protobuf_unittest.repeated_cord_extension]: "325"
[protobuf_unittest.default_int32_extension]: 401
[protobuf_unittest.default_int64_extension]: 402
[protobuf_unittest.default_uint32_extension]: 403
[protobuf_unittest.default_uint64_extension]: 404
[protobuf_unittest.default_sint32_extension]: 405
[protobuf_unittest.default_sint64_extension]: 406
[protobuf_unittest.default_fixed32_extension]: 407
[protobuf_unittest.default_fixed64_extension]: 408
[protobuf_unittest.default_sfixed32_extension]: 409
[protobuf_unittest.default_sfixed64_extension]: 410
[protobuf_unittest.default_float_extension]: 411
[protobuf_unittest.default_double_extension]: 412
[protobuf_unittest.default_bool_extension]: false
[protobuf_unittest.default_string_extension]: "415"
[protobuf_unittest.default_bytes_extension]: "416"
[protobuf_unittest.default_nested_enum_extension]: FOO
[protobuf_unittest.default_foreign_enum_extension]: FOREIGN_FOO
[protobuf_unittest.default_import_enum_extension]: IMPORT_FOO
[protobuf_unittest.default_string_piece_extension]: "424"
[protobuf_unittest.default_cord_extension]: "425"
...@@ -6,7 +6,7 @@ package tutorial; ...@@ -6,7 +6,7 @@ package tutorial;
option java_package = "com.example.tutorial"; option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos"; option java_outer_classname = "AddressBookProtos";
option csharp_namespace = "Google.ProtocolBuffers.Examples.AddressBook"; option csharp_namespace = "Google.Protobuf.Examples.AddressBook";
message Person { message Person {
required string name = 1; required string name = 1;
......
...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true; ...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "AnyProto"; option java_outer_classname = "AnyProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
......
...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true; ...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "DurationProto"; option java_outer_classname = "DurationProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
// A Duration represents a signed, fixed-length span of time represented // A Duration represents a signed, fixed-length span of time represented
......
...@@ -34,7 +34,7 @@ package google.protobuf; ...@@ -34,7 +34,7 @@ package google.protobuf;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "FieldMaskProto"; option java_outer_classname = "FieldMaskProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
......
...@@ -32,7 +32,6 @@ syntax = "proto2"; ...@@ -32,7 +32,6 @@ syntax = "proto2";
option cc_enable_arenas = true; option cc_enable_arenas = true;
option optimize_for = LITE_RUNTIME; option optimize_for = LITE_RUNTIME;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
import "google/protobuf/unittest_lite.proto"; import "google/protobuf/unittest_lite.proto";
......
...@@ -36,8 +36,6 @@ syntax = "proto2"; ...@@ -36,8 +36,6 @@ syntax = "proto2";
// In map_test_util.h we do "using namespace unittest = protobuf_unittest". // In map_test_util.h we do "using namespace unittest = protobuf_unittest".
package protobuf_unittest; package protobuf_unittest;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
enum Proto2MapEnum { enum Proto2MapEnum {
PROTO2_MAP_ENUM_FOO = 0; PROTO2_MAP_ENUM_FOO = 0;
PROTO2_MAP_ENUM_BAR = 1; PROTO2_MAP_ENUM_BAR = 1;
......
...@@ -31,7 +31,6 @@ ...@@ -31,7 +31,6 @@
syntax = "proto3"; syntax = "proto3";
option cc_enable_arenas = true; option cc_enable_arenas = true;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
import "google/protobuf/unittest.proto"; import "google/protobuf/unittest.proto";
......
...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true; ...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "StructProto"; option java_outer_classname = "StructProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
......
...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true; ...@@ -35,7 +35,7 @@ option java_generate_equals_and_hash = true;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "TimestampProto"; option java_outer_classname = "TimestampProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
......
...@@ -42,7 +42,6 @@ option cc_generic_services = true; // auto-added ...@@ -42,7 +42,6 @@ option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added option java_generic_services = true; // auto-added
option py_generic_services = true; // auto-added option py_generic_services = true; // auto-added
option cc_enable_arenas = true; option cc_enable_arenas = true;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
import "google/protobuf/unittest_import.proto"; import "google/protobuf/unittest_import.proto";
......
...@@ -41,7 +41,6 @@ syntax = "proto2"; ...@@ -41,7 +41,6 @@ syntax = "proto2";
option cc_generic_services = true; // auto-added option cc_generic_services = true; // auto-added
option java_generic_services = true; // auto-added option java_generic_services = true; // auto-added
option py_generic_services = true; option py_generic_services = true;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// A custom file option (defined below). // A custom file option (defined below).
option (file_opt1) = 9876543210; option (file_opt1) = 9876543210;
......
...@@ -33,7 +33,7 @@ syntax = "proto3"; ...@@ -33,7 +33,7 @@ syntax = "proto3";
package unittest_drop_unknown_fields; package unittest_drop_unknown_fields;
option objc_class_prefix = "DropUnknowns"; option objc_class_prefix = "DropUnknowns";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; option csharp_namespace = "Google.Protobuf.TestProtos";
message Foo { message Foo {
enum NestedEnum { enum NestedEnum {
......
...@@ -39,8 +39,6 @@ import "google/protobuf/unittest_optimize_for.proto"; ...@@ -39,8 +39,6 @@ import "google/protobuf/unittest_optimize_for.proto";
package protobuf_unittest; package protobuf_unittest;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// We optimize for speed here, but we are importing a proto that is optimized // We optimize for speed here, but we are importing a proto that is optimized
// for code size. // for code size.
option optimize_for = SPEED; option optimize_for = SPEED;
......
...@@ -40,7 +40,6 @@ syntax = "proto2"; ...@@ -40,7 +40,6 @@ syntax = "proto2";
package google.protobuf; package google.protobuf;
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// Avoid generating insanely long methods. // Avoid generating insanely long methods.
option optimize_for = CODE_SIZE; option optimize_for = CODE_SIZE;
......
...@@ -47,7 +47,6 @@ option cc_enable_arenas = true; ...@@ -47,7 +47,6 @@ option cc_enable_arenas = true;
// Exercise the java_package option. // Exercise the java_package option.
option java_package = "com.google.protobuf.test"; option java_package = "com.google.protobuf.test";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// Do not set a java_outer_classname here to verify that Proto2 works without // Do not set a java_outer_classname here to verify that Proto2 works without
// one. // one.
......
...@@ -38,7 +38,6 @@ package protobuf_unittest_import; ...@@ -38,7 +38,6 @@ package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME; option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
import public "google/protobuf/unittest_import_public_lite.proto"; import public "google/protobuf/unittest_import_public_lite.proto";
......
...@@ -35,7 +35,6 @@ syntax = "proto2"; ...@@ -35,7 +35,6 @@ syntax = "proto2";
package protobuf_unittest_import; package protobuf_unittest_import;
option java_package = "com.google.protobuf.test"; option java_package = "com.google.protobuf.test";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message PublicImportMessage { message PublicImportMessage {
optional int32 e = 1; optional int32 e = 1;
......
...@@ -37,7 +37,6 @@ package protobuf_unittest_import; ...@@ -37,7 +37,6 @@ package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME; option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message PublicImportMessageLite { message PublicImportMessageLite {
optional int32 e = 1; optional int32 e = 1;
......
...@@ -40,7 +40,6 @@ import "google/protobuf/unittest_import_lite.proto"; ...@@ -40,7 +40,6 @@ import "google/protobuf/unittest_import_lite.proto";
option optimize_for = LITE_RUNTIME; option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// Same as TestAllTypes but with the lite runtime. // Same as TestAllTypes but with the lite runtime.
message TestAllTypesLite { message TestAllTypesLite {
......
...@@ -38,7 +38,6 @@ package protobuf_unittest; ...@@ -38,7 +38,6 @@ package protobuf_unittest;
import "google/protobuf/unittest.proto"; import "google/protobuf/unittest.proto";
option optimize_for = LITE_RUNTIME; option optimize_for = LITE_RUNTIME;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message TestLiteImportsNonlite { message TestLiteImportsNonlite {
optional TestAllTypes message = 1; optional TestAllTypes message = 1;
......
...@@ -39,7 +39,6 @@ package protobuf_unittest; ...@@ -39,7 +39,6 @@ package protobuf_unittest;
option cc_enable_arenas = true; option cc_enable_arenas = true;
option optimize_for = SPEED; option optimize_for = SPEED;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
// A message with message_set_wire_format. // A message with message_set_wire_format.
message TestMessageSet { message TestMessageSet {
......
...@@ -37,8 +37,6 @@ import "google/protobuf/unittest.proto"; ...@@ -37,8 +37,6 @@ import "google/protobuf/unittest.proto";
package proto2_nofieldpresence_unittest; package proto2_nofieldpresence_unittest;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos.Proto3";
// This proto includes every type of field in both singular and repeated // This proto includes every type of field in both singular and repeated
// forms. // forms.
message TestAllTypes { message TestAllTypes {
......
...@@ -40,7 +40,6 @@ import "google/protobuf/unittest.proto"; ...@@ -40,7 +40,6 @@ import "google/protobuf/unittest.proto";
package protobuf_unittest; package protobuf_unittest;
option optimize_for = CODE_SIZE; option optimize_for = CODE_SIZE;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message TestOptimizedForSize { message TestOptimizedForSize {
optional int32 i = 1; optional int32 i = 1;
......
...@@ -33,7 +33,7 @@ syntax = "proto3"; ...@@ -33,7 +33,7 @@ syntax = "proto3";
package proto3_preserve_unknown_enum_unittest; package proto3_preserve_unknown_enum_unittest;
option objc_class_prefix = "UnknownEnums"; option objc_class_prefix = "UnknownEnums";
option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; option csharp_namespace = "Google.Protobuf.TestProtos";
enum MyEnum { enum MyEnum {
FOO = 0; FOO = 0;
......
...@@ -32,8 +32,6 @@ syntax = "proto2"; ...@@ -32,8 +32,6 @@ syntax = "proto2";
package proto2_preserve_unknown_enum_unittest; package proto2_preserve_unknown_enum_unittest;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
enum MyEnum { enum MyEnum {
FOO = 0; FOO = 0;
BAR = 1; BAR = 1;
......
...@@ -36,8 +36,6 @@ syntax = "proto2"; ...@@ -36,8 +36,6 @@ syntax = "proto2";
package google.protobuf.util; package google.protobuf.util;
option csharp_namespace = "Google.ProtocolBuffers.TestProtos";
message DownRevision { message DownRevision {
enum Enum { enum Enum {
DEFAULT_VALUE = 2; DEFAULT_VALUE = 2;
......
...@@ -40,7 +40,7 @@ package google.protobuf; ...@@ -40,7 +40,7 @@ package google.protobuf;
option java_multiple_files = true; option java_multiple_files = true;
option java_outer_classname = "WrappersProto"; option java_outer_classname = "WrappersProto";
option java_package = "com.google.protobuf"; option java_package = "com.google.protobuf";
option csharp_namespace = "Google.ProtocolBuffers"; option csharp_namespace = "Google.Protobuf";
option objc_class_prefix = "GPB"; option objc_class_prefix = "GPB";
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment