New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding a sample on how to use the custom serializer. #560
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
Microsoft.Azure.Cosmos.Samples/CodeSamples/CustomSerializer/CustomSerializer.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>netcoreapp2.1</TargetFramework> | ||
<LangVersion>latest</LangVersion> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.0.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" /> | ||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" /> | ||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" /> | ||
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" /> | ||
</ItemGroup> | ||
<ItemGroup> | ||
<None Include="..\AppSettings.json"> | ||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> | ||
</None> | ||
</ItemGroup> | ||
</Project> |
93 changes: 93 additions & 0 deletions
93
Microsoft.Azure.Cosmos.Samples/CodeSamples/CustomSerializer/CustomSerializerProgram.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
namespace Cosmos.Samples.Shared | ||
{ | ||
using System; | ||
using System.Threading.Tasks; | ||
using Microsoft.Azure.Cosmos; | ||
using Microsoft.Extensions.Configuration; | ||
using Newtonsoft.Json.Linq; | ||
|
||
class CustomSerializerProgram | ||
{ | ||
// Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute | ||
// <Main> | ||
public static async Task Main(string[] args) | ||
{ | ||
try | ||
{ | ||
IConfigurationRoot configuration = new ConfigurationBuilder() | ||
.AddJsonFile("appSettings.json") | ||
.Build(); | ||
|
||
string endpoint = configuration["EndPointUrl"]; | ||
if (string.IsNullOrEmpty(endpoint)) | ||
{ | ||
throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json"); | ||
} | ||
|
||
string authKey = configuration["AuthorizationKey"]; | ||
if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key")) | ||
{ | ||
throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json"); | ||
} | ||
|
||
//Read the Cosmos endpointUrl and authorisationKeys from configuration | ||
//These values are available from the Azure Management Portal on the Cosmos Account Blade under "Keys" | ||
//NB > Keep these values in a safe & secure location. Together they provide Administrative access to your Cosmos account | ||
CustomSerializerProgram program = new CustomSerializerProgram(); | ||
await program.RunDemo(endpoint, authKey); | ||
|
||
} | ||
catch (CosmosException cre) | ||
{ | ||
Console.WriteLine(cre.ToString()); | ||
} | ||
catch (Exception e) | ||
{ | ||
Exception baseException = e.GetBaseException(); | ||
Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message); | ||
} | ||
finally | ||
{ | ||
Console.WriteLine("End of demo, press any key to exit."); | ||
Console.ReadKey(); | ||
} | ||
} | ||
|
||
public async Task RunDemo(string endpoint, string key) | ||
{ | ||
CosmosClientOptions options = new CosmosClientOptions() | ||
{ | ||
Serializer = new JsonSerializerIgnoreNull(), | ||
}; | ||
|
||
using (CosmosClient client = new CosmosClient(endpoint, key, options)) | ||
{ | ||
Database db = null; | ||
try | ||
{ | ||
db = await client.CreateDatabaseIfNotExistsAsync("CustomSerializerDemo"); | ||
Container container = await db.CreateContainerIfNotExistsAsync( | ||
id: "ContainerDemo", | ||
partitionKeyPath: "/pk"); | ||
|
||
dynamic testItem = new { id = "MyTestItemWithIgnoreNull" + Guid.NewGuid(), pk = "ItExists", description = (string)null }; | ||
ItemResponse<dynamic> itemResponse = await container.CreateItemAsync<dynamic>(testItem, new PartitionKey(testItem.pk)); | ||
dynamic responseObject = itemResponse.Resource; | ||
if (responseObject["description"] != null) | ||
{ | ||
throw new InvalidOperationException("Description was not ignored"); | ||
} | ||
|
||
Console.WriteLine($"Item created: {responseObject}"); | ||
} | ||
finally | ||
{ | ||
if(db != null) | ||
{ | ||
await db.DeleteAsync(); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
58 changes: 58 additions & 0 deletions
58
Microsoft.Azure.Cosmos.Samples/CodeSamples/CustomSerializer/JsonSerializerIgnoreNull.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
namespace Cosmos.Samples.Shared | ||
{ | ||
using System; | ||
using System.IO; | ||
using System.Text; | ||
using Microsoft.Azure.Cosmos; | ||
using Newtonsoft.Json; | ||
|
||
class JsonSerializerIgnoreNull : CosmosSerializer | ||
{ | ||
private static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true); | ||
private static readonly JsonSerializer Serializer = new JsonSerializer() | ||
{ | ||
NullValueHandling = NullValueHandling.Ignore | ||
}; | ||
|
||
public override T FromStream<T>(Stream stream) | ||
{ | ||
using (stream) | ||
{ | ||
if (typeof(Stream).IsAssignableFrom(typeof(T))) | ||
{ | ||
return (T)(object)(stream); | ||
} | ||
|
||
using (StreamReader sr = new StreamReader(stream)) | ||
{ | ||
using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) | ||
{ | ||
return JsonSerializerIgnoreNull.Serializer.Deserialize<T>(jsonTextReader); | ||
} | ||
} | ||
} | ||
} | ||
|
||
public override Stream ToStream<T>(T input) | ||
{ | ||
MemoryStream streamPayload = new MemoryStream(); | ||
using (StreamWriter streamWriter = new StreamWriter( | ||
streamPayload, | ||
encoding: JsonSerializerIgnoreNull.DefaultEncoding, | ||
bufferSize: 1024, | ||
leaveOpen: true)) | ||
{ | ||
using (JsonWriter writer = new JsonTextWriter(streamWriter)) | ||
{ | ||
writer.Formatting = Newtonsoft.Json.Formatting.None; | ||
JsonSerializerIgnoreNull.Serializer.Serialize(writer, input); | ||
writer.Flush(); | ||
streamWriter.Flush(); | ||
} | ||
} | ||
|
||
streamPayload.Position = 0; | ||
return streamPayload; | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One more option is to make it generic to take JsonSerializerSettings and we can use it as reference for V2 -> V3 migration. Thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I created a separate issue to track that. #551
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
JSON.net implementation as public contract will force its dependency even in future when implementation moved to .NET core JSON parser.