Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c# - azure cosmos DB is not creating container under database with no errors in xamarin.forms

i was following this tutorial here youtubetutorial github

my code below(took out the key for obvious reasons)

using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace azurebasics {
  public partial class App: Application {
    public App() {
      InitializeComponent();

      MainPage = new MainPage();
      CreateItem().Wait();

    }
    private static async Task CreateItem() {
      var cosmosUrl = "";
      var cosmoskey = "";
      var databaseName = "DemoDB";

      CosmosClient client = new CosmosClient(cosmosUrl, cosmoskey);
      Database database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
      Container container = await database.CreateContainerIfNotExistsAsync(
        "MyContainerName", "/partitionKeyPath", 400);

      dynamic testItem = new {
        id = Guid.NewGuid().ToString(), partitionKeyPath = "MyTestPkValue", details = "it's working"
      };
      var response = await container.CreateItemAsync(testItem);
    }

    protected override void OnStart() {}

    protected override void OnSleep() {}

    protected override void OnResume() {}
  }
}

so I would run this code and it would create the database with no container as shown here I'm confused because the connection works if it makes the database. and the only weird thing I found between the github and his tutorial is in the video he has

var response = await container.CreateItemAsync(testItem);

and the github has

ItemResponse<dynamic> response = await container.CreateItemAsync(testItem);
question from:https://stackoverflow.com/questions/65661746/azure-cosmos-db-is-not-creating-container-under-database-with-no-errors-in-xamar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, please follow the Performance Guidelines and have a singleton instance of the CosmosClient. Creating a new instance every time you want to insert 1 item would be detrimental for the app.

Second, you are doing a blocking async call CreateItem().Wait(); this can generate deadlocks. Try and execute the async operations following the recommendations on the Xamarin docs: https://docs.microsoft.com/xamarin/cross-platform/platform/async, for example, binding to a button that actually performs the save.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...