UWP是否与CosmosDb兼容

时间:2018-09-11 16:11:08

标签: c# uwp azure-cosmosdb

我有一个.net标准2.0类库。我正在使用带有棱镜mvvm框架的UWP前端。当我尝试在视图模型中访问cosmosdb时,文档客户端不会返回。是否存在兼容性问题?

2 个答案:

答案 0 :(得分:1)

基于我们现有的项目,不存在兼容性问题。

对于政策限制,我可以分享我们的代码。但是我找到了第三个链接供您参考:

  

https://www.c-sharpcorner.com/article/customized-azure-cosmos-db-with-xamarin-forms-application-student-detail-for-a/

参考摘要:

  
      
  1. 创建Azure Cosmos数据库。

  2.   
  3. 创建Xamarin.Forms应用程序:打开Visual Studio 2017->“开始”->“新建项目”->选择跨平台(在Visual C#->跨平台下)   ->移动应用程序(Xamarin.Forms)->为您的应用程序(XamFormStudCos)输入合适的名称->确定。

  4.   
     

选择“跨平台”模板作为空白APP->“将平台设置为”   Android,iOS和UWP和代码共享策略作为共享项目。

     

添加Microsoft.Azure.DocumentDB.Core参考。

     

为xamstudcosmos帐户(CosmosDB)添加Connection.cs类:

using Newtonsoft.Json;  
public class Connection {  
    public static readonly string EndpointUri = "https://xamstudcosmos.documents.azure.com:443/";  
    public static readonly string PrimaryKey = "r03kRnNeyU3Bij7b9TZgsrkoKoU2ERdWM2d2jMAaaKWFClSJobyC8SyXmeazwKEwm8c2UhEjCNDU9NhI4grEFQ==";

    public static readonly string DatabaseName = "StudentDB";  
    public static readonly string CollectionName = "Student";  
} 
     

使用MVC,首先创建模型文件夹并添加StudentDetail类   用于数据模型:

public class StudentDetail {  
    [JsonProperty(PropertyName = "id")]  
    public string Id {  
        get;  
        set;  
    }  
    [JsonProperty(PropertyName = "name")]  
    public string Name {  
        get;  
        set;  
    }  
    [JsonProperty(PropertyName = "Age")]  
    public string Age {  
        get;  
        set;  
    }  
}
     

创建控制器文件夹并为DocumentDB添加IDocumentDBService接口:

using System.Threading.Tasks;  
using XamFormStudCos.Model;  
public interface IDocumentDBService {  
    Task CreateDatabaseAsync(string databaseName);  
    Task CreateDocumentCollectionAsync(string databaseName, string collectionName);  
    Task < List < StudentDetail >> GetStoreInfoAsync();  
    Task SaveStudentDetailAsync(StudentDetail stud, bool isNewstudent);  
    Task DeleteStudentAsync(string id);  
} 
     

添加用于实现IDocumentDBService的DocumentDBService类   界面

using System.Threading.Tasks;  
using XamFormStudCos.Model;  
using Microsoft.Azure.Documents;  
using Microsoft.Azure.Documents.Client;  
using Microsoft.Azure.Documents.Linq;  
using System.Diagnostics;  
class DocumentDBService: IDocumentDBService {  
    public List < StudentDetail > Items {  
        get;  
        private set;  
    }  
    DocumentClient client;  
    Uri collectionLink;  
    public DocumentDBService() {  
        client = new DocumentClient(new Uri(Connection.EndpointUri), Connection.PrimaryKey);  

collectionLink = UriFactory.CreateDocumentCollectionUri(Connection.DatabaseName,
     

Connection.CollectionName); }公共异步任务   CreateDatabaseAsync(string databaseName){
      尝试{
          等待client.CreateDatabaseIfNotExistsAsync(新数据库{
              ID = databaseName
          });
      }捕捉(DocumentClientException ex){
          Debug.WriteLine(“错误:”,例如消息);
      }}公共异步任务CreateDocumentCollectionAsync(string databaseName,string collectionName){
      尝试{
          等待client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName),   新的DocumentCollection {
              ID = collectionName
          },新的RequestOptions {
              OfferThroughput = 400
          });
      }捕捉(DocumentClientException ex){
          Debug.WriteLine(“错误:”,例如消息);
      }}公共异步任务DeleteStudentAsync(string id){
      尝试{
          等待client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName,   Connection.CollectionName,id));

        } catch (DocumentClientException ex) {  
            Debug.WriteLine("Error: ", ex.Message);  
        }  
    }  
    async Task DeleteDocumentCollection() {  
        try {  
            await client.DeleteDocumentCollectionAsync(collectionLink);  
        } catch (DocumentClientException ex) {  
            Debug.WriteLine("Error: ", ex.Message);  
        }  
    }  
    async Task DeleteDatabase() {  
        try {  
            await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName));

        } catch (DocumentClientException ex) {  
            Debug.WriteLine("Error: ", ex.Message);  
        }  
    }  
    public async Task < List < StudentDetail >> GetStudentAsync() {  
        Items = new List < StudentDetail > ();  
        try {  
            var query = client.CreateDocumentQuery < StudentDetail > (collectionLink).AsDocumentQuery();  
            while (query.HasMoreResults) {  
                Items.AddRange(await query.ExecuteNextAsync < StudentDetail > ());

            }  
        } catch (DocumentClientException ex) {  
            Debug.WriteLine("Error: ", ex.Message);  
        }  
        return Items;  
    }  
    public async Task SaveStudentDetailAsync(StudentDetail student, bool isNewItem) {  
        try {  
            if (isNewItem) {  
                await client.CreateDocumentAsync(collectionLink, student);  
            } else {  
                await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName,
     

Connection.CollectionName,student.Id),student);
                  }
              }捕捉(DocumentClientException ex){
                  Debug.WriteLine(“错误:”,例如消息);
              }
          }
      }   添加StudentDetailManager类。

using System.Threading.Tasks;  
using XamFormStudCos.Model;  
using XamFormStudCos.Controller;  
public class StudentDetailManager {  
    IDocumentDBService documentDBService;  
    public StudentDetailManager(IDocumentDBService service) {  
        documentDBService = service;  
    }  
    public Task CreateDatabase(string databaseName) {  
        return documentDBService.CreateDatabaseAsync(databaseName);  
    }  
    public Task CreateDocumentCollection(string databaseName, string collectionName) {  
        return documentDBService.CreateDocumentCollectionAsync(databaseName,
     

collectionName);
          }
          公共任务<列表> GetStoreInfoAsync(){
              返回documentDBService.GetStoreInfoAsync();
          }
          公共任务SaveStudentDetailAsync(StudentDetail学生,bool isNewItem = false){
              返回documentDBService.SaveStudentDetailAsync(student,isNewItem);
          }
          公共任务DeleteStudentAsync(StudentDetail学生){
              返回documentDBService.DeleteStudentAsync(student.Id);
          }
      }
  在App.xaml.cs中添加以下命名空间和代码。

using XamFormStudCos.Controller;  
using XamFormStudCos.View;  
public static StudentDetailManager StudentDetailManager {  
    get;  
    private set;  
}  
public App() {  
    InitializeComponent();  
    StudentDetailManager = new StudentDetailManager(new DocumentDBService());  
    MainPage = new NavigationPage(new StudentList());  
} 
     

接下来,创建查看文件夹并添加StudentList Xaml页面以查看所有学生列表。使用“添加”和“列表视图”项添加“工具栏”项   用于查看学生列表。

<ContentPage.ToolbarItems>  
    <ToolbarItem Text="Add" Order="Primary" Clicked="OnItemAdded" /> </ContentPage.ToolbarItems>  
<ListView x:Name="SList" ItemSelected="OnItemselected">  
    <ListView.ItemTemplate>  
        <DataTemplate>  
            <TextCell Text="{Binding Name}" Detail="{Binding Age}" /> </DataTemplate>  
    </ListView.ItemTemplate>  
</ListView> 
     

在StudentList.xaml.cs中添加以下命名空间和代码

using XamFormStudCos.Model;  
protected override async void OnAppearing() {  
    base.OnAppearing();  
    await App.StudentDetailManager.CreateDatabase(Constants.DatabaseName);  
    await App.StudentDetailManager.CreateDocumentCollection(Constants.DatabaseName,
     

Constants.CollectionName);
          var data = await App.StudentDetailManager.GetStoreInfoAsync();
          StdList.ItemsSource =数据;
      }
      异步void OnItemAdded(object sender,EventArgs e){
          等待Navigation.PushAsync(new StudentDetails(true){
              BindingContext =新的StudentDetail {
                  ID = Guid.NewGuid()。ToString()
              }
          });
      }
      异步void OnItemselected(对象发送者,SelectedItemChangedEventArgs e){
          if(e.SelectedItem!= null){
              等待Navigation.PushAsync(new EditStudent(){
                  BindingContext = e.SelectedItem作为StudentDetail
              });
          }
      }

     

添加StudentDetails Xaml页面以添加新的Student Detail。

     

要添加新学生,请使用以下命令添加标签,条目和按钮控件   点击事件方法。

<ContentPage.Content>  
    <StackLayout Margin="20" VerticalOptions="StartAndExpand">  
        <Label Text="Name" />  
        <Entry Text="{Binding Path=Name}" Placeholder="Enter Student Name" />  
        <Label Text="Age" />  
        <Entry Text="{Binding Path=Age}" />  
        <Button Text="Save" Clicked="OnSaveClicked" />  
        <Button Text="Cancel" Clicked="OnCancelClicked" /> </StackLayout>  
</ContentPage.Content>  
     

在StudentDetail.xaml.cs中添加以下命名空间和代码

using XamFormStudCos.Model;  
bool isNewItem;  
public StudentDetails(bool isNew) {  
    InitializeComponent();  
    isNewItem = isNew;  
}  
async void OnSaveClicked(object sender, EventArgs e) {  
    var student = (StudentDetail) BindingContext;  
    await App.StudentDetailManager.SaveStudentDetailAsync(student, isNewItem);  
    await Navigation.PopAsync();  
}  
async void OnCancelClicked(object sender, EventArgs e) {  
    await Navigation.PopAsync();  
}  
     

为EditStudent(更新,删除)详细信息添加EditStudent Xaml页面。

     

要编辑学生,请单击添加标签,条目和按钮控件   事件方法,

<StackLayout Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
    <Grid>  
        <Label Text="Name" Grid.Row="0" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center"
     

/>
              
              
               
          
           

    <Button Text="Cancel" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnCancelClicked" />
     

     

在EditStudent.xaml.cs中添加以下命名空间和代码

using XamFormStudCos.Model;  
async void Update_Clicked(object sender, System.EventArgs e) {  
    var student = (StudentDetail) BindingContext;  
    await App.StudentDetailManager.SaveStudentDetailAsync(student);  
    await Navigation.PopAsync();  
}  
async void OnDeleteClicked(object sender, EventArgs e) {  
    bool accepted = await DisplayAlert("Confirm", "Are you Sure ?", "Yes", "No");  
    if (accepted) {  
        var student = (StudentDetail) BindingContext;  
        await App.StudentDetailManager.DeleteStudentAsync(student);  
        await Navigation.PopAsync();  
    }  
}  
async void OnCancelClicked(object sender, EventArgs e) {  
    await Navigation.PopAsync();  
}
     

构建和部署。

您需要检查配置或其他代码逻辑。

答案 1 :(得分:0)

Microsoft 支持人员表示,Cosmos DB 在发布模式下无法在 UWP 上工作(并且从未工作过)(并且修复它的优先级较低)。我假设这个例子只在调试模式下运行。我很想知道一个解决方法。我已经尝试了 V2 SDK 和 V3 SDK。 复制不需要像这个例子那么复杂。只需从 Blank UWP 应用模板开始,尝试查询 Cosmos。