Skip to content

Commit a81f3b7

Browse files
committed
Add sample sources.
1 parent d451f0d commit a81f3b7

10 files changed

Lines changed: 741 additions & 140 deletions

MsgPack.sln

Lines changed: 22 additions & 140 deletions
Large diffs are not rendered by default.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
6+
// アセンブリに関連付けられている情報を変更するには、
7+
// これらの属性値を変更してください。
8+
[assembly: AssemblyTitle("Samples")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("Samples")]
13+
[assembly: AssemblyCopyright("Copyright © 2014")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
18+
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
19+
// その型の ComVisible 属性を true に設定してください。
20+
[assembly: ComVisible(false)]
21+
22+
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
23+
[assembly: Guid("d3ba6c47-60c9-4e4e-90c5-45e747bc5dcc")]
24+
25+
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
26+
//
27+
// Major Version
28+
// Minor Version
29+
// Build Number
30+
// Revision
31+
//
32+
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
33+
// 既定値にすることができます:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#region -- License Terms --
2+
//
3+
// MessagePack for CLI
4+
//
5+
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
6+
//
7+
// Licensed under the Apache License, Version 2.0 (the "License");
8+
// you may not use this file except in compliance with the License.
9+
// You may obtain a copy of the License at
10+
//
11+
// http://www.apache.org/licenses/LICENSE-2.0
12+
//
13+
// Unless required by applicable law or agreed to in writing, software
14+
// distributed under the License is distributed on an "AS IS" BASIS,
15+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
// See the License for the specific language governing permissions and
17+
// limitations under the License.
18+
//
19+
#endregion -- License Terms --
20+
21+
using System;
22+
using System.Collections.Generic;
23+
using System.Diagnostics;
24+
using System.IO;
25+
26+
using MsgPack.Serialization;
27+
28+
using NUnit.Framework; // For running checking
29+
30+
namespace Samples
31+
{
32+
/// <summary>
33+
/// A simple sample code for basic serialization/deserialization.
34+
/// </summary>
35+
[TestFixture]
36+
public class BasicUsageSample
37+
{
38+
[Test]
39+
public void SerializeThenDeserialize()
40+
{
41+
// They are object for just description.
42+
var targetObject =
43+
new PhotoEntry
44+
{
45+
Id = 123,
46+
Title = "My photo",
47+
Date = DateTime.Now,
48+
Image = new byte[] { 1, 2, 3, 4 },
49+
Comment = "This is test object to be serialize/deserialize using MsgPack."
50+
};
51+
targetObject.Tags.Add( "Sample" );
52+
targetObject.Tags.Add( "Excellent" );
53+
var stream = new MemoryStream();
54+
55+
// 1. Create serializer instance.
56+
var serializer = SerializationContext.Default.GetSerializer<PhotoEntry>();
57+
58+
// 2. Serialize object to the specified stream.
59+
serializer.Pack( stream, targetObject );
60+
61+
// Set position to head of the stream to demonstrate deserialization.
62+
stream.Position = 0;
63+
64+
// 3. Deserialize object from the specified stream.
65+
var deserializedObject = serializer.Unpack( stream );
66+
67+
// Test deserialized value.
68+
Debug.WriteLine( "Same object? {0}", Object.ReferenceEquals( targetObject, deserializedObject ) );
69+
Debug.WriteLine( "Same Id? {0}", targetObject.Id == deserializedObject.Id );
70+
Debug.WriteLine( "Same Title? {0}", targetObject.Title == deserializedObject.Title );
71+
// Note that MsgPack defacto-standard is Unix epoc in milliseconds precision, so micro- and nano- seconds will be lost. See sample 04 for workaround.
72+
Debug.WriteLine( "Same Date? {0}", targetObject.Date.ToString( "YYYY-MM-DD HH:mm:ss.fff" ) == deserializedObject.Date.ToString( "YYYY-MM-DD HH:mm:ss.fff" ) );
73+
// Image and Comment tests are ommitted here.
74+
// Collection elements are deserialzed.
75+
Debug.WriteLine( "Items count: {0}", deserializedObject.Tags.Count );
76+
}
77+
}
78+
79+
public class PhotoEntry
80+
{
81+
public long Id { get; set; }
82+
public string Title { get; set; }
83+
public DateTime Date { get; set; }
84+
public string Comment { get; set; }
85+
public byte[] Image { get; set; }
86+
private readonly List<string> _tags = new List<string>();
87+
// Note that non-null read-only collection members are OK (of course, collections themselves must not be readonly.)
88+
public IList<string> Tags { get { return this._tags; } }
89+
}
90+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#region -- License Terms --
2+
//
3+
// MessagePack for CLI
4+
//
5+
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
6+
//
7+
// Licensed under the Apache License, Version 2.0 (the "License");
8+
// you may not use this file except in compliance with the License.
9+
// You may obtain a copy of the License at
10+
//
11+
// http://www.apache.org/licenses/LICENSE-2.0
12+
//
13+
// Unless required by applicable law or agreed to in writing, software
14+
// distributed under the License is distributed on an "AS IS" BASIS,
15+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
// See the License for the specific language governing permissions and
17+
// limitations under the License.
18+
//
19+
#endregion -- License Terms --
20+
21+
using System;
22+
using System.Diagnostics;
23+
using System.IO;
24+
25+
using MsgPack;
26+
using MsgPack.Serialization;
27+
using NUnit.Framework; // For running checking
28+
29+
namespace Samples
30+
{
31+
/// <summary>
32+
/// A sample code for explore MessagePackObject.
33+
/// </summary>
34+
[TestFixture]
35+
public class HandlingDynamicObjectSample
36+
{
37+
[Test]
38+
public void SerializeThenDeserialize()
39+
{
40+
// They are object for just description.
41+
var targetObject =
42+
new PhotoEntry // See Sample01_BasicUsage.cs
43+
{
44+
Id = 123,
45+
Title = "My photo",
46+
Date = DateTime.Now,
47+
Image = new byte[] { 1, 2, 3, 4 },
48+
Comment = "This is test object to be serialize/deserialize using MsgPack."
49+
};
50+
targetObject.Tags.Add( "Sample" );
51+
targetObject.Tags.Add( "Excellent" );
52+
var stream = new MemoryStream();
53+
54+
// Set using Map instead of Array to serialize complex object. See Sample03 for details.
55+
SerializationContext.Default.SerializationMethod = SerializationMethod.Map;
56+
57+
// 1. Create serializer instance.
58+
var serializer = SerializationContext.Default.GetSerializer<PhotoEntry>();
59+
60+
// 2. Serialize object to the specified stream.
61+
serializer.Pack( stream, targetObject );
62+
63+
// Set position to head of the stream to demonstrate deserialization.
64+
stream.Position = 0;
65+
66+
// 3. Unpack MessagePackObject to get raw representation.
67+
var rawObject = Unpacking.UnpackObject( stream );
68+
// You can read MPO tree via Unpacker
69+
// var unpacker = Unpacker.Create( stream );
70+
71+
// Check its type
72+
Debug.WriteLine( "Is array? {0}", rawObject.IsArray ); // IsList is alias
73+
Debug.WriteLine( "Is map? {0}", rawObject.IsMap ); // IsDictionary is alias
74+
Debug.WriteLine( "Type: {0}", rawObject.UnderlyingType );
75+
76+
// Gets serialized fields.
77+
// Note: When the object was serialized as array instead of map, use index instead.
78+
var asDictionary = rawObject.AsDictionary();
79+
Debug.WriteLine( "Id : {0}({1})", asDictionary[ "Id" ], asDictionary[ "Id" ].UnderlyingType );
80+
// String is encoded as utf-8 by default.
81+
Debug.WriteLine( "Title : {0}({1})", asDictionary[ "Title" ], asDictionary[ "Title" ].UnderlyingType );
82+
// Non-primitive is serialized as complex type or encoded primitive type.
83+
// DateTimeOffset is encoded as array[2]{ticks,offset}
84+
Debug.WriteLine( "Date : {0}({1})", asDictionary[ "Date" ], asDictionary[ "Date" ].UnderlyingType );
85+
// byte[] is byte[], as you know.
86+
Debug.WriteLine( "Image : {0}({1})", asDictionary[ "Image" ], asDictionary[ "Image" ].UnderlyingType );
87+
}
88+
}
89+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#region -- License Terms --
2+
//
3+
// MessagePack for CLI
4+
//
5+
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
6+
//
7+
// Licensed under the Apache License, Version 2.0 (the "License");
8+
// you may not use this file except in compliance with the License.
9+
// You may obtain a copy of the License at
10+
//
11+
// http://www.apache.org/licenses/LICENSE-2.0
12+
//
13+
// Unless required by applicable law or agreed to in writing, software
14+
// distributed under the License is distributed on an "AS IS" BASIS,
15+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
// See the License for the specific language governing permissions and
17+
// limitations under the License.
18+
//
19+
#endregion -- License Terms --
20+
21+
using System;
22+
using System.Collections.Generic;
23+
using System.Collections.ObjectModel;
24+
25+
using MsgPack;
26+
using MsgPack.Serialization;
27+
using NUnit.Framework; // For running checking
28+
29+
namespace Samples
30+
{
31+
/// <summary>
32+
/// A sample code to describe SerializationContext usage.
33+
/// </summary>
34+
[TestFixture]
35+
public class SerializationContextAndOptionsSample
36+
{
37+
[Test]
38+
public void CustomizeSerializeBehavior()
39+
{
40+
// 1. To take advantage of SerializationContext, you should create own context to isolate others.
41+
// Note that SerializationContext is thread safe.
42+
// As you imagine, you can change 'default' settings by modifying properties of SerializationContext.Default.
43+
var context = new SerializationContext();
44+
45+
// 2. Set options.
46+
47+
// 2-1. SerializationMethod: it changes comple type serialization method as array or map.
48+
// Array(default): Space and time efficient, but depends on member declaration order so less version torrelant.
49+
// Map : Less effitient, but more version torrelant (and easy to traverse as MesasgePackObject).
50+
context.SerializationMethod = SerializationMethod.Map;
51+
52+
// 2-2. EnumSerializationMethod: it changes enum serialization as their name or underlying value.
53+
// ByName(default): More version torrelant and interoperable, and backward compatible prior to 0.5 of MsgPack for CLI.
54+
// ByUnderlyingValue: More efficient, but you should manage their underlying value and specify precise data contract between counterpart systems.
55+
context.EnumSerializationMethod = EnumSerializationMethod.ByUnderlyingValue;
56+
57+
// 2-3. If CompatibilityOptions.OneBoundDataMemberOrder is set, the origin DataMemberAttribute.Order becomes 1.
58+
// It is compatibility options 1 base library like Proto-buf.NET.
59+
context.CompatibilityOptions.OneBoundDataMemberOrder = true;
60+
61+
// 2-4. The CompatibilityOptions.PackerCompatibilityOptions control packer compatibility level.
62+
// If you want to communicate with the library which only supports legacy message pack format spec, use PackerCompatibilityOptions.Classic flag set (default).
63+
// If you want to utilize full feature including tiny string type, binary type, extended type, specify PackerCompatibilityOptions.None explicitly.
64+
context.CompatibilityOptions.PackerCompatibilityOptions = PackerCompatibilityOptions.None;
65+
66+
// 2-5. You can tweak default concrete collection types for collection interfaces including IEnumerable<T>, IList, etc.
67+
context.DefaultCollectionTypes.Unregister( typeof( IList<> ) );
68+
context.DefaultCollectionTypes.Register( typeof( IList<> ), typeof( Collection<> ) );
69+
70+
// 3. Get a serializer instance with customized settings.
71+
var serializer = context.GetSerializer<PhotoEntry>( context );
72+
73+
// Following instructions are omitted... see sample 01.
74+
}
75+
}
76+
}
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#region -- License Terms --
2+
//
3+
// MessagePack for CLI
4+
//
5+
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
6+
//
7+
// Licensed under the Apache License, Version 2.0 (the "License");
8+
// you may not use this file except in compliance with the License.
9+
// You may obtain a copy of the License at
10+
//
11+
// http://www.apache.org/licenses/LICENSE-2.0
12+
//
13+
// Unless required by applicable law or agreed to in writing, software
14+
// distributed under the License is distributed on an "AS IS" BASIS,
15+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
// See the License for the specific language governing permissions and
17+
// limitations under the License.
18+
//
19+
#endregion -- License Terms --
20+
21+
using System;
22+
using System.Diagnostics;
23+
using System.IO;
24+
25+
using MsgPack;
26+
using MsgPack.Serialization;
27+
using NUnit.Framework; // For running checking
28+
29+
namespace Samples
30+
{
31+
/// <summary>
32+
/// A sample code to describe SerializationContext usage.
33+
/// </summary>
34+
[TestFixture]
35+
public class CustomSerializerSample
36+
{
37+
[Test]
38+
public void RegisterAndUseCustomSerializer()
39+
{
40+
var stream = new MemoryStream();
41+
42+
// 1. To take advantage of SerializationContext, you should create own context to isolate others.
43+
// Note that SerializationContext is thread safe.
44+
// As you imagine, you can change 'default' settings by modifying properties of SerializationContext.Default.
45+
var context = new SerializationContext();
46+
47+
// 2. Register custom serializers.
48+
context.Serializers.RegisterOverride( new NetUtcDateTimeSerializer( context ) );
49+
50+
// 3. Get a serializer instance with customized settings.
51+
var serializer = context.GetSerializer<DateTime>( context );
52+
53+
// Test it.
54+
var dateTime = DateTime.Now;
55+
serializer.Pack( stream, dateTime );
56+
stream.Position = 0;
57+
var deserialized = serializer.Unpack( stream );
58+
59+
Debug.WriteLine( "Ticks are same? {0}", dateTime.Ticks == deserialized.Ticks );
60+
}
61+
}
62+
63+
/// <summary>
64+
/// A custom serializer sample: Serialize <see cref="System.DateTime"/> as UTC.
65+
/// </summary>
66+
public class NetUtcDateTimeSerializer : MessagePackSerializer<DateTime>
67+
{
68+
// CAUTION: You MUST implement your serializer thread safe (usually, you can and you should implement serializer as immutable.)
69+
70+
// Note: If your type has complex type fields, you want to add read only fields in the custom serializer for each fields complex types.
71+
// Note: It is good start point to use mpgen.exe utility to get Code-DOM generated serializer to understand custom serializer.
72+
// Notice that the generated serializer is bit complex because of poor expressiveness of CodeDOM tree and built-in nil-handling (described in sample 06.)
73+
74+
// ownerContext should be match the context to be registered.
75+
public NetUtcDateTimeSerializer( SerializationContext ownerContext ) : base( ownerContext ) { }
76+
77+
protected override void PackToCore( Packer packer, DateTime objectTree )
78+
{
79+
packer.Pack( objectTree.Ticks );
80+
}
81+
82+
protected override DateTime UnpackFromCore( Unpacker unpacker )
83+
{
84+
// Note that unapcker should be in head of the complex type.
85+
return new DateTime( unpacker.LastReadData.AsInt64() );
86+
87+
// Note: if you deserialize following members, call Read() as following:
88+
// if ( unpacker.Read() )
89+
// {
90+
// throw SerializationExceptions.NewUnexpectedEndOfStream();
91+
// }
92+
// ...Read next field...
93+
}
94+
}
95+
}

0 commit comments

Comments
 (0)