本文整理汇总了C#中Microsoft.Azure.Documents.Client.DocumentClient.CreateDocumentAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DocumentClient.CreateDocumentAsync方法的具体用法?C# DocumentClient.CreateDocumentAsync怎么用?C# DocumentClient.CreateDocumentAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Azure.Documents.Client.DocumentClient
的用法示例。
在下文中一共展示了DocumentClient.CreateDocumentAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteDocument
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;
}
示例2: Main
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();
}
}
示例3: SendInfo
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();
}
}
示例4: CreateDatabase
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);
}
示例5: SaveTestResults
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);
}
示例6: TransferDc
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();
}
}
}
}
示例7: SaveDisList
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);
}
示例8: AttemptWriteWithReadPermissionAsync
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;
}
}
}
示例9: AttemptReadFromTwoCollections
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;
}
示例10: GetData
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;
}
}
示例11: GetStartedDemo
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
};
//.........这里部分代码省略.........
示例12: GetStartedDemo
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
//.........这里部分代码省略.........
示例13: SendToDb
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);
}
}
}
示例14: RunAsync
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);
}
}
}
示例15: SendToDb
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);
}
}
}