Category: documentdb

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

    DocumentDB – Partitioning



    When your database starts to grow beyond 10GB, you can scale out simply by creating new collections and then spreading or partitioning your data across more and more collections.

    Sooner or later a single collection, which has a 10GB capacity, will not be enough to contain your database. Now 10GB may not sound like a very large number, but remember that we”re storing JSON documents, which is just plain text and you can fit a lot of plain text documents in 10GB, even when you consider the storage overhead for the indexes.

    Storage isn”t the only concern when it comes to scalability. The maximum throughput available on a collection is two and a half thousand request units per second that you get with an S3 collection. Hence, if you need higher throughput, then you will also need to scale out by partitioning with multiple collections. Scale out partitioning is also called horizontal partitioning.

    There are many approaches that can be used for partitioning data with Azure DocumentDB. Following are most common strategies −

    • Spillover Partitioning
    • Range Partitioning
    • Lookup Partitioning
    • Hash Partitioning

    Spillover Partitioning

    Spillover partitioning is the simplest strategy because there is no partition key. It”s often a good choice to start with when you”re unsure about a lot of things. You might not know if you”ll even ever need to scale out beyond a single collection or how many collections you may need to add or how fast you may need to add them.

    • Spillover partitioning starts with a single collection and there is no partition key.

    • The collection starts to grow and then grows some more, and then some more, until you start getting close to the 10GB limit.

    • When you reach 90 percent capacity, you spill over to a new collection and start using it for new documents.

    • Once your database scales out to a larger number of collections, you”ll probably want to shift to a strategy that”s based on a partition key.

    • When you do that you”ll need to rebalance your data by moving documents to different collections based on whatever strategy you”re migrating to.

    Range Partitioning

    One of the most common strategies is range partitioning. With this approach you determine the range of values that a document”s partition key might fall in and direct the document to a collection corresponding to that range.

    • Dates are very typically used with this strategy where you create a collection to hold documents that fall within the defined range of dates. When you define ranges that are small enough, where you”re confident that no collection will ever exceed its 10GB limit. For example, there may be a scenario where a single collection can reasonably handle documents for an entire month.

    • It may also be the case that most users are querying for current data, which would be data for this month or perhaps last month, but users are rarely searching for much older data. So you start off in June with an S3 collection, which is the most expensive collection you can buy and delivers the best throughput you can get.

    • In July you buy another S3 collection to store the July data and you also scale the June data down to a less-expensive S2 collection. Then in August, you get another S3 collection and scale July down to an S2 and June all the way down to an S1. It goes, month after month, where you”re always keeping the current data available for high throughput and older data is kept available at lower throughputs.

    • As long as the query provides a partition key, only the collection that needs to be queried will get queried and not all the collections in the database like it happens with spillover partitioning.

    Lookup Partitioning

    With lookup partitioning you can define a partition map that routes documents to specific collections based on their partition key. For example, you could partition by region.

    • Store all US documents in one collection, all European documents in another collection, and all documents from any other region in a third collection.

    • Use this partition map and a lookup partition resolver can figure out which collection to create a document in and which collections to query, based on the partition key, which is the region property contained in each document.

    Hash Partitioning

    In hash partitioning, partitions are assigned based on the value of a hash function, allowing you to evenly distribute requests and data across a number of partitions.

    This is commonly used to partition data produced or consumed from a large number of distinct clients, and is useful for storing user profiles, catalog items, etc.

    Let’s take a look at a simple example of range partitioning using the RangePartitionResolver supplied by the .NET SDK.

    Step 1 − Create a new DocumentClient and we will create two collections in CreateCollections task. One will contain documents for users that have user IDs beginning with A through M and the other for user IDs N through Z.

    private static async Task CreateCollections(DocumentClient client) {
       await client.CreateDocumentCollectionAsync(“dbs/myfirstdb”, new DocumentCollection {
          Id = “CollectionAM” });
    
       await client.CreateDocumentCollectionAsync(“dbs/myfirstdb”, new DocumentCollection {
          Id = “CollectionNZ” });
    }
    

    Step 2 − Register the range resolver for the database.

    Step 3 − Create a new RangePartitionResolver<string>, which is the datatype of our partition key. The constructor takes two parameters, the property name of the partition key and a dictionary that is the shard map or partition map, which is just a list of the ranges and corresponding collections that we are predefining for the resolver.

    private static void RegisterRangeResolver(DocumentClient client) {
    
       //Note: uffff is the largest UTF8 value, so Mufff includes all strings that start with M.
    
       var resolver = new RangePartitionResolver<string>(
          "userId", new Dictionary<Range<string>, string>() {
          { new Range<string>("A", "Muffff"), "dbs/myfirstdb/colls/CollectionAM" },
          { new Range<string>("N", "Zuffff"), "dbs/myfirstdb/colls/CollectionNZ" },
       });
    
       client.PartitionResolvers["dbs/myfirstdb"] = resolver;
     }
    

    It”s necessary to encode the largest possible UTF-8 value here. Or else the first range wouldn”t match on any Ms except the one single M, and likewise for Z in the second range. So, you can just think of this encoded value here as a wildcard for matching on the partition key.

    Step 4 − After creating the resolver, register it for the database with the current DocumentClient. To do that just assign it to the PartitionResolver”s dictionary property.

    We”ll create and query for documents against the database, not a collection as you normally do, the resolver will use this map to route requests to the appropriate collections.

    Now let”s create some documents. First we will create one for userId Kirk, and then one for Spock.

    private static async Task CreateDocumentsAcrossPartitions(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** Create Documents Across Partitions ****");
    
       var kirkDocument = await client.CreateDocumentAsync("dbs/myfirstdb", new { userId =
          "Kirk", title = "Captain" });
       Console.WriteLine("Document 1: {0}", kirkDocument.Resource.SelfLink);
    
       var spockDocument = await client.CreateDocumentAsync("dbs/myfirstdb", new { userId =
          "Spock", title = "Science Officer" });
       Console.WriteLine("Document 2: {0}", spockDocument.Resource.SelfLink);
    }
    

    The first parameter here is a self-link to the database, not a specific collection. This is not possible without a partition resolver, but with one it just works seamlessly.

    Both documents were saved to the database myfirstdb, but we know that Kirk is being stored in the collection for A through M and Spock is being stored in the collection for N to Z, if our RangePartitionResolver is working properly.

    Let’s call these from the CreateDocumentClient task as shown in the following code.

    private static async Task CreateDocumentClient() {
       // Create a new instance of the DocumentClient
       using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
          await CreateCollections(client);
          RegisterRangeResolver(client);
          await CreateDocumentsAcrossPartitions(client);
       }
    }
    

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

    **** Create Documents Across Partitions ****
    Document 1: dbs/Ic8LAA==/colls/Ic8LAO2DxAA=/docs/Ic8LAO2DxAABAAAAAAAAAA==/
    Document 2: dbs/Ic8LAA==/colls/Ic8LAP12QAE=/docs/Ic8LAP12QAEBAAAAAAAAAA==/
    

    As seen the self-links of the two documents have different resource IDs because they exist in two separate collections.


    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 Migration nhận dự án làm có lương

    DocumentDB – Data Migration



    With the DocumentDB Data Migration tool, you can easily migrate data to DocumentDB. The DocumentDB Data Migration Tool is a free and open source utility you can download from the Microsoft Download Center

    The Migration Tool supports many data sources, some of them are listed below −

    • MongoDB
    • Azure Table Storage
    • Amazon DynamoDB
    • HBase, and even other DocumentDB databases

    After downloading the DocumentDB Data Migration tool, extract the zip file.

    You can see two executables in this folder as shown in the following screenshot.

    Executable Files

    First, there is dt.exe, which is the console version with a command line interface, and then there is dtui.exe, which is the desktop version with a graphical user interface.

    Let”s launch the GUI version.

    Launch GUI version

    You can see the Welcome page. Click ‘Next’ for the Source Information page.

    Source Information page

    Here”s where you configure your data source, and you can see the many supported choices from the dropdown menu.

    Specify Source Information

    When you make a selection, the rest of the Source Information page changes accordingly.

    It is very easy to import data to DocumentDB using the DocumentDB Data Migration Tool. We recommend you exercise the above examples and use the other data files as well.


    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 – Useful Resources nhận dự án làm có lương

    DocumentDB – Useful Resources



    The following resources contain additional information on DocumentDB. Please use them to get more in-depth knowledge on this topic.

    Useful Links on DocumentDB

    • − Reference for DocumentDB.

    • − Introduction Reference for DocumentDB.

    • − Wikipedia Reference for DocumentDB.

    Useful Books on DocumentDB

    To enlist your site on this page, please drop an email to contact@tutorialspoint.com


    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 – Discussion nhận dự án làm có lương

    Discuss DocumentDB



    DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. DocumentDB is designed keeping in mind the requirements of managing data for latest applications. This tutorial explains the basics of DocumentDB with illustrative examples.


    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 – Access Control nhận dự án làm có lương

    DocumentDB – Access Control



    DocumentDB provides the concepts to control access to DocumentDB resources. Access to DocumentDB resources is governed by a master key token or a resource token. 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.

    • First you create one or more users, and these are defined at the database level.

    • Then 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.

    • Users are defined at the database level and permissions are defined for each user.

    • Users and permissions apply to all collections in the database.

    Let’s take a look at a simple example in which we will learn how to define users and permissions to achieve granular security in DocumentDB.

    We will start with a new DocumentClient and query for the myfirstdb 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 =
             ''myfirstdb''").AsEnumerable().First();
    
          collection = client.CreateDocumentCollectionQuery(database.CollectionsLink,
             "SELECT * FROM c WHERE c.id = ''MyCollection''").AsEnumerable().First();
    
          var alice = await CreateUser(client, "Alice");
          var tom = await CreateUser(client, "Tom");
       }
    }
    

    Following is the implementation for CreateUser.

    private async static Task<User> CreateUser(DocumentClient client, string userId) {
       Console.WriteLine();
       Console.WriteLine("**** Create User {0} in {1} ****", userId, database.Id);
    
       var userDefinition = new User { Id = userId };
       var result = await client.CreateUserAsync(database.SelfLink, userDefinition);
       var user = result.Resource;
    
       Console.WriteLine("Created new user");
       ViewUser(user);
    
       return user;
    }
    

    Step 1 − Create two users, Alice and Tom like any resource we create, we construct a definition object with the desired Id and call the create method and in this case we”re calling CreateUserAsync with the database”s SelfLink and the userDefinition. We get back the result from whose resource property we obtain the newly created user object.

    Now to see these two new users in the database.

    private static void ViewUsers(DocumentClient client) {
       Console.WriteLine();
       Console.WriteLine("**** View Users in {0} ****", database.Id);
    
       var users = client.CreateUserQuery(database.UsersLink).ToList();
       var i = 0;
    
       foreach (var user in users) {
          i++;
          Console.WriteLine();
          Console.WriteLine("User #{0}", i);
          ViewUser(user);
       }
    
       Console.WriteLine();
       Console.WriteLine("Total users in database {0}: {1}", database.Id, users.Count);
    }
    
    private static void ViewUser(User user) {
       Console.WriteLine("User ID: {0} ", user.Id);
       Console.WriteLine("Resource ID: {0} ", user.ResourceId);
       Console.WriteLine("Self Link: {0} ", user.SelfLink);
       Console.WriteLine("Permissions Link: {0} ", user.PermissionsLink);
       Console.WriteLine("Timestamp: {0} ", user.Timestamp);
    }
    

    Step 2 − Call CreateUserQuery, against the database”s UsersLink to retrieve a list of all users. Then loop through them and view their properties.

    Now we have to create them first. So let”s say that we wanted to allow Alice read/write permissions to the MyCollection collection, but Tom can only read documents in the collection.

    await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All,
       collection);
    
    await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read,
       collection);
    

    Step 3− Create a permission on a resource that is MyCollection collection so we need to get that resource a SelfLink.

    Step 4 − Then create a Permission.All on this collection for Alice and a Permission.Read on this collection for Tom.

    Following is the implementation for CreatePermission.

    private async static Task CreatePermission(DocumentClient client, User user,
       string permId, PermissionMode permissionMode, string resourceLink) {
       Console.WriteLine();
       Console.WriteLine("**** Create Permission {0} for {1} ****", permId, user.Id);
    
       var permDefinition = new Permission {
          Id = permId,
          PermissionMode = permissionMode,
          ResourceLink = resourceLink
       };
    
       var result = await client.CreatePermissionAsync(user.SelfLink, permDefinition);
       var perm = result.Resource;
       Console.WriteLine("Created new permission");
       ViewPermission(perm);
    }
    

    As you should come to expect by now, we do this by creating a definition object for the new permission, which includes an Id and a permissionMode, which is either Permission.All or Permission.Read, and the SelfLink of the resource that”s being secured by the permission.

    Step 5 − Call CreatePermissionAsync and get the created permission from the resource property in the result.

    To view the created permission, following is the implementation of ViewPermissions.

    private static void ViewPermissions(DocumentClient client, User user) {
       Console.WriteLine();
       Console.WriteLine("**** View Permissions for {0} ****", user.Id);
    
       var perms = client.CreatePermissionQuery(user.PermissionsLink).ToList();
       var i = 0;
    
       foreach (var perm in perms) {
          i++;
          Console.WriteLine();
          Console.WriteLine("Permission #{0}", i);
          ViewPermission(perm);
       }
    
       Console.WriteLine();
       Console.WriteLine("Total permissions for {0}: {1}", user.Id, perms.Count);
    }
    
    private static void ViewPermission(Permission perm) {
       Console.WriteLine("Permission ID: {0} ", perm.Id);
       Console.WriteLine("Resource ID: {0} ", perm.ResourceId);
       Console.WriteLine("Permission Mode: {0} ", perm.PermissionMode);
       Console.WriteLine("Token: {0} ", perm.Token);
       Console.WriteLine("Timestamp: {0} ", perm.Timestamp);
    }
    

    This time, it”s a permission query against the user”s permissions link and we simply list each permission returned for the user.

    Let”s delete the Alice’s and Tom’s permissions.

    await DeletePermission(client, alice, "Alice Collection Access");
    await DeletePermission(client, tom, "Tom Collection Access");
    

    Following is the implementation for DeletePermission.

    private async static Task DeletePermission(DocumentClient client, User user,
       string permId) {
       Console.WriteLine();
       Console.WriteLine("**** Delete Permission {0} from {1} ****", permId, user.Id);
    
       var query = new SqlQuerySpec {
          QueryText = "SELECT * FROM c WHERE c.id = @id",
          Parameters = new SqlParameterCollection {
             new SqlParameter { Name = "@id", Value = permId }
          }
       };
    
       Permission perm = client.CreatePermissionQuery(user.PermissionsLink, query)
          .AsEnumerable().First();
       await client.DeletePermissionAsync(perm.SelfLink);
       Console.WriteLine("Deleted permission {0} from user {1}", permId, user.Id);
    }
    

    Step 6 − To delete permissions, query by permission Id to get the SelfLink, and then using the SelfLink to delete the permission.

    Next, let’s delete the users themselves. Let’s delete both the users.

    await DeleteUser(client, "Alice");
    await DeleteUser(client, "Tom");
    

    Following is the implementation for DeleteUser.

    private async static Task DeleteUser(DocumentClient client, string userId) {
       Console.WriteLine();
       Console.WriteLine("**** Delete User {0} in {1} ****", userId, database.Id);
    
       var query = new SqlQuerySpec {
          QueryText = "SELECT * FROM c WHERE c.id = @id",
          Parameters = new SqlParameterCollection {
             new SqlParameter { Name = "@id", Value = userId }
          }
       };
    
       User user = client.CreateUserQuery(database.SelfLink, query).AsEnumerable().First();
       await client.DeleteUserAsync(user.SelfLink);
       Console.WriteLine("Deleted user {0} from database {1}", userId, database.Id);
    }
    

    Step 7 − First query to get her SelfLink and then call DeleteUserAsync to delete her user object.

    Following is the implementation of CreateDocumentClient task in which we call all the above tasks.

    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();
    
          ViewUsers(client);
    
          var alice = await CreateUser(client, "Alice");
          var tom = await CreateUser(client, "Tom");
          ViewUsers(client);
    
          ViewPermissions(client, alice);
          ViewPermissions(client, tom);
    
          string collectionLink = client.CreateDocumentCollectionQuery(database.SelfLink,
             "SELECT VALUE c._self FROM c WHERE c.id = ''MyCollection''")
             .AsEnumerable().First().Value;
    
          await CreatePermission(client, alice, "Alice Collection Access", PermissionMode.All,
             collectionLink);
    
          await CreatePermission(client, tom, "Tom Collection Access", PermissionMode.Read,
             collectionLink);
    
          ViewPermissions(client, alice);
          ViewPermissions(client, tom);
    
          await DeletePermission(client, alice, "Alice Collection Access");
          await DeletePermission(client, tom, "Tom Collection Access");
    
          await DeleteUser(client, "Alice");
          await DeleteUser(client, "Tom");
       }
    }
    

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

    **** View Users in myfirstdb ****
    
    Total users in database myfirstdb: 0
    
    **** Create User Alice in myfirstdb ****
    Created new user
              User ID: Alice
          Resource ID: kV5oAC56NwA=
            Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/
     Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/
            Timestamp: 12/17/2015 5:44:19 PM
    
    **** Create User Tom in myfirstdb ****
    Created new user
              User ID: Tom
          Resource ID: kV5oAALxKgA=
            Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/
     Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/
            Timestamp: 12/17/2015 5:44:21 PM
    
    **** View Users in myfirstdb ****
    
    User #1
              User ID: Tom
          Resource ID: kV5oAALxKgA=
            Self Link: dbs/kV5oAA==/users/kV5oAALxKgA=/
     Permissions Link: dbs/kV5oAA==/users/kV5oAALxKgA=/permissions/
            Timestamp: 12/17/2015 5:44:21 PM
    
    User #2
              User ID: Alice
          Resource ID: kV5oAC56NwA=
            Self Link: dbs/kV5oAA==/users/kV5oAC56NwA=/
     Permissions Link: dbs/kV5oAA==/users/kV5oAC56NwA=/permissions/
            Timestamp: 12/17/2015 5:44:19 PM
    
    Total users in database myfirstdb: 2
    
    **** View Permissions for Alice ****
    
    Total permissions for Alice: 0
    
    **** View Permissions for Tom ****
    
    Total permissions for Tom: 0
    
    **** Create Permission Alice Collection Access for Alice ****
    Created new permission
        Permission ID: Alice Collection Access
          Resource ID: kV5oAC56NwDON1RduEoCAA==
      Permission Mode: All
                Token: type=resource&ver=1&sig=zB6hfvvleC0oGGbq5cc67w==;Zt3Lx
    Ol14h8pd6/tyF1h62zbZKk9VwEIATIldw4ZyipQGW951kirueAKdeb3MxzQ7eCvDfvp7Y/ZxFpnip/D G
    JYcPyim5cf+dgLvos6fUuiKSFSul7uEKqp5JmJqUCyAvD7w+qt1Qr1PmrJDyAIgbZDBFWGe2VT9FaBH o
    PYwrLjRlnH0AxfbrR+T/UpWMSSHtLB8JvNFZNSH8hRjmQupuTSxCTYEC89bZ/pS6fNmNg8=;
            Timestamp: 12/17/2015 5:44:28 PM
    
    **** Create Permission Tom Collection Access for Tom ****
    Created new permission
        Permission ID: Tom Collection Access
          Resource ID: kV5oAALxKgCMai3JKWdfAA==
      Permission Mode: Read
                Token: type=resource&ver=1&sig=ieBHKeyi6EY9ZOovDpe76w==;92gwq
    V4AxKaCJ2dLS02VnJiig/5AEbPcfo1xvOjR10uK3a3FUMFULgsaK8nzxdz6hLVCIKUj6hvMOTOSN8Lt 7
    i30mVqzpzCfe7JO3TYSJEI9D0/5HbMIEgaNJiCu0JPPwsjVecTytiLN56FHPguoQZ7WmUAhVTA0IMP6 p
    jQpLDgJ43ZaG4Zv3qWJiO689balD+egwiU2b7RICH4j6R66UVye+GPxq/gjzqbHwx79t54=;
            Timestamp: 12/17/2015 5:44:30 PM
    
    **** View Permissions for Alice ****
    
    Permission #1
        Permission ID: Alice Collection Access
          Resource ID: kV5oAC56NwDON1RduEoCAA==
      Permission Mode: All
                Token: type=resource&ver=1&sig=BSzz/VNe9j4IPJ9M31Mf4Q==;Tcq/B
    X50njB1vmANZ/4aHj/3xNkghaqh1OfV95JMi6j4v7fkU+gyWe3mJasO3MJcoop9ixmVnB+RKOhFaSxE l
    P37SaGuIIik7GAWS+dcEBWglMefc95L2YkeNuZsjmmW5b+a8ELCUg7N45MKbpzkp5BrmmGVJ7h4Z4pf D
    rdmehYLuxSPLkr9ndbOOrD8E3bux6TgXCsgYQscpIlJHSKCKHUHfXWBP2Y1LV2zpJmRjis=;
            Timestamp: 12/17/2015 5:44:28 PM
    
    Total permissions for Alice: 1
    
    **** View Permissions for Tom ****
    Permission #1
        Permission ID: Tom Collection Access
          Resource ID: kV5oAALxKgCMai3JKWdfAA==
      Permission Mode: Read
                Token: type=resource&ver=1&sig=NPkWNJp1mAkCASE8KdR6PA==;ur/G2
    V+fDamBmzECux000VnF5i28f8WRbPwEPxD1DMpFPqYcu45wlDyzT5A5gBr3/R3qqYkEVn8bU+een6Gl j
    L6vXzIwsZfL12u/1hW4mJT2as2PWH3eadry6Q/zRXHAxV8m+YuxSzlZPjBFyJ4Oi30mrTXbBAEafZhA 5
    yvbHkpLmQkLCERy40FbIFOzG87ypljREpwWTKC/z8RSrsjITjAlfD/hVDoOyNJwX3HRaz4=;
            Timestamp: 12/17/2015 5:44:30 PM
    
    Total permissions for Tom: 1
    
    **** Delete Permission Alice Collection Access from Alice ****
    Deleted permission Alice Collection Access from user Alice
    
    **** Delete Permission Tom Collection Access from Tom ****
    Deleted permission Tom Collection Access from user Tom
    
    **** Delete User Alice in myfirstdb ****
    Deleted user Alice from database myfirstdb
    
    **** Delete User Tom in myfirstdb ****
    Deleted user Tom 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 – 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 – 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 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 – Home nhận dự án làm có lương

    DocumentDB tutorial

    DocumentDB Tutorial







    DocumentDB is Microsoft”s newest NoSQL document database platform that runs on Azure. DocumentDB is designed keeping in mind the requirements of managing data for latest applications. This tutorial explains the basics of DocumentDB with illustrative examples.

    Audience

    This tutorial is designed for beginners, i.e., for developers who want to get acquainted with how DocumentDB works.

    Prerequisites

    It is an elementary tutorial that explains the basics of DocumentDB and there are no prerequisites as such. However, it will certainly help if you have some prior exposure to NoSQL technologies.

    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 – List Databases nhận dự án làm có lương

    DocumentDB – List Databases



    So far, we have created two databases in our DocumentDB account, first one is created using Azure portal while the second database is created using .Net SDK. Now to view these databases, you can use Azure portal.

    Go to your DocumentDB account on Azure portal and you will see two databases now.

    Two Databases

    You can also view or list the databases from your code using .Net SDK. Following are the steps involved.

    Step 1 − Issue a database Query with no parameters which returns a complete list, but you can also pass in a query to look for a specific database or specific databases.

    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);
    }
    

    You will see that there are a bunch of these CreateQuery methods for locating collections, documents, users, and other resources. These methods don”t actually execute the query, they just define the query and return an iterateable object.

    It”s the call to ToList() that actually executes the query, iterates the results, and returns them in a list.

    Step 2 − Call GetDatabases method from the CreateDocumentClient task after DocumentClient is instantiated.

    Step 3 − You also need to comment the CreateDatabase task or change the database id, otherwise you will get an error message that the database exists.

    using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) {
       //await CreateDatabase(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);
             }
          }
    
          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);
          }
    
       }
    }
    

    When the above code is compiled and executed you will receive the following output which contains the Database and Resources IDs of both the databases. In the end you will also see the total number of databases.

    ******** Get Databases List ********
     Database Id: myfirstdb; Rid: Ic8LAA==
     Database Id: mynewdb; Rid: ltpJAA==
    Total databases: 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