public async Task<bool> WriteDocument(MessageType type, String jsonString) { var client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentServiceEndpoint"]), ConfigurationManager.AppSettings["DocumentKey"]); var dbName = ConfigurationManager.AppSettings["DocumentDatabase"]; var database = client.CreateDatabaseQuery().Where(db => db.Id == dbName).AsEnumerable().FirstOrDefault() ?? await client.CreateDatabaseAsync(new Database{ Id = dbName}); // Check to verify a document collection with the does not exist var docCollection = ConfigurationManager.AppSettings["DocumentCollection"]; var documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == docCollection).AsEnumerable().FirstOrDefault() ?? await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = docCollection }); var id = Guid.NewGuid().ToString(); var response = HttpStatusCode.Unused; switch (type) { case MessageType.Energy: var energyDoc = JsonConvert.DeserializeObject<EnergyDocument>(jsonString); energyDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, energyDoc)).StatusCode; break; case MessageType.Humidity: var humidityDoc = JsonConvert.DeserializeObject<HumidityDocument>(jsonString); humidityDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, humidityDoc)).StatusCode; break; case MessageType.Light: var lightDoc = JsonConvert.DeserializeObject<LightDocument>(jsonString); lightDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, lightDoc)).StatusCode; break; case MessageType.Temperature: var tempDoc = JsonConvert.DeserializeObject<TemperatureDocument>(jsonString); tempDoc.id = id; response = (await client.CreateDocumentAsync(documentCollection.DocumentsLink, tempDoc)).StatusCode; break; } return response == HttpStatusCode.Created; }
public async Task <DocumentDBResultDto> CreateDocument(CosmosDBDocument document) { var result = await _cosmosDBClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_dbSetting.DatabaseId, _dbSetting.CollectionId), document, CreateRequestOptions("*")); return(new DocumentDBResultDto() { Id = result.Resource.Id, ETag = result.Resource.ETag }); }
static void Main(string[] args) { ConnectionPolicy policy = new ConnectionPolicy() { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }; Uri endPoint = new Uri(EndpointUrl); using (DocumentClient client = new DocumentClient(endPoint, AuthKey, policy)) { Database database = client.CreateDatabaseQuery().Where(db => db.Id == DatabasebId).AsEnumerable().First(); DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink) .Where(c => c.Id == CollectionId) .AsEnumerable() .First(); IEnumerable<DataClass> dataSet = GetDataObjects(100); Task<ResourceResponse<Document>>[] documentTasks = dataSet.Select(d => client.CreateDocumentAsync(collection.DocumentsLink, d)).ToArray(); Task.WaitAll(documentTasks); Document[] docs = documentTasks.Select(t => t.Result.Resource).ToArray(); Document doc = docs.First(); Task<ResourceResponse<Attachment>>[] attachmentTasks = docs.Select(d => client.CreateAttachmentAsync(doc.AttachmentsLink, GetStream(1024))).ToArray(); Task.WaitAll(attachmentTasks); DataClass[] data = client.CreateDocumentQuery<DataClass>(collection.DocumentsLink).Select(d => d).ToArray(); Attachment[] attachments = client.CreateAttachmentQuery(doc.AttachmentsLink).ToArray(); string sql = "SELECT c.Name FROM c Where c.ObjectKey < 30 AND c.ObjectKey > 20"; dynamic[] dataArray = client.CreateDocumentQuery(collection.DocumentsLink, sql).ToArray(); } }
public async void SendInfo(SoundRecord soundRecord) { Uri endpointUri = new Uri(CloudConfiguration.DocumentDbUri); string authorizationKey = CloudConfiguration.DocumentDbKey; _documentClient = new DocumentClient(endpointUri, authorizationKey); var collection = await GetDocumentCollection(); try { Console.WriteLine("{0} > Sending message to Document DB: {1}", DateTime.Now, soundRecord); var result = await _documentClient.CreateDocumentAsync(collection.SelfLink, soundRecord); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message); Console.ResetColor(); } }
private static async void CreateDatabase() { DocumentClient client = new DocumentClient(new Uri(CONST_EndPointUrl), CONST_AuthorizationKey); Database database = await GetDatabase(client); DocumentCollection documentCollection = await GetDocumentCollection(client, database); Course course = new Course() { Id = "1", Name = "English", CreationDate = DateTime.Now.ToUniversalTime(), Teacher = new Teacher() { Age = 40, FullName = "Adel Mohamed" }, Sessions = new List<Session>(){ new Session(){Id=3, Name="Introduction", MaterialsCount=10}, new Session(){Id=4, Name="First Lesson", MaterialsCount = 3} } }; Document document = await client.CreateDocumentAsync(documentCollection.DocumentsLink, course); }
public static async Task SaveTestResults(PerformanceTestResult testResults) { // Make sure to call client.Dispose() once you've finished all DocumentDB interactions // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "DistributedWebTest").AsEnumerable().FirstOrDefault(); if (database == null) { // Create a database database = await client.CreateDatabaseAsync( new Database { Id = "DistributedWebTest" }); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "DistributedTestResults").AsEnumerable().FirstOrDefault(); if (documentCollection == null) { // Create a document collection using the lowest performance tier available (currently, S1) documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = "DistributedTestResults" }, new RequestOptions { OfferType = "S1" }); } await client.CreateDocumentAsync(documentCollection.DocumentsLink, testResults); }
private static async Task TransferDc(DocumentCollection oldDc, DocumentCollection newDc, DocumentClient client, Database database, Hashtable newList) { foreach (DictionaryEntry dis in newList) { var tempDis = dis; var items = from d in client.CreateDocumentQuery<PostMessage>(oldDc.DocumentsLink) where d.Type == "Post" && d.Path.District == tempDis.Key.ToString() select d; foreach (var item in items) { try { await client.DeleteDocumentAsync(item._self); } catch (Exception) { Thread.Sleep(200); client.DeleteDocumentAsync(item._self).Wait(); } try { await client.CreateDocumentAsync(newDc.DocumentsLink, item); } catch (Exception) { Thread.Sleep(200); client.CreateDocumentAsync(newDc.DocumentsLink, item).Wait(); } } } }
private static async Task SaveDisList(Hashtable newList, Hashtable oldList, DocumentCollection origin, DocumentCollection oldDc, DocumentCollection newDc, DocumentClient client) { var t = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; var allow = new DcAllocate { Type = "DisList", DcName = newDc.Id, DcSelfLink = newDc.SelfLink, District = new List<string>() }; foreach (DictionaryEntry i in newList) { allow.District.Add(i.Key.ToString()); } await client.CreateDocumentAsync(origin.DocumentsLink, allow); var ds = from d in client.CreateDocumentQuery<DcAllocate>(origin.DocumentsLink) where d.Type == "DisList" && d.DcName == oldDc.Id select d; var l = ds.ToList().FirstOrDefault(); if (l != null) await client.DeleteDocumentAsync(l._self); var allow2 = new DcAllocate { Type = "DisList", DcName = oldDc.Id, DcSelfLink = oldDc.SelfLink, District = new List<string>(), }; foreach (DictionaryEntry i in oldList) { allow2.District.Add(i.Key.ToString()); } await client.CreateDocumentAsync(origin.DocumentsLink, allow2); }
private static async Task AttemptWriteWithReadPermissionAsync(string collectionLink, Permission permission) { using (DocumentClient client = new DocumentClient( new Uri(endpointUrl), permission.Token)) { //attempt to write a document > should fail try { await client.CreateDocumentAsync(collectionLink, new { id = "not allowed" }); //should never get here, because we expect the create to fail throw new ApplicationException("should never get here"); } catch (DocumentClientException de) { //expecting an Forbidden exception, anything else, rethrow if (de.StatusCode != HttpStatusCode.Forbidden) throw; } } }
private static async Task AttemptReadFromTwoCollections(List<string> collectionLinks, List<Permission> permissions) { //Now, we're going to use multiple permission tokens. //In this case, a read Permission on col1 AND another read Permission for col2 //This means the user should be able to read from both col1 and col2, but not have //the ability to read other collections should they exist, nor any admin access. //the user will also not have permission to write in either collection using (DocumentClient client = new DocumentClient(new Uri(endpointUrl), permissions)) { FeedResponse<dynamic> response; //read collection 1 > should succeed response = await client.ReadDocumentFeedAsync(collectionLinks[0]); //read from collection 2 > should succeed response = await client.ReadDocumentFeedAsync(collectionLinks[1]); //attempt to write a doc in col 2 > should fail with Forbidden try { await client.CreateDocumentAsync(collectionLinks[1], new { id = "not allowed" }); //should never get here, because we expect the create to fail throw new ApplicationException("should never get here"); } catch (DocumentClientException de) { //expecting an Forbidden exception, anything else, rethrow if (de.StatusCode != HttpStatusCode.Forbidden) throw; } } return; }
private static async Task GetData(DocumentClient client, DocumentCollection documentCollection) { var t = (long) (DateTime.UtcNow.AddHours(-4).Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; // Create the Andersen family document. Family AndersenFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent {FirstName = "Thomas"}, new Parent {FirstName = "Mary Kay"} }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet {GivenName = "Fluffy"} } } }, Address = new Address {State = "WA", County = "King", City = "Seattle"}, IsRegistered = true }; try { var res = await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersenFamily); } catch (DocumentClientException e) { var z = e; } }
private static async Task CreateDatabase() { var client = new DocumentClient(new Uri(url), auth); // Create the database if it does not exist. Database database = client.CreateDatabaseQuery().Where(db => db.Id == "fProj") .AsEnumerable().FirstOrDefault(); if (database == null) { database = await client.CreateDatabaseAsync(new Database { Id = "fProj" }); } else { Console.WriteLine("Your Database existed previously"); } // Create the Document Collection if it does not exist. DocumentCollection col = client.CreateDocumentCollectionQuery (database.CollectionsLink) .Where(c => c.Id == "fpDocs") .AsEnumerable().FirstOrDefault(); if (col == null) { col = await client.CreateDocumentCollectionAsync (database.CollectionsLink, new DocumentCollection { Id = "fpDocs" }, new RequestOptions { OfferType = "S1" }); } else { Console.WriteLine("Yo, you already had that collection"); } // Create the first document Document doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "1").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc1 = new Restaurant { Id = "1", RName = "Duck's Country Bunker", UserId = "user1", FName = "Phil", LName = "McLovin", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Small Fries", Calories = 333, Price = .99M }, new MenuItem { Id = "2", ItemName = "Medium Fries", Calories = 444, Price = 1.99M }, new MenuItem { Id = "3", ItemName = "Large Fries", Calories = 555, Price = 2.99M }, new MenuItem { Id = "4", ItemName = "Small Beer", Calories = 5, Price = .99M }, new MenuItem { Id = "5", ItemName = "Medium Beer", Calories = 10, Price = 2.00M }, new MenuItem { Id = "6", ItemName = "Normal Sized Beer", Calories = 300, Price = 3.00M }, new MenuItem { Id = "7", ItemName = "Coffee", Calories = 50, Price = 1.00M } }, Address = new Address { Id = "1", StreetNumber = "1235 SE Brooklyn St.", City = "Corvallis", State = "Oregon", ZipCode = "99775" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc1); } // Create the second document doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "2").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc2 = new Restaurant { Id = "2", RName = "Obi One", UserId = "user1", FName = "Allen", LName = "Jones", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Cheeseburger", Calories = 75, Price = .99M }, new MenuItem { Id = "2", ItemName = "Hamburger", Calories = 50, Price = 1M }, new MenuItem { Id = "3", ItemName = "Regular Onion Rings", Calories = 100, Price = 1.50M }, new MenuItem { Id = "4", ItemName = "Large Onion Rings", Calories = 300, Price = 2M } }, Address = new Address { Id = "2", StreetNumber = "4949 N Broadway Ave", City = "Eugene", State = "Oregon", ZipCode = "96709" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc2); } doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "3").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc3 = new Restaurant { Id = "3", RName = "Classy Chicken", UserId = "user2", FName = "Ash", LName = "Awesome", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Small Chicken Dinner", Calories = 1111, Price = 11M }, new MenuItem { Id = "2", ItemName = "Medium Chicken Dinner", Calories = 2222, Price = 22M }, new MenuItem { Id = "3", ItemName = "Large Chicken Dinner", Calories = 3333, Price = 33M }, new MenuItem { Id = "4", ItemName = "Freedom Sized Chicken Dinner", Calories = 4444, Price = 44M }, new MenuItem { Id = "5", ItemName = "Small Chicken Wings", Calories = 500, Price = 5M }, new MenuItem { Id = "6", ItemName = "Medium Chicken Wings", Calories = 1000, Price = 7M }, new MenuItem { Id = "7", ItemName = "Large Chicken Wings", Calories = 1500, Price = 10M } }, Address = new Address { Id = "3", StreetNumber = "500 Midtown Ave", City = "Los Angeles", State = "California", ZipCode = "90210" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc3); } doc = client.CreateDocumentQuery(col.DocumentsLink) .Where(d => d.Id == "4").AsEnumerable().FirstOrDefault(); if (doc == null) { Restaurant doc4 = new Restaurant { Id = "4", RName = "Four Stars", UserId = "user2", FName = "Ash", LName = "Awesome", MenuItems = new MenuItem[] { new MenuItem { Id = "1", ItemName = "Pretentious Meal #1", Calories = 1, Price = 100M }, new MenuItem { Id = "2", ItemName = "Pretentious Meal #2", Calories = 2, Price = 100M }, new MenuItem { Id = "3", ItemName = "Pretentious Meal #3", Calories = 3, Price = 300M }, new MenuItem { Id = "4", ItemName = "Small Gerbil Food", Calories = 4, Price = 400M }, new MenuItem { Id = "5", ItemName = "Medium Gerbil Food", Calories = 5, Price = 50M }, new MenuItem { Id = "6", ItemName = "Large Gerbil Food", Calories = 6, Price = 60M } }, Address = new Address { Id = "4", StreetNumber = "3001 SE Belmont St.", City = "Portland", State = "Oregon", ZipCode = "97214" } }; await client.CreateDocumentAsync(col.DocumentsLink, doc4); } var items = client.CreateDocumentQuery(col.DocumentsLink, "SELECT r.id, r.rName FROM Restaurant r"); // Query and check what I have entered is there. foreach(var rest in items) { Console.WriteLine(rest); } // Begin seeding of the collection with users Document user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user1") .AsEnumerable().FirstOrDefault(); if (user == null) { Users user1 = new Users { Id = "user1", UserName = "******", Password = "******" }; await client.CreateDocumentAsync(col.DocumentsLink, user1); } user = client.CreateDocumentQuery(col.DocumentsLink).Where(d => d.Id == "user2") .AsEnumerable().FirstOrDefault(); if (user == null) { Users user2 = new Users { Id = "user2", UserName = "******", Password = "******" }; await client.CreateDocumentAsync(col.DocumentsLink, user2); } // TODO: Try to query a user assosciated with a restaurant as a separate document. /* */ //await client.DeleteDatabaseAsync(database.SelfLink); // Dispose of the client connection. client.Dispose(); }
private static async Task GetStartedDemo() { // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); // If the database does not exist, create a new database if (database == null) { database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); WriteMessage("Created dbs/FamilyRegistry"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); // If the document collection does not exist, create a new collection if (documentCollection == null) { documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id, new DocumentCollection { Id = "FamilyCollection" }); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); // If the document does not exist, create a new document if (document == null) { // Create the Andersen Family document Family andersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay"} }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family wakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", family); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("Read {0} from LINQ", family); } // Query the documents using LINQ lambdas for the Andersen family families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", family); } // Clean up/delete the database and client await client.DeleteDatabaseAsync("dbs/" + database.Id); client.Dispose(); }
public static async Task AddFamily(DocumentClient client,DocumentCollection collection, string name) { var family = new Family { Address = new Dictionary<string, string> {{"state", "fl"}}, Childrend = new List<FamilyMemeber> { new FamilyMemeber {Age = 10, Gender = "female", Name = "susy"}, new FamilyMemeber {Age = 8, Gender = "male", Name = "jimmy"} }, IsHome = true, Parents = new List<FamilyMemeber> { new FamilyMemeber {Age = 45, Gender = "female", Name = "Linda"}, new FamilyMemeber {Age = 40, Gender = "male", Name = "Bob"} }, Name = name }; await client.CreateDocumentAsync(collection.DocumentsLink, family); }
private async Task SendToDb(DocumentClient client, string dataString) { dynamic data = JsonConvert.DeserializeObject(dataString); var path = data.url.ToString().Split('/'); data.body.timestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; PostMessage message = ModelService.PostData(data, path); //create document on DB with RangePartitionResolver var res = await RetryService.ExecuteWithRetries( () => client.CreateDocumentAsync(_databaseSelfLink, message)); //Check response and notify Firebase if (res.StatusCode == HttpStatusCode.Created) { ConfigurationManager.AppSettings["LMS2"] = "true"; try { FirebaseResponse response = await _client.PushAsync(data.url.ToString(), data.body); if (response.StatusCode == HttpStatusCode.OK) { ConfigurationManager.AppSettings["LMS3"] = "true"; } } catch (FirebaseException e) { Trace.TraceError("Error in push to Firebase: " + e.Message); } } }
private async Task SendToDb(DocumentClient client, string dataString) { dynamic data = JsonConvert.DeserializeObject(dataString); var path = data.url.ToString().Split('/'); data.body.timestamp = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; PostMessage message = ModelService.PostData(data, path); //create document on DB with RangePartitionResolver var res = await RetryService.ExecuteWithRetries( () => client.CreateDocumentAsync(_databaseSelfLink, message)); //if not found collection, update RangePartitionResolver if (res == null) { _iDbService.UpdateDocumentClient(); return; } //Check response and notify Firebase if (res.StatusCode == HttpStatusCode.Created) { Trace.TraceInformation("DocumentDB received. Message: '{0}'", res.Resource.SelfLink); try { FirebaseResponse response = await _client.PushAsync(data.url.ToString(), data.body); if (response.StatusCode == HttpStatusCode.OK) { Trace.TraceInformation("Firebase received. Message: '{0}'", response.Body); } } catch (FirebaseException e) { Trace.TraceError("Error in push to Firebase: " + e.Message); } } }
private async Task RunAsync(CancellationToken cancellationToken) { var endpointUrl = CloudConfigurationManager.GetSetting("ddbEndpointUri"); var authKey = CloudConfigurationManager.GetSetting("ddbAuthKey"); var dbName = CloudConfigurationManager.GetSetting("ddbName"); var dbCollection = CloudConfigurationManager.GetSetting("ddbCollection"); var dbClient = new DocumentClient(new Uri(endpointUrl), authKey); var db = GetOrCreateDatabase(dbClient, dbName); var coll = GetOrCreateCollection(dbClient, db.SelfLink, dbCollection); while (!cancellationToken.IsCancellationRequested) { var msg = await _client.ReceiveAsync(TimeSpan.FromSeconds(5)); if (msg != null) { var json = (string) msg.Properties["json"]; var result = JsonConvert.DeserializeObject<PurchaseResult>(json); await dbClient.CreateDocumentAsync(coll.DocumentsLink, result); } } }
private async Task InsertDocument(int taskId, DocumentClient client, DocumentCollection collection, string sampleJson, long numberOfDocumentsToInsert) { requestUnitsConsumed[taskId] = 0; string partitionKeyProperty = collection.PartitionKey.Paths[0].Replace("/", ""); Dictionary<string, object> newDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(sampleJson); for (var i = 0; i < numberOfDocumentsToInsert; i++) { newDictionary["id"] = Guid.NewGuid().ToString(); newDictionary[partitionKeyProperty] = Guid.NewGuid().ToString(); try { ResourceResponse<Document> response = await client.CreateDocumentAsync( UriFactory.CreateDocumentCollectionUri(DatabaseName, DataCollectionName), newDictionary, new RequestOptions() { }); string partition = response.SessionToken.Split(':')[0]; requestUnitsConsumed[taskId] += response.RequestCharge; Interlocked.Increment(ref this.documentsInserted); } catch (Exception e) { if (e is DocumentClientException) { DocumentClientException de = (DocumentClientException)e; if (de.StatusCode != HttpStatusCode.Forbidden) { Trace.TraceError("Failed to write {0}. Exception was {1}", JsonConvert.SerializeObject(newDictionary), e); } else { Interlocked.Increment(ref this.documentsInserted); } } } } Interlocked.Decrement(ref this.pendingTaskCount); }
public async void UploadFeedsToDocumentDB() { var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); Database database = client.CreateDatabaseQuery() .Where(db => db.Id == databaseId) .AsEnumerable() .FirstOrDefault(); if (database==null) { database = await client.CreateDatabaseAsync(new Database { Id = databaseId }); Console.WriteLine("Created Database: id - {0} and selfLink - {1}", database.Id, database.SelfLink); } DocumentCollection collectionBlog = client.CreateDocumentCollectionQuery(database.CollectionsLink) .Where(doccoll => doccoll.Id == collectionIdBlogs) .AsEnumerable() .FirstOrDefault(); if (collectionBlog == null) { collectionBlog = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionIdBlogs }); Console.WriteLine("Created Collection {0}.", collectionBlog); } DocumentCollection collectionPosts = client.CreateDocumentCollectionQuery(database.CollectionsLink) .Where(doccoll => doccoll.Id == collectionIdPost) .AsEnumerable() .FirstOrDefault(); if (collectionPosts == null) { collectionPosts = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionIdPost }); Console.WriteLine("Created Collection {0}.", collectionPosts); } foreach(var f in this.Feeds) { Console.WriteLine(f.Title); foreach (var post in f.Items) { Console.Write("."); try { await client.CreateDocumentAsync(collectionPosts.SelfLink, post); } catch(Exception ex) { Console.WriteLine("X"); } } f.Items.Clear(); await client.CreateDocumentAsync(collectionBlog.SelfLink, f); Console.WriteLine(); } }
private static async Task GetStartedDemo() { // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); // If the database does not exist, create a new database if (database == null) { database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); WriteMessage("Created dbs/FamilyRegistry"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); // If the document collection does not exist, create a new collection if (documentCollection == null) { documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id, new DocumentCollection { Id = "FamilyCollection" }); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); // If the document does not exist, create a new document if (document == null) { // Create the Andersen Family document Family andersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" , SSN = "111-11-1111"}.Seal(), new Parent { FirstName = "Mary Kay", SSN = "222-22-2222"}.Seal() }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true, GeneticCondition = "diabetes" }; Crypteron.CipherObject.Seal(andersonFamily); // or andersonFamily.Seal() // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family wakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false, }; Crypteron.CipherObject.Seal(wakefieldFamily); // or wakefieldFamily.Seal() // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection" await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily); WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("Read {0} from LINQ", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Query the documents using LINQ lambdas for the Andersen family // Need to get results back in original class with Secure attributes // Dynamic JObject is not currently supported families = client.CreateDocumentQuery<Family>("dbs/" + database.Id + "/colls/" + documentCollection.Id) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", JsonConvert.SerializeObject(family.Unseal(), Formatting.Indented)); } // Clean up/delete the database and client Console.WriteLine("Done. Press 'd' to delete database prior to exiting"); var choice = Console.ReadKey().KeyChar; if (choice == 'd' || choice == 'D') { Console.WriteLine("\nDeleting database ..."); await client.DeleteDatabaseAsync("dbs/" + database.Id); } client.Dispose(); }
static int Main(string[] args) { Options options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Invalid arguments"); return 1; } using (DocumentClient client = new DocumentClient( new Uri(options.Endpoint), options.AuthKey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp })) { Database database = client.CreateDatabaseQuery().Where(d => d.Id == options.Database).AsEnumerable().FirstOrDefault(); if (database == null) { Console.WriteLine("Cannot find database " + options.Database); return 2; } List<DocumentCollection> collections = client.ReadDocumentCollectionFeedAsync(database.SelfLink).Result.ToList(); int minimumRequiredCollections = Math.Max(options.NewCollections, options.CurrentCollections); if (collections.Count < minimumRequiredCollections) { Console.WriteLine("At least {0} collections must be pre-created", minimumRequiredCollections); return 3; } Console.WriteLine("Current distribution of documents across collections:"); LogDocumentCountsPerCollection(client, database).Wait(); Console.WriteLine(); HashPartitionResolver currentPartitionResolver = new HashPartitionResolver(options.PartitionKeyName, collections.Take(options.CurrentCollections).Select(c => c.SelfLink)); HashPartitionResolver nextPartitionResolver = new HashPartitionResolver(options.PartitionKeyName, collections.Take(options.NewCollections).Select(c => c.SelfLink)); int numberOfMovedDocuments = 0; Parallel.ForEach(currentPartitionResolver.CollectionLinks, collectionLink => { ResourceFeedReader<Document> feedReader = client.CreateDocumentFeedReader(collectionLink, new FeedOptions { MaxItemCount = -1 }); while (feedReader.HasMoreResults) { foreach (Document document in DocumentClientHelper.ExecuteWithRetryAsync<FeedResponse<Document>>(() => feedReader.ExecuteNextAsync()).Result) { object partitionKey = nextPartitionResolver.GetPartitionKey(document); string newCollectionLink = nextPartitionResolver.ResolveForCreate(partitionKey); if (newCollectionLink != collectionLink) { int count = Interlocked.Increment(ref numberOfMovedDocuments); DocumentClientHelper.ExecuteWithRetryAsync(() => client.DeleteDocumentAsync(document.SelfLink)).Wait(); DocumentClientHelper.ExecuteWithRetryAsync(() => client.CreateDocumentAsync(newCollectionLink, document)).Wait(); if (count % 100 == 0) { Console.WriteLine("Moved {0} documents between partitions", numberOfMovedDocuments); } } } } }); Console.WriteLine(); Console.WriteLine("Moved {0} documents between partitions.", numberOfMovedDocuments); Console.WriteLine(); Console.WriteLine("Current distribution of documents across collections:"); LogDocumentCountsPerCollection(client, database).Wait(); Console.WriteLine(); } return 0; }
/// <summary> /// Internal Member to save a new site request /// </summary> /// <param name="client"></param> /// <param name="collectionLink"></param> /// <param name="info"></param> /// <returns></returns> private Document SaveNewRequest(DocumentClient client, string collectionLink, SiteClassification info) { var saveDocumentTask = Task.FromResult(client.CreateDocumentAsync(collectionLink, info)); Document document = null; if (!saveDocumentTask.IsFaulted) { document = saveDocumentTask.Result.Result; } return document; }
private static async Task CreateCourse(DocumentClient documentClient, DocumentCollection documentCollection) { Course course = new Course() { CourseId = Guid.NewGuid(), Name = "En", Teacher = new Teacher() { TeacherId = Guid.NewGuid(), FullName = "Adel Adel", Age = 44 }, Students = new List<Model.Student>() { new Student(){ FullName = "Adel Mohamed", StudentId = Guid.NewGuid() } } , Sessions = new List<Session>(){ new Session(){ SessionId = Guid.NewGuid(), Name = "Intro", MaterialsCount = 10 }, new Session(){ SessionId = Guid.NewGuid(), Name = "Ch1", MaterialsCount = 3 } } }; Document document = await documentClient.CreateDocumentAsync(documentCollection.DocumentsLink, course); }
private static async Task WriteData(DocumentClient client, DocumentCollection documentCollection) { var z = new Random(); var topic = new Topic { Id = "123", Type = "Post", Path = new PostPath { District = "tst-azhang1", School = "JP", Classes = "Math", Unit = "Calculus" }, Info = new InfoPost { teacher = "Newton", start = "2015-4-1", due = DateTime.Now.AddDays(z.Next(1, 4)).ToString(CultureInfo.CurrentCulture), description = "homework" } }; //var res = await client.CreateDocumentAsync(documentCollection.DocumentsLink, topic); await RetryService.ExecuteWithRetries(5, () => client.CreateDocumentAsync(documentCollection.DocumentsLink, topic)); var i = 3; /* var families = from f in client.CreateDocumentQuery<Topic>(documentCollection.DocumentsLink) where f.Type == "Topic" select f; foreach (var family in families) { var s = JsonConvert.SerializeObject(family); dynamic d = JsonConvert.DeserializeObject(s); var res = await client.DeleteDocumentAsync(family._self); Console.Write(d); }*/ }
private static async Task GetStartedDemo() { // Make sure to call client.Dispose() once you've finished all DocumentDB interactions // Create a new instance of the DocumentClient var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey); // Check to verify a database with the id=FamilyRegistry does not exist Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault(); if (database == null) { // Create a database database = await client.CreateDatabaseAsync( new Database { Id = "FamilyRegistry" }); } else { Warn("database"); } // Check to verify a document collection with the id=FamilyCollection does not exist DocumentCollection documentCollection = client.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault(); if (documentCollection == null) { // Create a document collection using the lowest performance tier available (currently, S1) documentCollection = await client.CreateDocumentCollectionAsync(database.CollectionsLink, new DocumentCollection { Id = "FamilyCollection" }, new RequestOptions { OfferType = "S1" }); } else { Warn("document collection"); } // Check to verify a document with the id=AndersenFamily does not exist Document document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the Andersen Family document Family AndersonFamily = new Family { Id = "AndersenFamily", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay"} }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; await client.CreateDocumentAsync(documentCollection.DocumentsLink, AndersonFamily); } else { Warn("document"); } // Check to verify a document with the id=AndersenFamily does not exist document = client.CreateDocumentQuery(documentCollection.DocumentsLink).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault(); if (document == null) { // Create the WakeField document Family WakefieldFamily = new Family { Id = "WakefieldFamily", Parents = new Parent[] { new Parent { FamilyName= "Wakefield", FirstName= "Robin" }, new Parent { FamilyName= "Miller", FirstName= "Ben" } }, Children = new Child[] { new Child { FamilyName= "Merriam", FirstName= "Jesse", Gender= "female", Grade= 8, Pets= new Pet[] { new Pet { GivenName= "Goofy" }, new Pet { GivenName= "Shadow" } } }, new Child { FamilyName= "Miller", FirstName= "Lisa", Gender= "female", Grade= 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; await client.CreateDocumentAsync(documentCollection.DocumentsLink, WakefieldFamily); } else { Warn("document"); } // Query the documents using DocumentDB SQL for the Andersen family var families = client.CreateDocumentQuery(documentCollection.DocumentsLink, "SELECT * " + "FROM Families f " + "WHERE f.id = \"AndersenFamily\""); foreach (var family in families) { Console.WriteLine("\tRead {0} from SQL", family); } // Query the documents using LINQ for the Andersen family families = from f in client.CreateDocumentQuery(documentCollection.DocumentsLink) where f.Id == "AndersenFamily" select f; foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ", family); } // Query the documents using LINQ lambdas for the Andersen family families = client.CreateDocumentQuery(documentCollection.DocumentsLink) .Where(f => f.Id == "AndersenFamily") .Select(f => f); foreach (var family in families) { Console.WriteLine("\tRead {0} from LINQ query", family); } // Query the documents using DocumentSQl with one join var items = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink, "SELECT f.id, c.FirstName AS child " + "FROM Families f " + "JOIN c IN f.Children"); foreach (var item in items.ToList()) { Console.WriteLine(item); } // Query the documents using LINQ with one join items = client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink) .SelectMany(family => family.Children .Select(children => new { family = family.Id, child = children.FirstName })); foreach (var item in items.ToList()) { Console.WriteLine(item); } // Clean up/delete the database and client await client.DeleteDatabaseAsync(database.SelfLink); client.Dispose(); }
private static async Task CreateActiveTransactionsDocIfNotExists(ActiveTransactions activeTransactionsDoc) { var client = new DocumentClient(new Uri(Endpoint), AuthKey); Uri collectionLink = UriFactory.CreateDocumentCollectionUri(DbName, CollectionName); bool needToCreate = false; try { await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DbName, CollectionName, activeTransactionsDoc.Id.ToString())); } catch (DocumentClientException de) { if (de.StatusCode != HttpStatusCode.NotFound) { throw; } else { needToCreate = true; } } if (needToCreate) { await client.CreateDocumentAsync(collectionLink, activeTransactionsDoc); } }
private static async Task sp2(DocumentCollection dc, DocumentClient client, Database database) { DocumentCollection dc2 = client.CreateDocumentCollectionQuery(database.SelfLink) .Where(c => c.Id == "LMSCollection1444075919174") .AsEnumerable() .FirstOrDefault(); await client.OpenAsync(); //await _iDbService.CollectionTransfer(client, dc2, dc); var mn=await client.ReadDatabaseAsync(database.SelfLink); /* await client.CreateDocumentAsync(dc.SelfLink, new CurrentCollection { id = "CurrentCollection", name=dc.Id });*/ /* var resolver = _iDbService.GetResolver(client, dc); foreach (var d in resolver.PartitionMap) { Console.WriteLine(d.Value); Offer offer = client.CreateOfferQuery() .Where(r => r.ResourceLink == d.Value) .AsEnumerable() .SingleOrDefault(); }*/ /* HashPartitionResolver hashResolver = new HashPartitionResolver( u => ((PostMessage) u).Path.District, new string[] {dc.SelfLink, dc2.SelfLink}); client.PartitionResolvers[database.SelfLink] = hashResolver;*/ var rangeResolver = _iDbService.GetResolver(client); client.PartitionResolvers[database.SelfLink] = rangeResolver; var created = await _iDbService.InitResolver(""); while (true) { var re2 = await _iDbService.UpdateResolver(dc2); var p = re2; await Task.Delay(TimeSpan.FromSeconds(4)); } var z1 = rangeResolver.GetPartitionKey(new PostMessage { Type = "Post", Info = new Info { user = "******", uid = "1210808", message = "java", timestamp = 7 }, Path = new PostPath { District = "tst-azhang" } }); //search global IQueryable<PostMessage> query = client.CreateDocumentQuery<PostMessage>(database.SelfLink) .Where(u => u.Info.timestamp>1); var now = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; //search on partition var t1 = DateTime.Now; var query2 = client.CreateDocumentQuery<PostMessage>(database.SelfLink, new FeedOptions { MaxItemCount = 1200 }, now); var query3 = client.CreateDocumentQuery<PostMessage>(dc2.SelfLink).AsDocumentQuery(); var t2 = DateTime.Now; Console.WriteLine(t2-t1); //.Where(u => u.Path.District=="tst-azhang"); foreach (PostMessage a in query2) { Console.WriteLine(a.Info.timestamp); } /* double totalRequestCharge = 0; while (query3.HasMoreResults) { FeedResponse<dynamic> queryResponse = await query3.ExecuteNextAsync<dynamic>(); Console.WriteLine("Query batch consumed {0} request units {1} doc", queryResponse.RequestCharge, queryResponse.Count); totalRequestCharge += queryResponse.RequestCharge; } Console.WriteLine(DateTime.Now - t2); Console.WriteLine("Query consumed {0} request units in total", totalRequestCharge);*/ Console.ReadLine(); int n = 19; try { while (n < 10) { n++; var timestamp=(long) (DateTime.UtcNow.AddHours(-1).Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; PostMessage x = new PostMessage { Type = "Post", Info = new Info { user = "******", uid = "1210808", message = "java", timestamp = timestamp }, Path = new PostPath { District = "tst-azhang" } }; await client.CreateDocumentAsync(database.SelfLink, x); } } catch (Exception e) { var t = e; } var z = 4; }
/// <summary> /// Internal Member to save a new site request /// </summary> /// <param name="client"></param> /// <param name="collectionLink"></param> /// <param name="info"></param> /// <returns></returns> private Document SaveNewRequest(DocumentClient client, string collectionLink, SiteInformation info ) { //If Settings are set to autoapprove then automatically approve the requests if (_manager.GetAppSettings().AutoApprove) { info.RequestStatus = SiteRequestStatus.Approved.ToString(); info.ApprovedDate = DateTime.Now; } else { info.RequestStatus = SiteRequestStatus.New.ToString(); } info.SubmitDate = DateTime.Now; var saveDocumentTask = Task.FromResult(client.CreateDocumentAsync(collectionLink, info)); Document document = null; if(!saveDocumentTask.IsFaulted) { document = saveDocumentTask.Result.Result; } return document; }
private static async Task AddTestData(DocumentClient client, Database database, int number) { int n = 0; try { while (n < number) { n++; var timestamp = (long) (DateTime.UtcNow.AddHours(-1).Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; PostMessage x = new PostMessage { Type = "Post", Info = new Info { user = "******", uid = "1210808", message = "java", timestamp = timestamp }, Path = new PostPath { District = "tst-azhang" } }; await client.CreateDocumentAsync(database.SelfLink, x); } } catch (Exception e) { var t = e; } }