Author: alien

  • Khóa học miễn phí DocumentDB – Data Types nhận dự án làm có lương

    DocumentDB – Data Types



    JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange and also easy for machines to parse and generate. JSON is at the heart of DocumentDB. We transmit JSON over the wire, we store JSON as JSON, and we index the JSON tree allowing queries on the full JSON document.

    JSON format supports the following data types −

    S.No. Type & Description
    1

    Number

    Double-precision floating-point format in JavaScript

    2

    String

    Double-quoted Unicode with backslash escaping

    3

    Boolean

    True or false

    4

    Array

    An ordered sequence of values

    5

    Value

    It can be a string, a number, true or false, null, etc.

    6

    Object

    An unordered collection of key:value pairs

    7

    Whitespace

    It can be used between any pair of tokens

    8

    Null

    Empty

    Let’s take a look at a simple example DateTime type. Add birth date to the customer class.

    public class Customer {
       [JsonProperty(PropertyName = "id")]
       public string Id { get; set; }
    
       // Must be nullable, unless generating unique values for new customers on client
       [JsonProperty(PropertyName = "name")]
       public string Name { get; set; }
    
       [JsonProperty(PropertyName = "address")]
       public Address Address { get; set; }
    
       [JsonProperty(PropertyName = "birthDate")]
       public DateTime BirthDate { get; set; }
    }
    

    We can store, retrieve, and query using DateTime as shown in the following code.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       var document3Definition = new Customer {
          Id = "1001",
          Name = "Luke Andrew",
    
          Address = new Address {
             AddressType = "Main Office",
             AddressLine1 = "123 Main Street",
             Location = new Location {
                City = "Brooklyn",
                StateProvinceName = "New York"
             },
             PostalCode = "11229",
             CountryRegionName = "United States"
          },
    
          BirthDate = DateTime.Parse(DateTime.Today.ToString()),
       };
    
       Document document3 = await CreateDocument(client, document3Definition);
       Console.WriteLine("Created document {0} from typed object", document3.Id);
       Console.WriteLine();
    }
    

    When the above code is compiled and executed, and the document is created, you will see that birth date is added now.

    **** Create Documents ****
    Created new document: 1001
    {
       "id": "1001",
       "name": "Luke Andrew",
       "address": {
          "addressType": "Main Office",
          "addressLine1": "123 Main Street",
          "location": {
             "city": "Brooklyn",
             "stateProvinceName": "New York"
          },
          "postalCode": "11229",
          "countryRegionName": "United States"
       },
       "birthDate": "2015-12-14T00:00:00",
       "_rid": "Ic8LAMEUVgAKAAAAAAAAAA==",
       "_ts": 1450113676,
       "_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgAKAAAAAAAAAA==/",
       "_etag": ""00002d00-0000-0000-0000-566efa8c0000"",
       "_attachments": "attachments/"
    }
    Created document 1001 from typed object
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Limiting Records nhận dự án làm có lương

    DocumentDB – Limiting Records



    Microsoft has recently added a number of improvements on how you can query Azure DocumentDB, such as the TOP keyword to SQL grammar, which made queries run faster and consume fewer resources, increased the limits for query operators, and added support for additional LINQ operators in the .NET SDK.

    Let’s take a look at a simple example in which we will retrieve only the first two records. If you have a number of records and you want to retrieve only some of them, then you can use the Top keyword. In this example, we have a lot of records of earthquakes.

    Limiting Records

    Now we want to show the first two records only

    Step 1 − Go to the query explorer and run this query.

    SELECT * FROM c
    WHERE c.magnitude > 2.5
    

    You will see that it has retrieved four records because we have not specified TOP keyword yet.

    Retrieved Records

    Step 2 − Now use the TOP keyword with same query. Here we have specified the TOP keyword and ‘2’ means that we want two records only.

    SELECT TOP 2 * FROM c
    WHERE c.magnitude > 2.5
    

    Step 3 − Now run this query and you will see that only two records are retrieved.

    Two records retrieved

    Similarly, you can use TOP keyword in code using .Net SDK. Following is the implementation.

    private async static Task QueryDocumentsWithPaging(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Query Documents (paged results) ****");
       Console.WriteLine();
       Console.WriteLine("Quering for all documents");
    
       var sql = "SELECT TOP 3 * FROM c";
       var query = client
          .CreateDocumentQuery(collection.SelfLink, sql)
          .AsDocumentQuery();
    
       while (query.HasMoreResults) {
          var documents = await query.ExecuteNextAsync();
    
          foreach (var document in documents) {
             Console.WriteLine(" PublicId: {0}; Magnitude: {1};", document.publicid,
                document.magnitude);
          }
       }
    
       Console.WriteLine();
    }
    

    Following is the CreateDocumentClient task in which are instantiated the DocumentClient and earthquake database.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''earthquake''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''earthquakedata''").AsEnumerable().First();
    
          await QueryDocumentsWithPaging(client);
       }
    }
    

    When the above code is compiled and executed, you will see that only three records are retrieved.

    **** Query Documents (paged results) ****
    
    Quering for all documents
    PublicId: 2015p947400; Magnitude: 2.515176918;
    PublicId: 2015p947373; Magnitude: 1.506774108;
    PublicId: 2015p947329; Magnitude: 1.593394461;
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Query Document nhận dự án làm có lương

    DocumentDB – Query Document



    In DocumentDB, we actually use SQL to query for documents, so this chapter is all about querying using the special SQL syntax in DocumentDB. Although if you are doing .NET development, there is also a LINQ provider that can be used and which can generate appropriate SQL from a LINQ query.

    Querying Document using Portal

    The Azure portal has a Query Explorer that lets you run any SQL query against your DocumentDB database.

    We will use the Query Explorer to demonstrate the many different capabilities and features of the query language starting with the simplest possible query.

    Step 1 − In the database blade, click to open the Query Explorer blade.

    Query Explorer Blade

    Remember that queries run within the scope of a collection, and so the Query Explorer lets you choose the collection in this dropdown.

    Run Query

    Step 2 − Select Families collection which is created earlier using the portal.

    The Query Explorer opens up with this simple query SELECT * FROM c, which simply retrieves all documents from the collection.

    Step 3 − Execute this query by clicking the ‘Run query’ button. Then you will see that the complete document is retrieved in the Results blade.

    Document in Result Blade

    Querying Document using .Net SDK

    Following are the steps to run some document queries using .Net SDK.

    In this example, we want to query for the newly created documents that we just added.

    Step 1 − Call CreateDocumentQuery, passing in the collection to run the query against by its SelfLink and the query text.

    private async static Task QueryDocumentsWithPaging(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Query Documents (paged results) ****");
       Console.WriteLine();
       Console.WriteLine("Quering for all documents");
    
       var sql = "SELECT * FROM c";
       var query = client.CreateDocumentQuery(collection.SelfLink, sql).AsDocumentQuery();
    
       while (query.HasMoreResults) {
          var documents = await query.ExecuteNextAsync();
    
          foreach (var document in documents) {
             Console.WriteLine(" Id: {0}; Name: {1};", document.id, document.name);
          }
       }
    
       Console.WriteLine();
    }
    

    This query is also returning all documents in the entire collection, but we”re not calling .ToList on CreateDocumentQuery as before, which would issue as many requests as necessary to pull down all the results in one line of code.

    Step 2 − Instead, call AsDocumentQuery and this method returns a query object with a HasMoreResults property.

    Step 3 − If HasMoreResults is true, then call ExecuteNextAsync to get the next chunk and then dump all the contents of that chunk.

    Step 4 − You can also query using LINQ instead of SQL if you prefer. Here we”ve defined a LINQ query in q, but it won”t execute until we run .ToList on it.

    private static void QueryDocumentsWithLinq(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Query Documents (LINQ) ****");
       Console.WriteLine();
       Console.WriteLine("Quering for US customers (LINQ)");
    
       var q =
          from d in client.CreateDocumentQuery<Customer>(collection.DocumentsLink)
          where d.Address.CountryRegionName == " United States"
          select new {
             Id = d.Id,
             Name = d.Name,
             City = d.Address.Location.City
          };
    
       var documents = q.ToList();
       Console.WriteLine("Found {0} UK customers", documents.Count);
    
       foreach (var document in documents) {
          var d = document as dynamic;
          Console.WriteLine(" Id: {0}; Name: {1}; City: {2}", d.Id, d.Name, d.City);
       }
    
       Console.WriteLine();
    }
    

    The SDK will convert our LINQ query into SQL syntax for DocumentDB, generating a SELECT and WHERE clause based on our LINQ syntax

    Step 5 − Now call the above queries from the CreateDocumentClient task.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
    
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          //await CreateDocuments(client);
          await QueryDocumentsWithPaging(client);
          QueryDocumentsWithLinq(client);
       }
    
    }
    

    When the above code is executed, you will receive the following output.

    **** Query Documents (paged results) ****
    Quering for all documents
     Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1;
     Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1;
    
    **** Query Documents (LINQ) ****
    Quering for US customers (LINQ)
    Found 2 UK customers
     Id: 7e9ad4fa-c432-4d1a-b120-58fd7113609f; Name: New Customer 1; City: Brooklyn
     Id: 34e9873a-94c8-4720-9146-d63fb7840fad; Name: New Customer 1; City: Brooklyn
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Data Modeling nhận dự án làm có lương

    DocumentDB – Data Modeling



    While schema-free databases, like DocumentDB, make it super easy to embrace changes to your data model, you should still spend some time thinking about your data.

    • You have a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time.

    • You can also work with real C# objects, or Entities as they are called, which might be your business domain classes.

    Relationships

    Let’s take a look at the document”s hierarchal structure. It has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties.

    {
       "id": "AndersenFamily",
       "lastName": "Andersen",
    
       "parents": [
          { "firstName": "Thomas", "relationship": "father" },
          { "firstName": "Mary Kay", "relationship": "mother" }
       ],
    
       "children": [
          {
             "firstName": "Henriette Thaulow",
             "gender": "female",
             "grade": 5,
             "pets": [ { "givenName": "Fluffy", "type": "Rabbit" } ]
          }
       ],
    
       "location": { "state": "WA", "county": "King", "city": "Seattle"},
       "isRegistered": true
    }
    
    • For instance, the parents property is supplied as a JSON array as denoted by the square brackets.

    • We also have another array for children, even though there”s only one child in the array in this example. So this is how you model the equivalent of one-to-many relationships within a document.

    • You simply use arrays where each element in the array could be a simple value or another complex object, even another array.

    • So one family can have multiple parents and multiple children and if you look at the child objects, they have a pet’s property that is itself a nested array for a oneto-many relationship between children and pets.

    • For the location property, we”re combining three related properties, the state, county, and city into an object.

    • Embedding an object this way rather than embedding an array of objects is similar to having a one-to-one relationship between two rows in separate tables in a relational database.

    Embedding Data

    When you start modeling data in a document store, such as DocumentDB, try to treat your entities as self-contained documents represented in JSON. When working with relational databases, we always normalize data.

    • Normalizing your data typically involves taking an entity, such as a customer, and breaking it down into discreet pieces of data, like contact details and addresses.

    • To read a customer, with all their contact details and addresses, you need to use JOINS to effectively aggregate your data at run time.

    Now let”s take a look at how we would model the same data as a self-contained entity in a document database.

    {
       "id": "1",
       "firstName": "Mark",
       "lastName": "Upston",
    
       "addresses": [
          {
             "line1": "232 Main Street",
             "line2": "Unit 1",
             "city": "Brooklyn",
             "state": "NY",
             "zip": 11229
          }
       ],
    
       "contactDetails": [
          {"email": "mark.upston@xyz.com"},
          {"phone": "+1 356 545-86455", "extension": 5555}
       ]
    }
    

    As you can see that we have denormalized the customer record where all the information of the customer is embedded into a single JSON document.

    In NoSQL we have a free schema, so you can add contact details and addresses in different format as well. In NoSQL, you can retrieve a customer record from the database in a single read operation. Similarly, updating a record is also a single write operation.

    Following are the steps to create documents using .Net SDK.

    Step 1 − Instantiate DocumentClient. Then we will query for the myfirstdb database and also query for MyCollection collection, which we store in this private variable collection so that”s it”s accessible throughout the class.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
    
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          await CreateDocuments(client);
       }
    
    }
    

    Step 2 − Create some documents in CreateDocuments task.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       dynamic document1Definition = new {
          name = "New Customer 1", address = new {
             addressType = "Main Office",
             addressLine1 = "123 Main Street",
             location = new {
                city = "Brooklyn", stateProvinceName = "New York"
             },
             postalCode = "11229", countryRegionName = "United States"
          },
       };
    
       Document document1 = await CreateDocument(client, document1Definition);
       Console.WriteLine("Created document {0} from dynamic object", document1.Id);
       Console.WriteLine();
    }
    

    The first document will be generated from this dynamic object. This might look like JSON, but of course it isn”t. This is C# code and we”re creating a real .NET object, but there”s no class definition. Instead the properties are inferred from the way the object is initialized. You can notice also that we haven”t supplied an Id property for this document.

    Step 3 − Now let”s take a look at the CreateDocument and it looks like the same pattern we saw for creating databases and collections.

    private async static Task<Document> CreateDocument(DocumentClient client,
       object documentObject) {
       var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject);
    
       var document = result.Resource;
       Console.WriteLine("Created new document: {0}rn{1}", document.Id, document);
    
       return result;
    }
    

    Step 4 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties.

    In the following CreateDocuments task, we have created three documents.

    • In the first document, the Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       dynamic document1Definition = new {
          name = "New Customer 1", address = new {
             addressType = "Main Office",
             addressLine1 = "123 Main Street",
             location = new {
                city = "Brooklyn", stateProvinceName = "New York"
             },
             postalCode = "11229",
             countryRegionName = "United States"
          },
       };
    
       Document document1 = await CreateDocument(client, document1Definition);
       Console.WriteLine("Created document {0} from dynamic object", document1.Id);
       Console.WriteLine();
    
       var document2Definition = @" {
          ""name"": ""New Customer 2"",
    
          ""address"": {
             ""addressType"": ""Main Office"",
             ""addressLine1"": ""123 Main Street"",
             ""location"": {
                ""city"": ""Brooklyn"", ""stateProvinceName"": ""New York""
             },
             ""postalCode"": ""11229"",
             ""countryRegionName"": ""United States""
          }
       }";
    
       Document document2 = await CreateDocument(client, document2Definition);
       Console.WriteLine("Created document {0} from JSON string", document2.Id);
       Console.WriteLine();
    
       var document3Definition = new Customer {
          Name = "New Customer 3",
    
          Address = new Address {
             AddressType = "Main Office",
             AddressLine1 = "123 Main Street",
             Location = new Location {
                City = "Brooklyn", StateProvinceName = "New York"
             },
             PostalCode = "11229",
             CountryRegionName = "United States"
          },
       };
    
       Document document3 = await CreateDocument(client, document3Definition);
       Console.WriteLine("Created document {0} from typed object", document3.Id);
       Console.WriteLine();
    }
    
    • This second document just works with a raw JSON string. Now we step into an overload for CreateDocument that uses the JavaScriptSerializer to de-serialize the string into an object, which it then passes on to the same CreateDocument method that we used to create the first document.

    • In the third document, we have used the C# object Customer which is defined in our application.

    Let’s take a look at this customer, it has an Id and address property where the address is a nested object with its own properties including location, which is yet another nested object.

    using Newtonsoft.Json;
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DocumentDBDemo {
    
       public class Customer {
          [JsonProperty(PropertyName = "id")]
          public string Id { get; set; }
          // Must be nullable, unless generating unique values for new customers on client
          [JsonProperty(PropertyName = "name")]
          public string Name { get; set; }
          [JsonProperty(PropertyName = "address")]
          public Address Address { get; set; }
       }
    
       public class Address {
          [JsonProperty(PropertyName = "addressType")]
          public string AddressType { get; set; }
    
          [JsonProperty(PropertyName = "addressLine1")]
          public string AddressLine1 { get; set; }
    
          [JsonProperty(PropertyName = "location")]
          public Location Location { get; set; }
    
          [JsonProperty(PropertyName = "postalCode")]
          public string PostalCode { get; set; }
    
          [JsonProperty(PropertyName = "countryRegionName")]
          public string CountryRegionName { get; set; }
       }
    
       public class Location {
          [JsonProperty(PropertyName = "city")]
          public string City { get; set; }
    
          [JsonProperty(PropertyName = "stateProvinceName")]
          public string StateProvinceName { get; set; }
       }
    }
    

    We also have JSON property attributes in place because we want to maintain proper conventions on both sides of the fence.

    So I just create my New Customer object along with its nested child objects and call into CreateDocument once more. Although our customer object does have an Id property we didn”t supply a value for it and so DocumentDB generated one based on the GUID, just like it did for the previous two documents.

    When the above code is compiled and executed you will receive the following output.

    **** Create Documents ****
    Created new document: 575882f0-236c-4c3d-81b9-d27780206b2c
    {
      "name": "New Customer 1",
      "address": {
        "addressType": "Main Office",
        "addressLine1": "123 Main Street",
        "location": {
          "city": "Brooklyn",
          "stateProvinceName": "New York"
        },
        "postalCode": "11229",
        "countryRegionName": "United States"
      },
      "id": "575882f0-236c-4c3d-81b9-d27780206b2c",
      "_rid": "kV5oANVXnwDGPgAAAAAAAA==",
      "_ts": 1450037545,
      "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDGPgAAAAAAAA==/",
      "_etag": ""00006fce-0000-0000-0000-566dd1290000"",
      "_attachments": "attachments/"
    }
    Created document 575882f0-236c-4c3d-81b9-d27780206b2c from dynamic object
    Created new document: 8d7ad239-2148-4fab-901b-17a85d331056
    {
      "name": "New Customer 2",
      "address": {
        "addressType": "Main Office",
        "addressLine1": "123 Main Street",
        "location": {
          "city": "Brooklyn",
          "stateProvinceName": "New York"
        },
        "postalCode": "11229",
        "countryRegionName": "United States"
      },
      "id": "8d7ad239-2148-4fab-901b-17a85d331056",
      "_rid": "kV5oANVXnwDHPgAAAAAAAA==",
      "_ts": 1450037545,
      "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDHPgAAAAAAAA==/",
      "_etag": ""000070ce-0000-0000-0000-566dd1290000"",
      "_attachments": "attachments/"
    }
    Created document 8d7ad239-2148-4fab-901b-17a85d331056 from JSON string
    Created new document: 49f399a8-80c9-4844-ac28-cd1dee689968
    {
      "id": "49f399a8-80c9-4844-ac28-cd1dee689968",
      "name": "New Customer 3",
      "address": {
        "addressType": "Main Office",
        "addressLine1": "123 Main Street",
        "location": {
          "city": "Brooklyn",
          "stateProvinceName": "New York"
        },
        "postalCode": "11229",
        "countryRegionName": "United States"
      },
      "_rid": "kV5oANVXnwDIPgAAAAAAAA==",
      "_ts": 1450037546,
      "_self": "dbs/kV5oAA==/colls/kV5oANVXnwA=/docs/kV5oANVXnwDIPgAAAAAAAA==/",
      "_etag": ""000071ce-0000-0000-0000-566dd12a0000"",
      "_attachments": "attachments/"
    }
    Created document 49f399a8-80c9-4844-ac28-cd1dee689968 from typed object
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Update Document nhận dự án làm có lương

    DocumentDB – Update Document



    In this chapter, we will learn how to update the documents. Using Azure portal, you can easily update document by opening the document in Document explorer and updating it in editor like a text file.

    Update Document

    Click ‘Save’ button. Now when you need to change a document using .Net SDK you can just replace it. You don”t need to delete and recreate it, which besides being tedious, would also change the resource id, which you wouldn”t want to do when you”re just modifying a document. Here are the following steps to update the document using .Net SDK.

    Let’s take a look at the following ReplaceDocuments task where we will query for documents where the isNew property is true, but we will get none because there aren”t any. So, let”s modify the documents we added earlier, those whose names start with New Customer.

    Step 1 − Add the isNew property to these documents and set its value to true.

    private async static Task ReplaceDocuments(DocumentClient client) {
    
       Console.WriteLine();
       Console.WriteLine(">>> Replace Documents <<<");
       Console.WriteLine();
       Console.WriteLine("Quering for documents with ''isNew'' flag");
    
       var sql = "SELECT * FROM c WHERE c.isNew = true";
       var documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();
    
       Console.WriteLine("Documents with ''isNew'' flag: {0} ", documents.Count);
       Console.WriteLine();
       Console.WriteLine("Quering for documents to be updated");
    
       sql = "SELECT * FROM c WHERE STARTSWITH(c.name, ''New Customer'') = true";
       documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();
       Console.WriteLine("Found {0} documents to be updated", documents.Count);
    
       foreach (var document in documents) {
          document.isNew = true;
          var result = await client.ReplaceDocumentAsync(document._self, document);
          var updatedDocument = result.Resource;
          Console.WriteLine("Updated document ''isNew'' flag: {0}", updatedDocument.isNew);
       }
    
       Console.WriteLine();
       Console.WriteLine("Quering for documents with ''isNew'' flag");
    
       sql = "SELECT * FROM c WHERE c.isNew = true";
       documents = client.CreateDocumentQuery(collection.SelfLink, sql).ToList();
       Console.WriteLine("Documents with ''isNew'' flag: {0}: ", documents.Count);
       Console.WriteLine();
    }
    

    Step 2 − Get the documents to be updated using the same STARTSWITH query and that gives us the documents, which we are getting back here as dynamic objects.

    Step 3 − Attach the isNew property and set it to true for each document.

    Step 4 − Call ReplaceDocumentAsync, passing in the document”s SelfLink, along with the updated document.

    Now just to prove that this worked, query for documents where isNew equaled true. Let’s call the above queries from the CreateDocumentClient task.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
    
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          //await CreateDocuments(client);
          //QueryDocumentsWithSql(client);
          //await QueryDocumentsWithPaging(client);
          //QueryDocumentsWithLinq(client);
          await ReplaceDocuments(client);
       }
    
    }
    

    When the above code is compiled and executed, you will receive the following output.

    **** Replace Documents ****
    Quering for documents with ''isNew'' flag
    Documents with ''isNew'' flag: 0
    Quering for documents to be updated
    Found 2 documents to be updated
    Updated document ‘isNew’ flag: True
    Updated document ‘isNew’ flag: True
    Quering for documents with ''isNew'' flag
    Documents with ''isNew'' flag: 2
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Delete Document nhận dự án làm có lương

    DocumentDB – Delete Document



    In this chapter, we will learn how to delete a document from your DocumentDB account. Using Azure Portal, you can easily delete any document by opening the document in Document Explorer and click the ‘Delete’ option.

    Delete Document

    Delete Document Dialog

    It will display the confirmation message. Now press the Yes button and you will see that the document is no longer available in your DocumentDB account.

    Now when you want to delete a document using .Net SDK.

    Step 1 − It”s the same pattern as we”ve seen before where we”ll query first to get the SelfLinks of each new document. We don”t use SELECT * here, which would return the documents in their entirety, which we don”t need.

    Step 2 − Instead we”re just selecting the SelfLinks into a list and then we just call DeleteDocumentAsync for each SelfLink, one at a time, to delete the documents from the collection.

    private async static Task DeleteDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine(">>> Delete Documents <<<");
       Console.WriteLine();
       Console.WriteLine("Quering for documents to be deleted");
    
       var sql =
          "SELECT VALUE c._self FROM c WHERE STARTSWITH(c.name, ''New Customer'') = true";
    
       var documentLinks =
          client.CreateDocumentQuery<string>(collection.SelfLink, sql).ToList();
    
       Console.WriteLine("Found {0} documents to be deleted", documentLinks.Count);
    
       foreach (var documentLink in documentLinks) {
          await client.DeleteDocumentAsync(documentLink);
       }
    
       Console.WriteLine("Deleted {0} new customer documents", documentLinks.Count);
       Console.WriteLine();
    }
    

    Step 3 − Now let’s call the above DeleteDocuments from the CreateDocumentClient task.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          await DeleteDocuments(client);
       }
    }
    

    When the above code is executed, you will receive the following output.

    ***** Delete Documents *****
    Quering for documents to be deleted
    Found 2 documents to be deleted
    Deleted 2 new customer documents
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Insert Document nhận dự án làm có lương

    DocumentDB – Insert Document



    In this chapter, we will get to work with actual documents in a collection. You can create documents using either Azure portal or .Net SDK.

    Creating Documents with the Azure Portal

    Let’s take a look at the following steps to add document to your collection.

    Step 1 − Add new collection Families of S1 pricing tier in myfirstdb.

    Insert Document

    Step 2 − Select the Families collection and click on Create Document option to open the New Document blade.

    Families Collection

    This is just a simple text editor that lets you type any JSON for a new document.

    simple text editor

    Step 3 − As this is raw data entry, let’s enter our first document.

    {
       "id": "AndersenFamily",
       "lastName": "Andersen",
    
       "parents": [
          { "firstName": "Thomas", "relationship": "father" },
          { "firstName": "Mary Kay", "relationship": "mother" }
       ],
    
       "children": [
          {
             "firstName": "Henriette Thaulow",
             "gender": "female",
             "grade": 5,
             "pets": [ { "givenName": "Fluffy", "type": "Rabbit" } ]
          }
       ],
    
       "location": { "state": "WA", "county": "King", "city": "Seattle"},
       "isRegistered": true
    }
    

    When you enter the above document, you will see the following screen.

    Document

    Notice that we”ve supplied an id for the document. The id value is always required, and it must be unique across all other documents in the same collection. When you leave it out then DocumentDB would automatically generate one for you using a GUID or a Globally Unique Identifier.

    The id is always a string and it can”t be a number, date, Boolean, or another object, and it can”t be longer than 255 characters.

    Also notice the document”s hierarchal structure which has a few top-level properties like the required id, as well as lastName and isRegistered, but it also has nested properties.

    For instance, the parents property is supplied as a JSON array as denoted by the square brackets. We also have another array for children, even though there”s only one child in the array in this example.

    Step 4 − Click ‘Save’ button to save the document and we”ve created our first document.

    As you can see that pretty formatting was applied to our JSON, which breaks up every property on its own line indented with a whitespace to convey the nesting level of each property.

    Save Document

    The portal includes a Document Explorer, so let”s use that now to retrieve the document we just created.

    Retrieve Document

    Step 5 − Choose a database and any collection within the database to view the documents in that collection. We currently have just one database named myfirstdb with one collection called Families, both of which have been preselected here in the dropdowns.

    choose a Database

    By default, the Document Explorer displays an unfiltered list of documents within the collection, but you can also search for any specific document by ID or multiple documents based on a wildcard search of a partial ID.

    We have only one document in our collection so far, and we see its ID on the following screen, AndersonFamily.

    Step 6 − Click on the ID to view the document.

    Click on ID

    Creating Documents with the .NET SDK

    As you know that documents are just another type of resource and you”ve already become familiar with how to treat resources using the SDK.

    • The one big difference between documents and other resources is that, of course, they”re schema free.

    • Thus there are a lot of options. Naturally, you can just work JSON object graphs or even raw strings of JSON text, but you can also use dynamic objects that lets you bind to properties at runtime without defining a class at compile time.

    • You can also work with real C# objects, or Entities as they are called, which might be your business domain classes.

    Let’s start to create documents using .Net SDK. Following are the steps.

    Step 1 − Instantiate DocumentClient then we will query for the myfirstdb database and then query for the MyCollection collection, which we store in this private variable collection so that it”s accessible throughout the class.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
    
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          await CreateDocuments(client);
       }
    }
    

    Step 2 − Create some documents in CreateDocuments task.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       dynamic document1Definition = new {
          name = "New Customer 1", address = new {
             addressType = "Main Office",
             addressLine1 = "123 Main Street",
             location = new {
                city = "Brooklyn", stateProvinceName = "New York"
             }, postalCode = "11229", countryRegionName = "United States"
          },
       };
    
       Document document1 = await CreateDocument(client, document1Definition);
       Console.WriteLine("Created document {0} from dynamic object", document1.Id);
       Console.WriteLine();
    }
    

    The first document will be generated from this dynamic object. This might look like JSON, but of course it isn”t. This is C# code and we”re creating a real .NET object, but there”s no class definition. Instead, the properties are inferred from the way the object is initialized.

    Notice that we haven”t supplied an Id property for this document.

    Now let”s have a look into CreateDocument. It looks like the same pattern we saw for creating databases and collections.

    private async static Task<Document> CreateDocument(DocumentClient client,
       object documentObject) {
    
       var result = await client.CreateDocumentAsync(collection.SelfLink, documentObject);
       var document = result.Resource;
    
       Console.WriteLine("Created new document: {0}rn{1}", document.Id, document);
       return result;
    }
    

    Step 3 − This time we call CreateDocumentAsync specifying the SelfLink of the collection we want to add the document to. We get back a response with a resource property that, in this case, represents the new document with its system-generated properties.

    The Document object is a defined class in the SDK that inherits from resource and so it has all the common resource properties, but it also includes the dynamic properties that define the schema-free document itself.

    private async static Task CreateDocuments(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents ****");
       Console.WriteLine();
    
       dynamic document1Definition = new {
          name = "New Customer 1", address = new {
             addressType = "Main Office",
             addressLine1 = "123 Main Street",
             location = new {
                city = "Brooklyn", stateProvinceName = "New York"
             }, postalCode = "11229", countryRegionName = "United States"
          },
       };
    
       Document document1 = await CreateDocument(client, document1Definition);
       Console.WriteLine("Created document {0} from dynamic object", document1.Id);
       Console.WriteLine();
    }
    

    When the above code is compiled and executed you will receive the following output.

    **** Create Documents ****
    Created new document: 34e9873a-94c8-4720-9146-d63fb7840fad {
       "name": "New Customer 1",
    
       "address": {
          "addressType": "Main Office",
          "addressLine1": "123 Main Street",
          "location": {
             "city": "Brooklyn", "stateProvinceName": "New York"
          },
          "postalCode": "11229", "countryRegionName": "United States"
       },
    
       "id": "34e9873a-94c8-4720-9146-d63fb7840fad",
       "_rid": "Ic8LAMEUVgACAAAAAAAAAA==",
       "_ts": 1449812756,
       "_self": "dbs/Ic8LAA==/colls/Ic8LAMEUVgA=/docs/Ic8LAMEUVgACAAAAAAAAAA==/",
       "_etag": ""00001000-0000-0000-0000-566a63140000"",
       "_attachments": "attachments/"
    }
    Created document 34e9873a-94c8-4720-9146-d63fb7840fad from dynamic object
    

    As you can see, we haven’t supplied an Id, however DocumentDB generated this one for us for the new document.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Delete Collection nhận dự án làm có lương

    DocumentDB – Delete Collection



    To drop collection or collections you can do the same from the portal as well as from the code by using .Net SDK.

    Step 1 − Go to your DocumentDB account on Azure portal. For the purpose of demo, I have added two more collections as seen in the following screenshot.

    Delete Collection

    Step 2 − To drop any collection, you need to click on that collection. Let’s select TempCollection1. You will see the following page, select the ‘Delete Collection’ option.

    Select Collection

    Step 3 − It will display the confirmation message. Now click ‘Yes’ button.

    Delete Collection Message

    You will see that the TempCollection1 is no more available on your dashboard.

    Collection Deleted

    You can also delete collections from your code using .Net SDK. To do that, following are the following steps.

    Step 1 − Let”s delete the collection by specifying the ID of the collection we want to delete.

    It”s the usual pattern of querying by Id to obtain the selfLinks needed to delete a resource.

    private async static Task DeleteCollection(DocumentClient client, string collectionId) {
       Console.WriteLine();
       Console.WriteLine("**** Delete Collection {0} in {1} ****", collectionId, database.Id);
    
       var query = new SqlQuerySpec {
          QueryText = "SELECT * FROM c WHERE c.id = @id",
             Parameters = new SqlParameterCollection {
             new SqlParameter {
                Name = "@id", Value = collectionId
             }
          }
       };
    
       DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink,
          query).AsEnumerable().First();
    
       await client.DeleteDocumentCollectionAsync(collection.SelfLink);
       Console.WriteLine("Deleted collection {0} from database {1}", collectionId,
          database.Id);
    }
    

    Here we see the preferred way of constructing a parameterized query. We”re not hardcoding the collectionId so this method can be used to delete any collection. We are querying for a specific collection by Id where the Id parameter is defined in this SqlParameterCollection assigned to the parameter”s property of this SqlQuerySpec.

    Then the SDK does the work of constructing the final query string for DocumentDB with the collectionId embedded inside of it.

    Step 2 − Run the query and then use its SelfLink to delete the collection from the CreateDocumentClient task.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
    
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
             ''myfirstdb''").AsEnumerable().First();
          await DeleteCollection(client, "TempCollection");
       }
    }
    

    Following is the complete implementation of Program.cs file.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Microsoft.Azure.Documents.Linq;
    
    using Newtonsoft.Json;
    
    namespace DocumentDBDemo {
    
       class Program {
    
          private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
    
          private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
             StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    
          private static Database database;
    
          static void Main(string[] args) {
             try {
                CreateDocumentClient().Wait();
             } catch (Exception e) {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
             }
             Console.ReadKey();
          }
    
          private static async Task CreateDocumentClient() {
             // Create a new instance of the DocumentClient
             using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
                database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id =
                   ''myfirstdb''").AsEnumerable().First();
                await DeleteCollection(client, "TempCollection");
    
                //await CreateCollection(client, "MyCollection1");
                //await CreateCollection(client, "MyCollection2", "S2");
                ////await CreateDatabase(client);
                //GetDatabases(client);
                //await DeleteDatabase(client);
                //GetDatabases(client);
             }
          }
    
          private async static Task CreateCollection(DocumentClient client,
             string collectionId, string offerType = "S1") {
    
             Console.WriteLine();
             Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId,
                database.Id);
    
             var collectionDefinition = new DocumentCollection { Id = collectionId };
             var options = new RequestOptions { OfferType = offerType };
             var result = await client.CreateDocumentCollectionAsync(database.SelfLink,
                collectionDefinition, options);
    
             var collection = result.Resource;
    
             Console.WriteLine("Created new collection");
             ViewCollection(collection);
          }
    
          private static void ViewCollection(DocumentCollection collection) {
             Console.WriteLine("Collection ID: {0} ", collection.Id);
             Console.WriteLine("Resource ID: {0} ", collection.ResourceId);
             Console.WriteLine("Self Link: {0} ", collection.SelfLink);
             Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink);
             Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink);
             Console.WriteLine("StoredProcs Link: {0} ", collection.StoredProceduresLink);
             Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink);
             Console.WriteLine("Timestamp: {0} ", collection.Timestamp);
          }
    
          private async static Task DeleteCollection(DocumentClient client,
             string collectionId) {
    
             Console.WriteLine();
             Console.WriteLine("**** Delete Collection {0} in {1} ****", collectionId,
                database.Id);
    
             var query = new SqlQuerySpec {
                QueryText = "SELECT * FROM c WHERE c.id = @id", Parameters = new
                   SqlParameterCollection {
                   new SqlParameter {
                      Name = "@id", Value = collectionId
                   }
                }
             };
    
             DocumentCollection collection = client.CreateDocumentCollectionQuery
                (database.SelfLink, query).AsEnumerable().First();
    
             await client.DeleteDocumentCollectionAsync(collection.SelfLink);
             Console.WriteLine("Deleted collection {0} from database {1}", collectionId,
                database.Id);
          }
    
       }
    }
    

    When the above code is compiled and executed, you will receive the following output.

    **** Delete Collection TempCollection in myfirstdb ****
    Deleted collection TempCollection from database myfirstdb
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Drop Databases nhận dự án làm có lương

    DocumentDB – Drop Databases



    You can drop a database or databases from the portal as well as from the code by using .Net SDK. Here, we will discuss, in a step-wise manner, how to drop a database in DocumentDB.

    Step 1 − Go to your DocumentDB account on Azure portal. For the purpose of demo, I have added two more databases as seen in the following screenshot.

    Drop Databases

    Step 2 − To drop any database, you need to click that database. Let’s select tempdb, you will see the following page, select the ‘Delete Database’ option.

    Delete Database

    Step 3 − It will display the confirmation message, now click the ‘Yes’ button.

    Confirmation Message

    You will see that the tempdb is no more available in your dashboard.

    TempDB Deleted

    You can also delete databases from your code using .Net SDK. To do following are the steps.

    Step 1 − Let”s delete the database by specifying the ID of the database we want to delete, but we need its SelfLink.

    Step 2 − We are calling the CreateDatabaseQuery like before, but this time we are actually supplying a query to return just the one database with the ID tempdb1.

    private async static Task DeleteDatabase(DocumentClient client) {
       Console.WriteLine("******** Delete Database ********");
       Database database = client
          .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''tempdb1''")
          .AsEnumerable()
          .First();
       await client.DeleteDatabaseAsync(database.SelfLink);
    }
    

    Step 3 − This time, we can call AsEnumerable instead of ToList() because we don”t actually need a list object. Expecting only result, calling AsEnumerable is sufficient so that we can get the first database object returned by the query with First(). This is the database object for tempdb1 and it has a SelfLink that we can use to call DeleteDatabaseAsync which deletes the database.

    Step 4 − You also need to call DeleteDatabase task from the CreateDocumentClient task after DocumentClient is instantiated.

    Step 5 − To view the list of databases after deleting the specified database, let’s call GetDatabases method again.

    using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
       //await CreateDatabase(client);
    
       GetDatabases(client);
       await DeleteDatabase(client);
       GetDatabases(client);
    }
    

    Following is the complete Program.cs file so far.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Microsoft.Azure.Documents.Linq;
    using Newtonsoft.Json;
    
    namespace DocumentDBDemo {
    
       class Program {
    
          private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
    
          private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
             StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    
          static void Main(string[] args) {
             try {
                CreateDocumentClient().Wait();
             } catch (Exception e) {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
             }
             Console.ReadKey();
          }
    
          private static async Task CreateDocumentClient() {
             // Create a new instance of the DocumentClient
             using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
                //await CreateDatabase(client);
                GetDatabases(client);
                await DeleteDatabase(client);
                GetDatabases(client);
             }
          }
    
          private async static Task CreateDatabase(DocumentClient client) {
             Console.WriteLine();
             Console.WriteLine("******** Create Database *******");
    
             var databaseDefinition = new Database { Id = "mynewdb" };
             var result = await client.CreateDatabaseAsync(databaseDefinition);
             var database = result.Resource;
    
             Console.WriteLine(" Database Id: {0}; Rid: {1}",
                database.Id, database.ResourceId);
             Console.WriteLine("******** Database Created *******");
          }
    
          private static void GetDatabases(DocumentClient client) {
             Console.WriteLine();
             Console.WriteLine();
             Console.WriteLine("******** Get Databases List ********");
    
             var databases = client.CreateDatabaseQuery().ToList();
    
             foreach (var database in databases) {
                Console.WriteLine(" Database Id: {0}; Rid: {1}", database.Id,
                   database.ResourceId);
             }
    
             Console.WriteLine();
             Console.WriteLine("Total databases: {0}", databases.Count);
          }
    
          private async static Task DeleteDatabase(DocumentClient client) {
             Console.WriteLine();
             Console.WriteLine("******** Delete Database ********");
    
             Database database = client
                .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = ''tempdb1''")
                .AsEnumerable()
                .First();
             await client.DeleteDatabaseAsync(database.SelfLink);
          }
    
       }
    }
    

    When the above code is compiled and executed, you will receive the following output which contains the Database and Resources IDs of the three databases and total number of databases.

    ******** Get Databases List ********
     Database Id: myfirstdb; Rid: Ic8LAA==
     Database Id: mynewdb; Rid: ltpJAA==
     Database Id: tempdb1; Rid: 06JjAA==
    
    Total databases: 3
    
    ******** Delete Database ********
    
    ******** Get Databases List ********
     Database Id: myfirstdb; Rid: Ic8LAA==
     Database Id: mynewdb; Rid: ltpJAA==
    
    Total databases: 2
    

    After deleting the database, you will also see at the end that only two databases are left in DocumentDB account.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí DocumentDB – Connect Account nhận dự án làm có lương

    DocumentDB – Connect Account



    When you start programming against DocumentDB, the very first step is to connect. So to connect to your DocumentDB account you will need two things;

    • Endpoint
    • Authorization Key

    Endpoint

    Endpoint is the URL to your DocumentDB account and it is constructed by combining your DocumentDB account name with .documents.azure.com. Let’s go to the Dashboard.

    Endpoint

    Now, click on the created DocumentDB account. You will see the details as shown in the following image.

    click on created DocumentDB

    When you select the ‘Keys’ option, it will display additional information as shown in the following image. You will also see the URL to your DocumentDB account, which you can use as your endpoint.

    select keys option

    Authorization Key

    Authorization key contains your credentials and there are two types of keys. The master key allows full access to all resources within the account, while resource tokens permit restricted access to specific resources.

    Master Keys

    • There”s nothing you can”t do with a master key. You can blow away your entire database if you want, using the master key.

    • For this reason, you definitely don”t want to be sharing the master key or distributing it to client environments. As an added security measure, it”s a good idea to change it frequently.

    • There are actually two master keys for each database account, the primary and the secondary as highlighted in the above screenshot.

    Resource Tokens

    • You can also use resource tokens instead of a master key.

    • Connections based on resource tokens can only access the resources specified by the tokens and no other resources.

    • Resource tokens are based on user permissions, so first you create one or more users, and these are defined at the database level.

    • You create one or more permissions for each user, based on the resources that you want to allow each user to access.

    • Each permission generates a resource token that allows either read-only or full access to a given resource and that can be any user resource within the database.

    Let’s go to console application created in chapter 3.

    Step 1 − Add the following references in the Program.cs file.

    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Microsoft.Azure.Documents.Linq;
    using Newtonsoft.Json;
    

    Step 2 − Now add Endpoint URL and Authorization key. In this example we will be using primary key as Authorization key.

    Note that in your case both Endpoint URL and authorization key should be different.

    private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
    private const string AuthorizationKey =
       "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    

    Step 3 − Create a new instance of the DocumentClient in asynchronous task called CreateDocumentClient and instantiate new DocumentClient.

    Step 4 − Call your asynchronous task from your Main method.

    Following is the complete Program.cs file so far.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using Microsoft.Azure.Documents.Linq;
    using Newtonsoft.Json;
    
    namespace DocumentDBDemo {
    
       class Program {
          private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
    
          private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
             StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
    
          static void Main(string[] args) {
             try {
                CreateDocumentClient().Wait();
             } catch (Exception e) {
                Exception baseException = e.GetBaseException();
                Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
             }
    
             Console.ReadKey();
          }
    
          private static async Task CreateDocumentClient() {
             // Create a new instance of the DocumentClient
             var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
          }
    
       }
    }
    

    In this chapter, we have learnt how to connect to a DocumentDB account and create an instance of the DocumentClient class.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc