GithubHelp home page GithubHelp logo

azure / azure-cosmos-dotnet-v3 Goto Github PK

View Code? Open in Web Editor NEW
714.0 68.0 471.0 152.01 MB

.NET SDK for Azure Cosmos DB for the core SQL API

License: MIT License

C# 82.89% JavaScript 0.07% Smalltalk 0.03% PowerShell 0.19% Shell 0.05% Python 0.01% Jupyter Notebook 16.72% ANTLR 0.05% Dockerfile 0.01%

azure-cosmos-dotnet-v3's Introduction

NuGet NuGet Prerelease

Microsoft Azure Cosmos DB .NET SDK Version 3

This client library enables client applications to connect to Azure Cosmos DB for NoSQL. Azure Cosmos DB is a globally distributed, multi-model database service. For more information, refer to https://azure.microsoft.com/services/cosmos-db/.

CosmosClient client = new CosmosClient("https://mycosmosaccount.documents.azure.com:443/", "mysupersecretkey");
Database database = await client.CreateDatabaseIfNotExistsAsync("MyDatabaseName");
Container container = await database.CreateContainerIfNotExistsAsync(
    "MyContainerName",
    "/partitionKeyPath",
    400);

// Create an item
dynamic testItem = new { id = "MyTestItemId", partitionKeyPath = "MyTestPkValue", details = "it's working", status = "done" };
ItemResponse<dynamic> createResponse = await container.CreateItemAsync(testItem);

// Query for an item
using (FeedIterator<dynamic> feedIterator = container.GetItemQueryIterator<dynamic>(
    "select * from T where T.status = 'done'"))
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<dynamic> response = await feedIterator.ReadNextAsync();
        foreach (var item in response)
        {
            Console.WriteLine(item);
        }
    }
}

Install via Nuget.org

Install-Package Microsoft.Azure.Cosmos

For available versions, see SDK versioning.

Useful links

Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct.

Resources:

Contributing

For details on contributing to this repository, see the contributing guide.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

azure-cosmos-dotnet-v3's People

Contributors

abhijitpai avatar adityasa avatar akotalwar avatar anujtoshniwal avatar asketagarwal avatar ausfeldt avatar bchong95 avatar deparash avatar dependabot[bot] avatar ealsur avatar fabianmeiswinkel avatar fnarenji avatar imanvt avatar j82w avatar kirankumarkolli avatar kr-santosh avatar kundadebdatta avatar leminh98 avatar maya-painter avatar nalutripician avatar neildsh avatar philipthomas-msft avatar pramodvalavala-msft avatar rakkuma avatar rinatmini avatar saurabhsharma-msft avatar schintamicrosoft avatar simplynaveen20 avatar snehagunda avatar sourabh1007 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-cosmos-dotnet-v3's Issues

Request charge information missing for item queries?

Is your feature request related to a problem? Please describe.

Yes, just being able to get a sense of request charges for different queries.

Describe the solution you'd like

The CosmosQueryResponse<T> type does not inherit from CosmosResponse<T>, so it is missing details like request charge. This is crucial for logging and understanding query costs.

Describe alternatives you've considered

I know of none.

Possible imporvements by comparison to a homemade API

Hi Team,
I come to you because I have been struggling with similar issues around the object model of the old sdk when I first started using documentdb a year ago and I made a homemade api that resembles in some aspects the object model you now have. I said to myself I can now drop my api after reviewing this 3.0 preview, but I think there are a few things you might be interested to include in your sdk (I did not yet fully looked at the preview sdk, though).

  1. One of the things is to consider that a cosmodb account corresponds to exactly one client and users can have several several accounts. The idea is, in the same way as cosmosclient has many databases and you locate a database with databases["id"], you would have CosmosContext that includes all CosmosClient (i.e. accounts) with indexing to retrieve them. It was handy for me already to test localhost and on azure and there are compliance reasons why you would need more than one cosmos account. Above all it reflects best what the structure of cosmosdb is:

-User has many accounts, each account has many databases, each database has many containers, each container has many items

  1. As we had situations where we want to make sure that certain poco classes belong to certain collections and should be forbidden to be accidentally persisted on others, I introduced a registration of each poco that is entended to be stored in documentdb and the program which will throw if a given poco is not allowed. This entity check can be circumvented by a Boolean. However, this is perhaps more along the lines of a details implementation.

  2. Add DI injection for .Net Core, so far I am registering an application context as a singleton following the recommendation of documentdb (DocumentClient.OpenAsync). And do the same for uwp Xamarin etc with lazy loading of a singleton instance.

For .Net Core this would give the following fairly friendly flow

Startup.cs

services.AddGlobalDocumentDbContext<ApplicationGlobalDocumentDbContext>();

ApplicationGlobalDocumentDbContext which mimics EF strategy

public sealed class ApplicationGlobalDocumentDbContext : GlobalDocumentDbContext
{
           protected override void OnConfiguring(GlobalDocumentDbContextOptionsBuilder optionsBuilder)
{
           var client1 = new DocumentClient("localhost".ToDocumentUri(), CosmosDbConstants.emulatorPrimaryKey,
           new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Https });
           var client2 = new DocumentClient("account2".ToDocumentUri(), CosmosDbConstants.emulatorPrimaryKey);

           optionsBuilder
           .AddClient(client1)
           .AllowEntity<Item>("dbperson", "col2", "col1")
           .AllowEntity<Item>("dbperson", "colperson")
           .AllowEntity<A<Item, Person>>("dbperson", "colperson")
           .AllowEntity<Search>("dbsearch", "colsearch")
           .AllowEntity<Person>("dbperson", "colperson");

           optionsBuilder
               .AddClient(client2)
               .AllowEntity<Item>("dbitem", "col2", "col1");
}

       public IDocumentDbRepository<Item> Items { get; set; } = new DocumentDbRepository<Item>();
       public IDocumentDbRepository<Person> People { get; set; } = new DocumentDbRepository<Person>();
       public IDocumentDbRepository<A<Item, Person>> AItemPeople { get; set; } = new DocumentDbRepository<A<Item, Person>>();
       public IDocumentDbRepository<Search> Searches { get; set; } = new DocumentDbRepository<Search>();

}

DI on a controller

public class HomeController : Controller
{
            private readonly ApplicationGlobalDocumentDbContext _globalDocumentDbContext;

      public HomeController(ApplicationGlobalDocumentDbContext globalDocumentDbContext)
      {
            _globalDocumentDbContext = globalDocumentDbContext;
      }

      public async Task<IActionResult>Index()
      {
                var myitem = new Item { Name = "Item's name", FirstName = "Item's FirstName", ItemProperty = "Item Property" };
                var myperson = new Person { FirstName = "Person's FirstName", LastName = "Person's LastName" };

                //Retrieve the document collection objects (you would normally define these outside of a view method)
                var documentCollection = _globalDocumentDbContext["localhost", "dbs/dbperson/colls/colperson"];
                var searchCollection = _globalDocumentDbContext["localhost", "dbs/dbsearch/colls/colsearch"];

                //Create an item in documentdb and return the result projected onto a ViewModel
                var itemViewModel = await _globalDocumentDbContext.Items.AddAsync<ViewModel>(documentCollection, myitem);

                //Create a person in documentdb and return the person (no casting)
                var person = await _globalDocumentDbContext.People.AddAsync(documentCollection, myperson);

                //Update person and return a ViewModel. A replace is typically followed by a FindById (not shown)
                person.FirstName = "updated person FirstName";
                var personVieModel = await _globalDocumentDbContext.People.ReplaceAsync<ViewModel>(documentCollection, person);

                //Find
                var searchString = "irst";

                var feedOptions = new FeedOptions { MaxItemCount = -1 };

                Expression<Func<Item, bool>> expression = x => x.FirstName.ToLower().Contains($"{searchString}".ToLower());

                //find at most numOfItems = 17 items and project to view model (use x=>x in the second lambda for a one to one mapping)
                var numOfItems = 17;
                var find = await _globalDocumentDbContext.Items
                    .FindAsync(numOfItems, expression,
                    x => new ViewModel { Id = x.Id, Type = x.Type, Name = x.Name }, documentCollection, feedOptions);

                //Find on page 2, pagesize = 17 and project to view model
                var findOnRank = await _globalDocumentDbContext.Items
                    .FindOnPagedAsync(2, 17, expression,
                    x => new ViewModel { Id = x.Id, Type = x.Type, Name = x.Name }, documentCollection, feedOptions);

                //Operate on a different collection
                var search = await _globalDocumentDbContext.Searches.FindByIdAsync(searchCollection, "searchId");
                return new JsonResult(new
                {
                    //Print all collections you have registered
                    collections = _globalDocumentDbContext.GetDocumentCollections("localhost"),

                    a = findOnRank,
                    b = find
                });

I will have to rework this whole api since, from my understanding, I do not need anymore the uri's, which is great, and I would gladly drop it out to use only the new sdk, so I wonder if you would be interested in implementing some of these features/concepts I will be happy to help of course, hence my post.

Should CosmosResponse<T> have a non-generic base class?

Is your feature request related to a problem? Please describe.

Yes, generalized logging of Cosmos responses is made far more convoluted by key information being defined inside a generic class unnecessarily, rather than extracting that information to a non-generic base class. For my actual scenario, see this stackoverflow question.

Describe the solution you'd like

I think CosmosResponse<T> should inherit from a CosmosResponse base class, which contains all properties that don't rely on T: Headers, StatusCode, RequestCharge, ActivityId, and ETag. All of these things are useful to get at in a generalized way, and it would be far easier to do that if you didn't have to fill in T.

Describe alternatives you've considered

The workaround I have right now is shown in my stackoverflow question. It's messy and will perform far worse than if I just had a non-generic base class I could use instead.

Avoid Custom serialzier on SDK OOB types (including spatial types)

SDK uses custom given serializer for all types serialization including OOB types in SDK.
In some cases custom serialzier might result in un-intended behaviors

Broadly there are below types in SDK, which are ideal candidates

  1. REST types (Database, …)
  2. Spatial types

Repro:
Below settings on V2 SDK might result in spatial types serialization breaking the expectation.

JsonSerializerSettings jsonSerializerSettings =
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
Formatting = Formatting.None,
TypeNameHandling = TypeNameHandling.Auto,
};

EF team feedback on various APIs

The following improvements were identified while porting the EF Core provider to the Cosmos SDK version 3.0.0.1-preview.

cc @AndriySvyryd @ajcvickers @kirillg

  • Add a constructor to PartitionKeyDefinition that accepts an IEnumerable of paths
  • Remove the parameterless constructor from CosmosContainerSettings since the id and partition keys are required
  • Add a way to get the query and parameters from CosmosSqlQueryDefinition, this would be useful for logging
  • There doesn’t seem to be an advantage to have CosmosResponse.Resource be strongly typed, as the generic argument cannot always be inferred and frequently needs to be specified explicitly. Returning it as object makes using the methods like DeleteItemAsync<>() simpler as they won’t need the generic argument.
  • It might be better to rename the CreateItemQuery<>() overloads that don’t take a partition key as they could be invoked unintentionally if the partition key is an int. Or move maxConcurrency to requestOptions
  • Improve documentation for the partitionKey parameter in methods like CreateItemAsync<>(). PartitionKey doesn’t have any documentation. And a PartitionKey instance doesn’t seem to be accepted, consider changing the type to string or separating into overloads
  • Allow to provide a custom IDocumentClientRetryPolicy or provide a built in way of using exponential backoff.
  • (Not really API feedback, but a possible way to improve the codebase) Align directory structure of the code with the namespaces and apply other established C# coding conventions - https://docs.microsoft.com/dotnet/csharp/programming-guide/inside-a-program/coding-conventions

AsItemQuery

Hello,

One of the examples has a note mentioning about using "AsItemQuery", if we do not want to enumerate through all the results. However I do not see any such method on the CreateItemQuery method or seem to figure out a way to do it. Any help is greatly appreciated.

Thanks,
Ajay

Sample v3 Solution missing resources

We are continuously addressing and improving the SDK, if possible, make sure the problem persist in the latest SDK version.

Describe the bug
After doing a git clone, there are various projects that are "unavailable" and the solution is unable to run because of these missing project.

The missing projects are:

  1. ContainerManagement
  2. DatabaseManagement
  3. ItemManagement
  4. Microsoft.Azure.Cosmos.Direct
  5. Shared

image

To Reproduce
In a blank folder, git clone https://github.com/Azure/azure-cosmos-dotnet-v3 master branch and then go to the samples folder and open the SLN file Cosmos.Samples. Run the file and get errors. Also notice in the solution explorer that there are projects missing.

Expected behavior
Open the solution file, restore nuget packages, run the samples

Actual behavior
Error message about missing references.

Environment summary
SDK Version: Microsoft.Azure.Cosmos 3.0.0.1-preview1
Windows 10 Pro

Why is index utilization 0.00 %?

Hi,

Can you please help me figure out why index utilization is 0.00 %?

I'm including this path in the indexing policy:

{
	"path": "/receivedDateTime/?",
	"indexes": [
		{
			"kind": "Range",
			"dataType": "Number",
			"precision": -1
		},
		{
			"kind": "Hash",
			"dataType": "String",
			"precision": 3
		}
	]
}

and this is an example of my documents:

{
    "id": "",
    "userId": "XYZ",
    ...
    "receivedDateTime": 635903262620000000,
    ...
}

When I run the following query I get zero index utilization.
Notes:

  1. It does not happen with any other property/path that I included in the indexing policy
  2. UserId is the partition key
_client.CreateDocumentQuery<Message>(UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId),
                    new FeedOptions
                    {
                        PopulateQueryMetrics = true,
                        MaxItemCount = maxItemCount
                    })
                .Where(item => item.UserId == Guid.Parse("XYZ"))
                .OrderBy(m => m.ReceivedDateTime)
                .AsDocumentQuery();

image

On the other hand if I add item.ReceivedDateTime >= 0 to the where clause I get 98.02 % of index utilization even when item.ReceivedDateTime >= 0 is true for all the documents.

_client.CreateDocumentQuery<Message>(UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId),
                    new FeedOptions
                    {
                        PopulateQueryMetrics = true,
                        MaxItemCount = maxItemCount
                    })
                .Where(item => item.UserId == Guid.Parse("XYZ") && item.ReceivedDateTime >= 0)
                .OrderBy(m => m.ReceivedDateTime)
                .AsDocumentQuery();

image

Thank you

Stop requiring partition key parameter in the typed create, replace, upsert methods, infer from the data

When porting over to the new SDK from DocumentDB I came across needing to specify a Partition Key on an action (create, upsert, etc.) with a CosmosResource. However, the Partition Key Path is also specified on creating a Container.

Shouldn’t the Partition Key automatically be handled by the Container instead of having to specify it on every Resource action? Or will there now be a Partition Key property on the Resource if it doesn’t have a property that follows the Path specified on the Container?

I’m using the Azure.Documents.Cosmos package (not Azure.Documents.Cosmos.Table).

Thanks!

No DocumentQuery Linq to SQL evaluation

As far as I can see there is no equivalent of CreateDocumentQuery that supports a LINQ expression path which is converted to SQL behind the scenes but I can see that the evaluator is still in the code.

Are there plans to support this feature?

Next preview release time frame?

Looks like there have been some updates to the source code here. Any hints as to the time frame for the next preview NuGet package?

CosmosClient Unit Test Constructor marked internal

We are continuously addressing and improving the SDK, if possible, make sure the problem persist in the latest SDK version.

Describe the bug
There is a constructor on CosmosClient that takes a DocumentClient for mocking purposes but it is marked internal. This needs to be public so that it can be used for mocking.

To Reproduce
Open the source code and navigate to Microsoft.Azure.Cosmos/Resource/Database/CosmosDatabase.cs and note that there is a constructor marked internal when it should not be as it is a stated intent to make mocking easy of v3.

Expected behavior
Not have the CosmosClient(config,documentclient) constructor marked as internal

Actual behavior
CosmosClient(config,documentclient) is marked internal and unusable

Environment summary
SDK Version: Microsoft.Azure.Cosmos v3.0.0.1-preview1
OS Version: Windows 10

CosmosQueryRequestOptions excludes old FeedOptions

Is your feature request related to a problem? Please describe.
Not sure if this is a regression bug or feature request but the PopulateQueryMetrics feed option is not exposed as a member of the CosmosQueryRequestOptions class.

In fact there are a number of feed options which have been left out between the current client and this one. Have these options been left off for a reason or are they configurable else where?

Comparison between FeedOptions & CosmosQueryRequestOptions

Property Status
ConsistencyLevel Supported
EnableCrossPartitionQuery Internally Set (no public access)
EnableLowPrecisionOrderBy Supported
EnableScanInQuery Supported
JsonSerializerSettings Not Supported
MaxBufferedItemCount Supported
MaxDegreeOfParallelism Supported (called MaxConcurrency and no longer request option)
MaxItemCount Supported (no longer request option)
PartitionKey Supported
PartitionKeyRangeId Not Supported
PopulateQueryMetrics Not Supported
RequestContinuation Not Supported
ResponseContinuationTokenLimitInKb Supported
SessionToken Supported

Describe the solution you'd like
Are there any objections to adding PopulateQueryMetrics as an option to CosmosQueryRequestOptions? I've tested and confirmed that CosmosQueryResponse<T> includes the metrics if set. This setting is really useful for performance tuning etc.

Don't use exceptions for flow control

On every cross partition query this exception is thrown and caught. This makes debugging much slower and probably degrades production performance.

Microsoft.Azure.Cosmos.Internal.DocumentClientException
HResult=0x80131500
Message=The provided cross partition query can not be directly served by the gateway. This is a first chance (internal) exception that all newer clients will know how to handle gracefully. This exception is traced, but unless you see it bubble up as an exception (which only happens on older SDK clients), then you can safely ignore this message.
ActivityId: 17f2c157-c4c0-4ca1-9da2-8b3e42af20c5, Microsoft.Azure.Documents.Common/2.1.0.0
Source=Microsoft.Azure.Cosmos.Client
StackTrace:
at Microsoft.Azure.Cosmos.ClientExtensions.d__1.MoveNext()

Functions v2 sample

Can you please publish Azure Functions V2 Sample showing the correct way to use it?

CosmosConfiguration should be immutable

Describe the bug
The CosmosConfiguration that is passed to the CosmosClient constructor can be updated after the CosmosClient creation. The CosmosClient does not handle any updates to the CosmosConfiguration. This can cause unexpected behavior, and lead to confusion.

To Reproduce

  1. Create a CosmosClient with a CosmosConfiguration.
  2. Add a new handler to the CosmosConfiguration.
  3. The new handler will not be used in any of the calls. A new CosmosClient must be created in order for it to be added.
CosmosConfiguration config = new CosmosConfiguration("accountEndPoint", "key");
CosmosClient client = new CosmosClient(config);
//client will not use the added handler
config.AddCustomHandlers(logHandler);
//client2 will use the new handler. Both clients are pointing to the same configuration instance.
CosmosClient client2 = new CosmosClient(config);

Expected behavior
The current proposal to fix this issue is to add a CosmosClient builder.

  1. The builder will create each instance of CosmosClient with it's own immutable copy of the CosmosConfiguration. This will prevent any modification after the CosmosClient is created.
  2. Remove public access to the CosmosClient constructor that takes a CosmosConfiguration. The builder will create the CosmosConfiguration and the client. The other basic constructor on the CosmosClient will remain to prevent unnecessary complexity for simple projects.
CosmosClientBuilder builder = new CosmosClientBuilder("accountEndPoint", "key");
CosmosClient client = builder.Build();

//Only client2 will use the added handler
builder.AddCustomHandlers(logHandler);
CosmosClient client2 = builder.Build();

System.AggregateException

We are continuously addressing and improving the SDK, if possible, make sure the problem persist in the latest SDK version.

Describe the bug
I described the bug in a blog post: A strange bug in Azure Cosmos DB SQL API account (SDK Version 3 Preview)

To Reproduce
Steps to reproduce the behavior. If you can include code snippets or links to repositories containing a repro of the issue that can help us in detecting the scenario it would speed up the resolution.

Expected behavior
A clear and concise description of what you expected to happen.

Actual behavior
Error: System.AggregateException: One or more errors occurred. (Exception has been thrown by the target of an invocation.) ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(Boolean overflow, String overflowResourceKey)
at System.Double.Parse(String s)
at Microsoft.Azure.Cosmos.CosmosResponseMessageHeaders.set__requestCharge(String value)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
at Microsoft.Azure.Cosmos.CosmosResponseMessageHeaders.<>c__DisplayClass43_0.b__3(String value)
at Microsoft.Azure.Cosmos.CosmosCustomHeader.Set(String value)
at Microsoft.Azure.Cosmos.CosmosMessageHeadersInternal.Add(String headerName, String value)
at Microsoft.Azure.Cosmos.CosmosMessageHeadersBase.Add(String headerName, String value)
at Microsoft.Azure.Cosmos.Extensions.ToCosmosResponseMessage(DocumentServiceResponse response, CosmosRequestMessage requestMessage)
at Microsoft.Azure.Cosmos.Handlers.TransportHandler.SendAsync(CosmosRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.ExecuteHttpRequestAsync(Func1 callbackMethod, Func3 callShouldRetry, Func3 callShouldRetryException, CancellationToken cancellationToken) at Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.SendAsync(CosmosRequestMessage request, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at Microsoft.Azure.Cosmos.ExecUtils.<>c__DisplayClass3_01.b__0(Task1 task)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location where exception was thrown --- at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location where exception was thrown --- at CosmosGettingStartedDotnetCoreTutorial.Program.ReplaceFamilyItem() in D:\CosmosGettingStartedDotnetCoreTutorial\CosmosGettingStartedDotnetCoreTutorial\Program.cs:line 210 at CosmosGettingStartedDotnetCoreTutorial.Program.GetStartedDemoAsync() in D:\CosmosGettingStartedDotnetCoreTutorial\CosmosGettingStartedDotnetCoreTutorial\Program.cs:line 75 at CosmosGettingStartedDotnetCoreTutorial.Program.Main(String[] args) in D:\CosmosGettingStartedDotnetCoreTutorial\CosmosGettingStartedDotnetCoreTutorial\Program.cs:line 30 ---> (Inner Exception #0) System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.FormatException: Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(Boolean overflow, String overflowResourceKey) at System.Double.Parse(String s) at Microsoft.Azure.Cosmos.CosmosResponseMessageHeaders.set__requestCharge(String value) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index) at Microsoft.Azure.Cosmos.CosmosResponseMessageHeaders.<>c__DisplayClass43_0.b__3(String value) at Microsoft.Azure.Cosmos.CosmosCustomHeader.Set(String value) at Microsoft.Azure.Cosmos.CosmosMessageHeadersInternal.Add(String headerName, String value) at Microsoft.Azure.Cosmos.CosmosMessageHeadersBase.Add(String headerName, String value) at Microsoft.Azure.Cosmos.Extensions.ToCosmosResponseMessage(DocumentServiceResponse response, CosmosRequestMessage requestMessage) at Microsoft.Azure.Cosmos.Handlers.TransportHandler.SendAsync(CosmosRequestMessage request, CancellationToken cancellationToken) at Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.ExecuteHttpRequestAsync(Func1 callbackMethod, Func3 callShouldRetry, Func3 callShouldRetryException, CancellationToken cancellationToken)
at Microsoft.Azure.Cosmos.Handlers.AbstractRetryHandler.SendAsync(CosmosRequestMessage request, CancellationToken cancellationToken)<---

End of demo, press any key to exit

Environment summary
SDK Version: 3.0.0.1-preview
OS Version (e.g. Windows, Linux, MacOSX): Windows 10 Version 809

Additional context
Add any other context about the problem here (for example, complete stack traces or logs).

Value cannot be null error: Parameter name: key

What does the exception "Value cannot be null error: Parameter name: key" mean? Which value was left empty? I have added a PartitionPath key to the collection.

Just curious.
Marcel


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Allow a custom HttpMessageHandler to support overriding the verification of Self-Signed SSL certificates.

With the V2 client now using the latest framework it is possible to override the HttpMessageHandler and override self-signed certificate checking.

	var handler = new HttpClientHandler();
	handler.ClientCertificateOptions = ClientCertificateOption.Manual;
	handler.ServerCertificateCustomValidationCallback += DangerousAcceptAnyServerCertificateValidator;

	_client = new DocumentClient(new Uri(_documentDbOptions.Endpoint), _documentDbOptions.Key, handler);

However with the V3 client, there is no ability to do this.
Can we look for a suitable way to do this?

Self-Signed certification verification overrides are required when running on Linux clients that wish to connect to the emulator. Despite all of the good work that has been done with the emulator such as allowing you to specify the alternative subject names for the self-signed certificate and export it, there are still limitations. I've found that the Linux implementation of .NET core that uses cURL/OpenSSL will still error with a self-signed certificate, even if you install it into the ca-certificates store. (Windows will honor the certificate if you put it into the Trusted Certificate Authorities store).

It would be preferable to use the V3 SDK rather than the V2.

DocumentClient Linq to SQL

I'm struggling to create a query... I want to use Linq extension methods (e.g. .Where(), .Select()) but it seems this API was removed. However documentation seems to not acknowledge this in a straightforward way, nor give an indication as to the plan...

If I look at docs for the v2 API it says it is deprecated. v3 is in preview and obviously incomplete. Where does that leave me?

Expose Quota / capacity information on every response

Applications can be designed to prioritize certain I/O over others and make optimum use of provisioned capacity if the current value of RUs consumed / available at the collection / database level would be returned on every request. (Even if this is slightly stale or an approximate measure). Some information is still better than no information.

Query works in emulator portal, but not via client library

Describe the bug

Assume a document with structure:

{
    "id": "whatever",
    "created": "2019-03-06T23:10:43.897Z",
}

The following query works fine in the portal:

SELECT DISTINCT VALUE u FROM u ORDER BY u.created

However, the same query fails to execute with the v3 .NET client:

System.AggregateException: One or more errors occurred. ---> System.ArgumentException: Distict query requires a matching order by in order to return a continuation token.
If you would like to serve this query through continuation tokens, then please rewrite the query in the form 'SELECT DISTINCT VALUE c.blah FROM c ORDER BY c.blah' and please make sure that there is a range index on 'c.blah'.
   at Microsoft.Azure.Cosmos.FeedResponse`1.get_ResponseContinuation()
   at Microsoft.Azure.Cosmos.CosmosItems.<NextResultSetAsync>d__29`1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at Microsoft.Azure.Cosmos.CosmosDefaultResultSetIterator`1.<FetchNextSetAsync>b__7_0(Task`1 task)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at UserQuery.<Main>d__0.MoveNext() in C:\Users\Kent\AppData\Local\Temp\LINQPad5\_qtvejoem\query_hddtrt.cs:line 65
---> (Inner Exception #0) System.ArgumentException: Distict query requires a matching order by in order to return a continuation token.
If you would like to serve this query through continuation tokens, then please rewrite the query in the form 'SELECT DISTINCT VALUE c.blah FROM c ORDER BY c.blah' and please make sure that there is a range index on 'c.blah'.
   at Microsoft.Azure.Cosmos.FeedResponse`1.get_ResponseContinuation()
   at Microsoft.Azure.Cosmos.CosmosItems.<NextResultSetAsync>d__29`1.MoveNext()<---

SIDE NOTE: there's also a typo in the error message: "distict"

To Reproduce

  1. Create the above document
  2. Execute query in portal
  3. Execute query via the code below
async Task Main()
{
    var conn = "<<connection string>>";
    var cosmosClient = new CosmosClient(conn);

    var databaseResult = await cosmosClient
        .Databases
        .CreateDatabaseIfNotExistsAsync("my", 400);
    var database = databaseResult.Database;
    var usersContainerResult = await database
        .Containers
        .CreateContainerIfNotExistsAsync("test", "/id");
    var usersContainer = usersContainerResult.Container;

    var sql = new CosmosSqlQueryDefinition("SELECT DISTINCT VALUE u FROM u ORDER BY u.created");
    
    var itemQuery = usersContainer
        .Items
        .CreateItemQuery<JObject>(sql, 2);

    try
    {
        while (itemQuery.HasMoreResults)
        {
            // THIS FAILS
            var currentResultSet = await itemQuery
                .FetchNextSetAsync();
        }
    }
    catch (Exception ex)
    {
        ex.ToString().Dump();
    }
}

Expected behavior

It should work from the .NET client exactly as in the portal.

Actual behavior

It fails, and asks you to do something you've already done.

Environment summary

SDK Version: 3.0.0.1-preview
OS Version: Windows 10

Additional Context

You may wonder why I'm requiring the DISTINCT, VALUE, and ORDER BY at all. It's because my actual query has a JOIN to an inner child collection. So I need the DISTINCT because I don't want repeated values (it does repeat but that looks to be a separate bug. See here). Because I have DISTINCT I then require an ORDER BY. And because I want the actual values, that's why I have VALUE.

Script logs lose information (casing and new lines)

Is your feature request related to a problem? Please describe.
Trying to debug a sproc. I've set EnableScriptLogging in the options, but can't find a way to pull the console output out using the Microsoft.Azure.Cosmos API.

Describe the solution you'd like
A way to get the console output.

Describe alternatives you've considered
The old way doesn't appear to work any more.

Items by Partition Key

I’m sure this is obvious but how do I get all items by partiton key? do i still use MaxItems = -1 and does the concurrently option come into play?

thanks!

Ship DefaultCosmosJsonSerializer in a separate package

Moving out all code that depends on Newtonsoft.Json would make it possible to avoid a transitive reference from a project that doesn't need it.

Microsoft.Azure.Cosmos could become a meta-package to keep the simplicity of the common use case.

How does one delete a sproc?

Is your feature request related to a problem? Please describe.
I am creating a sproc programmatically. The first time it's created, the creation invocation works (CreateStoredProceducreAsync). The second time, I get a 409 with no explanation. I figured out that it's complaining because that sproc has been created already. By appending a random string on the name, it then worked.

I'd obviously rather delete the sproc and create a replacement, but I can't see any API allowing this in the Microsoft.Azure.Cosmos client.

Describe the solution you'd like
A simple way to delete a sproc programmatically.

Describe alternatives you've considered
Recreating the entire container (nope, especially impossible when production data is in the container).

How the old OpenAsync has been handled

Hi Team,
First of I back up what others have said that it is super super cool that you open source the project! :)
DocumentClien.OpenAsync() has been an important feature that needed to be handled properly when using dependency injection in .Net Core. But it seems to have disappeared. Could you explain a bit how that is handled now?

Getting sane errors out of sprocs

Is your feature request related to a problem? Please describe.
I just want a sensible way/guidance to get errors out of procs. Throwing Error per the docs is fine and dandy, except now you've no practical way of switching on error codes or the likes from the client side. Throwing a JSON-formatted string and catching BadRequestException / DocumentClientException seemed promising, except both those exceptions are (inexplicably) internal types with no way of getting the Error object without reflection. Also, they get unwrapped into a CosmosException which throws away the Error property altogether and leaves you with little choice but to do string manipulation on its Message property.

Describe the solution you'd like
Make it practical to get errors out of sprocs and UDFs in such a way that the client can obtain information about what went wrong. Add relevant information to the docs.

Describe alternatives you've considered
As best I can tell, all alternatives are hacks. Reflection, string parsing etc. Yuck.

EF Core provider gap: CreateContainerIfNotExistsAsync call is required for getting CosmosItem

In the new SDK, if you need to get CosmosItems you first need to call CreateContainerIfNotExistsAsync().

For SDK customers in general, this means there is no way to get the CosmosItems object without creating a container as a side effect, even if that isn't the intent.

For EF Core it means that some existing APIs will have unexpected semantics.

This issue was found while adapting EF Core provider to work with Cosmos SDK version 3.0.0.1-preview.

cc @AndriySvyryd @ajcvickers @kirillg

[RFC] Proxy support

re: Azure/azure-cosmos-dotnet-v2#434

I'd be willing to contribute a pull request to support that.

However, as there may potentially be various ways to put that in place, I'd like first to discuss about how you would prefer to see this implemented.

Java and Node versions of the SDK seem to expose the proxy address through a get/setter exposed by the ConnectionPolicy class.

However, I'm wondering if that wouldn't be actually easier to

  • Accept an optional HttpMessageHandler which would be wrapped by the internal HttpMessageHandler and from which we would build the HttpClient
  • Or accept an optional delegate that would be used to create an HttpMessageHandler. This may actually pave the way to later leverage the HttpClientFactory.

I understand that going the HttpMessageHandler way would actually make this SDK API differ from the other languages from an API standpoint. However, it's not uncommon for a .NET Api to accept a handler from which the back channel is built.

Thoughts?`

EF Core provider gap: CreateDatabaseIfNotExistsAsync call is required for getting CosmosDatabase

In the new SDK, if you need to get CosmosDatabase you first need to call CreateDatabaseIfNotExistsAsync().

For SDK customers in general, this means there is no way to get the CosmosDatabase object without creating a database as a side effect, even if that isn't the intent.

For EF Core it means that some existing APIs will have unexpected semantics.

This issue was found while adapting EF Core provider to work with Cosmos SDK version 3.0.0.1-preview.

cc @AndriySvyryd @ajcvickers @kirillg

FormatException : Input string was not in a correct format.

i try this very simple code sample, but getting a FormatException : Input string was not in a correct format.
Database and collection are created, but exception occurs on container.Items.CreateItemAsync
SDK :
Microsoft.Azure.Cosmos 3.0.0.1-preview (via nuget)
Emulator :
Azure Cosmos DB Emulator 2.1.3.0

string databaseId = "TodoDatabase";
string containerId = "TodoContainer";
string partitionKey = "/partitionKey";

// Create new instance of CosmosClient
using (CosmosClient cosmosClient = new CosmosClient("https://localhost:5002", "MyKey"))
           {
               // Create new database
               CosmosDatabase database = await cosmosClient.Databases.CreateDatabaseIfNotExistsAsync(databaseId);

               // Create new container
               CosmosContainer container = await database.Containers.CreateContainerIfNotExistsAsync(containerId, partitionKey);

               // Add item to container
               var todoItem = new TodoItem()
               {
                   Id = Guid.NewGuid().ToString(),
                   PartitionKey = Guid.NewGuid().ToString(),
                   Task = "Get started with Azure Cosmos DB!"
               };
               var todoItemResponse = await container.Items.CreateItemAsync<TodoItem>(todoItem.PartitionKey, todoItem);
           }    

Please put spatial classes in separate Nuget

Developers will reference the spatial classes in their own classes. It would be helpful if they didn't need to reference the entire Cosmos SDK.

It goes without saying that you'll need to remove the "internal" keyword from your spatial classes to make them useful.

Introducing testability

When I write a unit testing with Moq, It can't be mocked. It says Could not find a parameterless constructor.

Solution might be adding a parameterless constructor or interface. However, interface might be a good design as an API.

Another approach is using CosmosDB emulator and having some integration testing. We can do it. However, people might want to unit testing since it is very fast without having remote call.

EF Core provider gap: Provide proper synchronous version of various APIs

The following methods don't have synchronous equivalents:

  • CreateDatabaseIfNotExistsAsync()
  • CosmosDatabase.DeleteAsync()
  • CreateContainerIfNotExistsAsync()
  • CosmosResultSetIterator<>.FetchNextSetAsync()
  • CosmosQueryResponse<>.FetchNextSetAsync()
  • CreateItemAsync<>()
  • ReplaceItemAsync<>()
  • DeleteItemAsync<>()

Since EF Core provides both synchronous and asynchronous APIs, in the EF Core provider implementation we need to choose between throwing NotSupportedException and applying workarounds that can cause threads to block and deadlocks.

This issue existed in previous versions of the SDK, and still applies to Cosmos SDK version 3.0.0.1-preview.

cc @AndriySvyryd @ajcvickers @kirillg

Is there a support for functions also similar to stored procedures

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Preserve some of the way creating a query worked in v2

I liked how CreateDocumentQuery worked in v2. It returned an IQueryable so you could have one function that built up part of the query and pass it on to some other function that added to that query before executing it. It also let us use linq methods to build up the query.

Was it removed for performance reasons? Is there any way to retain some of the spirit of how it worked?

Thanks!

Thanks a lot for open sourcing this!

❤️

Any estimate when v.3 should go to production?

I haven't seen this info anywhere and as i am starting new project, i'm trying to see best decision about should i go with 2.2.1. until v.3 goes production or maybe starting with it right away if its close.

So, any known plans?

thanks

RequestCharge not available for CosmosQueryResponse<T>

I can not access Resources.RequestCharge in CosmosQueryResponse object.

To recreate
var resultSet = await querysetIterator.FetchNextSetAsync();

There is no way to get RequestCharge in resultSet. FeedResponse object is private.

Save document with diacritics

Describe the bug
When inserting an item that contains diacritics using container.Items.CreateItemAsync it is being inserted like this:
image

I've been playing with the CosmosDefaultJsonSerializer, trying to change the Encoding of the StreamWriter with no luck.

I've also noticed that if I insert the document by using the Data Explorer through Azure Portal it works as expected. Maybe I'm missing some configuration somewhere that would solve this?

To Reproduce
Just try to insert an object like this in a collection and check what is being saved.
new { id = "newid", name = "Román" }

Expected behavior
Chars with diacritics to be saved properly.

Actual behavior
Chars with diacritics are lost during the saving.

Environment summary
SDK Version: 3.0.0.1-preview

ItemQuery does not appear to use custom serializer

I've created a custom JSON serializer and am able to get it to work when inserting data using UpsertItemsAsync. However, when I retrieve data back using CreateItemQuery and FetchNextSetAsync the custom serializer does not appear to get called.

As you can see from this stack trace, it looks like it's calling Newtonsoft.Json even though I've plugged a custom serializer in.

System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> Newtonsoft.Json.JsonSerializationException: Unexpected property '_rid' found when reading union. Path '_rid', line 1, position 12715.
   at Newtonsoft.Json.Converters.DiscriminatedUnionConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor`1 creator, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, String id, Boolean& createdFromNonDefaultCreator)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.Convert(Type type)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.AsType[T]()
   at Microsoft.Azure.Cosmos.FeedResponseBinder.Convert[T](FeedResponse`1 dynamicFeed)
   at Microsoft.Azure.Cosmos.Linq.DocumentQuery`1.<ExecuteNextPrivateAsync>d__36`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Cosmos.CosmosItems.<NextResultSetAsync>d__29`1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.Azure.Cosmos.CosmosDefaultResultSetIterator`1.<FetchNextSetAsync>b__7_0(Task`1 task)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at <StartupCode$FSI_0015>.$FSI_0015.main@()
---> (Inner Exception #0) System.AggregateException: One or more errors occurred. ---> Newtonsoft.Json.JsonSerializationException: Unexpected property '_rid' found when reading union. Path '_rid', line 1, position 12715.
   at Newtonsoft.Json.Converters.DiscriminatedUnionConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor`1 creator, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, String id, Boolean& createdFromNonDefaultCreator)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.Convert(Type type)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.AsType[T]()
   at Microsoft.Azure.Cosmos.FeedResponseBinder.Convert[T](FeedResponse`1 dynamicFeed)
   at Microsoft.Azure.Cosmos.Linq.DocumentQuery`1.<ExecuteNextPrivateAsync>d__36`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Cosmos.CosmosItems.<NextResultSetAsync>d__29`1.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.Azure.Cosmos.CosmosDefaultResultSetIterator`1.<FetchNextSetAsync>b__7_0(Task`1 task)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
---> (Inner Exception #0) Newtonsoft.Json.JsonSerializationException: Unexpected property '_rid' found when reading union. Path '_rid', line 1, position 12715.
   at Newtonsoft.Json.Converters.DiscriminatedUnionConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor`1 creator, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, String id, Boolean& createdFromNonDefaultCreator)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType, JsonSerializer jsonSerializer)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.Convert(Type type)
   at Microsoft.Azure.Cosmos.Internal.QueryResult.AsType[T]()
   at Microsoft.Azure.Cosmos.FeedResponseBinder.Convert[T](FeedResponse`1 dynamicFeed)
   at Microsoft.Azure.Cosmos.Linq.DocumentQuery`1.<ExecuteNextPrivateAsync>d__36`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Cosmos.CosmosItems.<NextResultSetAsync>d__29`1.MoveNext()<---

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.