Creating Azure Cosmos DB Collections

Asked

Viewed 87 times

1

Well I was creating a Poc with Generic Interface for handling my data, but I had difficulties to do with Webapi MVC, I did with good old MVC. But for the whole JSON issue, I think I lose a lot if I don’t work with REST.

You could help me?

Repository:

public static class DocumentDBRepository<T> where T : class
{
    private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];
    private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];
    private static DocumentClient client;

    public static async Task<T> GetItemAsync(string id)
    {
        try
        {
            Document document = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
            return (T)(dynamic)document;
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return null;
            }
            else
            {
                throw;
            }
        }
    }

    public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate)
    {
        IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
            UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
            new FeedOptions { MaxItemCount = -1 })
            .Where(predicate)
            .AsDocumentQuery();

        List<T> results = new List<T>();
        while (query.HasMoreResults)
        {
            results.AddRange(await query.ExecuteNextAsync<T>());
        }

        return results;
    }

    public static async Task<Document> CreateItemAsync(T item)
    {
        return await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), item);
    }

    public static async Task<Document> UpdateItemAsync(string id, T item)
    {
        return await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
    }

    public static async Task DeleteItemAsync(string id)
    {
        await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
    }

    public static void Initialize()
    {
        client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
        CreateDatabaseIfNotExistsAsync().Wait();
        CreateCollectionIfNotExistsAsync().Wait();
    }

    private static async Task CreateDatabaseIfNotExistsAsync()
    {
        try
        {
            await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
            }
            else
            {
                throw;
            }
        }
    }

    private static async Task CreateCollectionIfNotExistsAsync()
    {
        try
        {
            await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
        }
        catch (DocumentClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                await client.CreateDocumentCollectionAsync(
                    UriFactory.CreateDatabaseUri(DatabaseId),
                    new DocumentCollection { Id = CollectionId },
                    new RequestOptions { OfferThroughput = 1000 });
            }
            else
            {
                throw;
            }
        }
    }
}

Model:

public class Item
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "titulo")]
    public string Titulo { get; set; }

    [JsonProperty(PropertyName = "descricao")]
    public string Descricao { get; set; }

    [JsonProperty(PropertyName = "status")]
    public bool Status { get; set; }
}

Controller:

public class ItemController : Controller
{
    [ActionName("Index")]
    public async Task<ActionResult> IndexAsync()
    {
        var items = await DocumentDBRepository<Item>.GetItemsAsync(d => d.Status);
        if (items != null)
            return View(items);

        return View();
    }

    [ActionName("Create")]
    public async Task<ActionResult> CreateAsync()
    {
        return View();
    }

    [HttpPost]
    [ActionName("Create")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> CreateAsync([Bind(Include = "id,titulo,descricao,status")] Item item)
    {
        if (ModelState.IsValid)
        {
            await DocumentDBRepository<Item>.CreateItemAsync(item);
            return RedirectToAction("Index");
        }

        return View(item);
    }

    [HttpPost]
    [ActionName("Edit")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> EditAsync([Bind(Include = "id,titulo,descricao,status")] Item item)
    {
        if (ModelState.IsValid)
        {
            await DocumentDBRepository<Item>.UpdateItemAsync(item.Id, item);
            return RedirectToAction("Index");
        }

        return View(item);
    }

    [ActionName("Edit")]
    public async Task<ActionResult> EditAsync(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        if (item == null)
        {
            return HttpNotFound();
        }

        return View(item);
    }

    [ActionName("Delete")]
    public async Task<ActionResult> DeleteAsync(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        if (item == null)
        {
            return HttpNotFound();
        }

        return View(item);
    }

    [HttpPost]
    [ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmedAsync([Bind(Include = "id")] string id)
    {
        await DocumentDBRepository<Item>.DeleteItemAsync(id);
        return RedirectToAction("Index");
    }

    [ActionName("Details")]
    public async Task<ActionResult> DetailsAsync(string id)
    {
        Item item = await DocumentDBRepository<Item>.GetItemAsync(id);
        return View(item);
    }
}
  • What was the difficulty in using the Webapi MVC?

  • Redo the repository using <T>.

  • But what problem are you facing?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.