I have following part of code which worked to upload data to CosmosDB Mongo API. Now I am using Cosmos Client to upload document to Cosmos DB SQL API. However, Below lines don't support in SQL api.
var item = objs[i];
var doc = BsonDocument.Parse(item.ToString());
//saving all the documents in cosmos
listTask.Add(collection.ReplaceOneAsync(
filter: new BsonDocument("id", doc["id"]),
options: new ReplaceOptions { IsUpsert = true },
replacement: doc));
Is it possible to replace for SQL API?
private async Task UploadComplete(List<object> objs)
{
double total_cycles = (int)((double)objs.Count / BATCH);
var cycle= 0;
//configuring cosmos connection-SQL
CosmosClient client = new CosmosClient(cosmos);
var database = client.GetDatabase(cosmos_database);
var collection = database.GetContainer(cosmos_collection);
//works for Cosmos DB Mongo API
var item = objs[i];
var doc = BsonDocument.Parse(item.ToString());
//saving all the documents in cosmos
listTask.Add(collection.ReplaceOneAsync(
filter: new BsonDocument("id", doc["id"]),
options: new ReplaceOptions { IsUpsert = true },
replacement: doc));
//Cosmos DB SQL API
//Code here---------
//------------------
}
The equivalent function in the Cosmos .NET SDK is UpsertItemAsync().
I'm assuming here your partition key is /id.
listTask.Add(collection.UpsertItemAsync(
item: doc,
new PartitionKey(doc["id"]));
Related
With older versions of .NET and Azure Function Apps v2 it was possible to get all datasets from an Azure Table Storage table using (among other things) a TableContinuationToken:
Get more than 1000 datasets from an Azure Table Storage
Since the underlying Microsoft.Azure.Cosmos.Table packages are deprecated:
What is the new, current way in an .NET 6 based v4 Azure Function App to get all datasets from a table in an Azure Table Storage?
I have reproduced the issue in my environment and able to fetch the data list.
Thanks #Gaurav Mantri for the comment.
create a storage account and table in azure.
I used the below code and able to fetch the data list
private void tableInsert()
{
CloudStorageAccount storage_Account = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudTableClient tableClient = storage_Account.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("table1");
for (int ctr = 0; ctr < 1000; ctr++)
{
EmployeeEntity employeeEntity = new EmployeeEntity("Fname"+ctr, "LName"+ctr)
{
Email = "something#something.com",
PhoneNumber = "123456789"
};
TableOperation insertOperation = TableOperation.Insert(employeeEntity);
table.ExecuteAsync(insertOperation);
}
}
for fetching
public async Task<List<TableEntity>> GetList()
{
CloudTable table = await GetTableAsync();
TableQuery<TableEntity> query = new TableQuery<TableEntity>();
List<TableEntity> results = new List<TableEntity>();
TableContinuationToken continuationToken = null;
do
{
TableQuerySegment<TableEntity> queryResults = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
continuationToken = queryResults.ContinuationToken;
results.AddRange(queryResults.Results);
} while (continuationToken != null);
return results;
}
private async Task<CloudTable> GetTableAsync()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("table1");
await table.CreateIfNotExistsAsync();
return table;
}
Reference taken from Azure Tables client library for .NET
Based on another post, I can filter via HTTP requests as follows:
https://graph.microsoft.com/v1.0/me/events?
$filter=categories/any(a:a+eq+'Red+Category')
I am not sure what the a:a stands for here but it works.
I want to replicate this in Microsoft Graph SDK, I am using a query option as per below which does not return any results:
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$filter",
"categories/any(a:a+eq+'Red+Category'")
};
You seem to be executing a search instead of a filter in your c# code.
Try using:
var request = graphClient.Users[userId].Events.Request().Filter("categories/any(a:a+eq+'Red+Category')");
var result = await request.GetAsync();
Or alternatively:
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$filter",
"categories/any(a:a+eq+'Red+Category')")
};
Hi I am a newbie on MongoDB and CosmosDB and I try to this in c#
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(connectionString)
);
settings.SslSettings =
new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
var mongoClient = new MongoClient(settings);
var mongoDatabase = mongoClient.GetDatabase("MYDATABASE");
var mongoCollection = mongoDatabase.GetCollection<BsonDocument>("MYCOLLECTION");
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Lt("mac", "001BC50670101BB8") & builder.Gte("date", "2016-09-18T00:00:00Z") & builder.Gte("date", "2017-09-22T00:00:00Z");
var query = mongoCollection.Find<BsonDocument>(filter).ToList<BsonDocument>();
But when it runs the query on the server I get this error:
Errors":["An invalid query has been specified with filters against path(s) that are not range-indexed. Consider adding allow scan header in the request."
I have found that I should add the "x-ms-documentdb-query-enable-scan" header to my request. But how I can do this?
Solution found in comment section:
Query changed from
builder.Lt("mac", "001BC50670101BB8")
to
builder.Eq("mac", "001BC50670101BB8")
I have this code:
public async void SaveAuditLog(AuditLog a)
{
var db = new MongoDBContext();
var o = db.GetMongoDatabase(Common.Common.MongoDbConnectionString);
var audit = o.GetCollection<AuditLog>("AuditLog");
await audit.InsertOneAsync(a);
}
public IMongoDatabase GetMongoDatabase(string connectionstring)
{
MongoClient client = new MongoClient(connectionstring);
return client.GetDatabase("test");
}
this is the connection string from web.config:
<add connectionString="mongodb://localhost:27017" name="mongodb"></add>
when I check the data through robomongo, it does not show me any data inserted.
I have tried the following code as well and no data is inserted:
public async void SaveAuditLog(AuditLog a)
{
var client = new MongoClient(Common.Common.MongoDbConnectionString);
var o = client.GetDatabase("test");
var audit = o.GetCollection<BsonDocument>("AuditLog");
var document = new BsonDocument { {"Test", "test"} };
await audit.InsertOneAsync(document);
}
I am using csharpdriver for mongo with 2.2. What am I doing wrong?
found out that the data is getting inserted in mongodb and there is a bug in robomongo version 0.8.5 itself which does not show collections/documents for mongodb version 3 and above.
ran some scripts (in robomongo) which do return the data:
db.stats()
db.CollectionName.find()
downloaded mongochef and it displayed the data straight away.
How to connect couchDB with ASP.NET C# application? If any one can you give a sample application.
I had the same need and after evaluating the options available, to meet the requirements of my application, I created any components that helped me a lot and maybe they can help you and also others. I make it clear that I have no intention of promoting myself here, just sharing something that may be useful.
The detailed explanation of how to configure and use it is on Github.
Link: Nuget Package |
Github
Example of use for retrieving documents with mango-querie:
IList<User> users;
var sts = new List<String> { "ACTIVE", "LOCKED" };
using (UserRepository db = new UserRepository())
{
var query = db.FindOf("list-status", new { id = "OwnerIdloop.user.7", statuses = sts });
users = db.List<User>(query);
}
Array.ForEach(users.ToArray(), Console.WriteLine);
Example of adding documents:
User user = createUser("email#email.com");
using (UserRepository db = new UserRepository())
{
var result = db.Insert<User>(user); // add document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of changing documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
user.Name = user.Name + "::CHANGED";
var result = db.Update<User>(user); // update document and return instance changed with operation revision id
Console.WriteLine(result.Revision);
}
Example of deleting documents:
using (UserRepository db = new UserRepository())
{
// Load document data by ID
var user = db.Get<User>("email#email.com");
var result = db.Delete<User>(user); // delete document from database. Return true case sucess or false case not deleted
Console.WriteLine($"Sucesso: {result}");
}
After installing the NuGet, just create an instance of MyCouch.Client and pass it the URL of your database.
using (var client = new MyCouchClient("http://127.0.0.1:5984/test"))
{
//Consume here
}
The format is: {scheme}://[{username}:{password}]/{authority}/{localpath}. From v0.11.0, there's a specific MyCouchUriBuilder that you can use for building the Uri. It will automatically e.g. apply Uri.EscapeDataString to username and password when calling SetBasicCredentials.
var uriBuilder = new MyCouchUriBuilder("http://localhost:5984/")
.SetDbName(TestConstants.TestDbName)
.SetBasicCredentials("foob#r", "p#ssword");
return new MyCouchClient(uriBuilder.Build());
For more details Click Here