I am trying to delete the document by id, which is of type ObjectId, I do have converted the string to ObjectId and passed as parameter to remove from collection, but I am not able to delete the record.
I don't know what is the actuall reason behind, Looking for solution, below is my code sample:
public void DeleteRecords(string objectID)
{
try
{
// Create server settings to pass connection string, timeout, etc.
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
// Create server object to communicate with our server
MongoServer server = new MongoServer(settings);
MongoDatabase myDB = server.GetDatabase("DemoMongoDB");
MongoCollection<BsonDocument> records = myDB.GetCollection<BsonDocument>("Records");
//var query = Query<Records>.EQ(fd => fd._id, ObjectId.Parse(name));
var query = Query<Records>.EQ(e => e._id, new BsonObjectId(objectID));
records.Remove(query);
}
catch (Exception ex)
{
}
}
Try below code, and see whether is working?
var query = Query.EQ("_id", new BsonObjectId("objectID"));
Or
var query = Query.EQ("_id", name);
records.Remove(query);
Finally, This worked for me, without converting the string to object id and pass as a parameter as a string itself.
var query = Query.EQ("_id", objectID);
records.Remove(query);
Related
I am working on an .net api development in which one task is deletes some documents based on the condition .The documents is resided in Cosmos DB.
I have tried via stored procedures but didnt get proper SP which deleted record.I have tried fetching the documents using select query with where condition and by loop through it fetched and passed document ID and I've tried to delete
using DeleteDocumentAsync
//---Deleting Document based on documentId from corresponding DbName,CollectionName-----------//
private async Task DeleteSecurityDocument(string databaseName, string collectionName, string documentName)
{
string endPoint = ConfigurationManager.AppSettings["DocDbEndPoint"];
string masterKey = ConfigurationManager.AppSettings["DocDbmasterKey"];
var client = new DocumentClient(new Uri(endPoint), masterKey);
await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentName));
}
This code works for me:
var options = new RequestOptions { PartitionKey = new PartitionKey(PartitionKeyValue) };
var docUri = UriFactory.CreateDocumentUri(databaseId, collectionId, documentId);
var doc = await _client.ReadDocumentAsync(docUri, options);
if (doc != null)
{
return await _client.DeleteDocumentAsync(doc.SelfLink, options);
}
where options is an instance of RequestOptions and should have PartitionKey set if you are working with partitioned collection.
Most probably reading the document before deleting is not necessary here, and you can directly put docUri, I haven't checked this (the code exists in the project for a long time).
/---------------.delete documents ------------/
var docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, documentName);
RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey(Partitionkeyvalue) };
var deleteresponse = await client.DeleteDocumentAsync(docUri, options);
Now it works fine for me .Problem was about partitiokeyvalue. Thanks
I created a database with SQLite-net so:
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db"), true);
await conn.CreateTableAsync<Musei>();
Musei musPref;
if (muss.NumeroTel != null && muss.Descrizione!=null && muss.indirizzoEmail!= null && muss.Immagine!= null)
{
musPref = new Musei
{
DidascaliaLista=muss.DidascaliaLista,
NomeMuseo = muss.NomeMuseo,
Luogopreciso = muss.Luogopreciso,
Descrizione = muss.Descrizione,
NumeroTel = muss.NumeroTel,
IndirizzoEmail = muss.IndirizzoEmail,
Immagine= muss.Immagine,
};
}
await conn.InsertAsync(musPref);
In another project I need to recover the database created and insert objects inside a ListView, But I do not know how to proceed ..
try
{
StorageFile data = await ApplicationData.Current.LocalFolder.GetFileAsync("Database.db");
}
catch(Exception)
{
}
And now??
I would like to retrieve the database created above and use it, inserting objects "Musei" that are in it and display it in a ListView
If you want to read from the database you created earlier, you can do the following:
// Get a connection to the database that is in the local folder.
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db");
var con = new SQLiteAsyncConnection(dbPath, true);
// Get all "Musei" in the database stored in the "Musei" table.
var results = await con.QueryAsync<Musei>("SELECT * FROM Musei");
If you only want the Musei that match a certain field value, for example: you only want to read those in the specific location "Rome", you can do that like this:
var searchLocation = "Rome"; // for example entered by the user in your UI.
// Get only the "Musei" in `searchLocation`.
var results = await con.QueryAsync<Musei>("SELECT * FROM Musei WHERE Luogopreciso ='?'", searchLocation);
An alternative, if you are only querying a single table, is to do it like this, using LINQ:
var query = con.Table<Musei>();
// or, if looking for `searchLocation`:
var query = con.Table<Musei>().Where(m => m.Luogopreciso == "Rome");
you can then get this as a list using:
var result = await query.ToListAsync();
To find out which tables are actually present in your opened database files, you can do this:
var nTables = 0;
System.Diagnostics.Debug.WriteLine("Tables in the database");
foreach (var mapping in con.TableMappings)
{
System.Diagnostics.Debug.WriteLine(mapping.TableName);
nTables++;
}
System.Diagnostics.Debug.WriteLine("{0} tables in total", nTables);
and look at the debug output.
Is there a way to run a shared team query, by name, through the TFS 2013 client object API
I'm working on a C# script that will do some work based off of the results of a shared team query. I don't want to have to maintain the query in the TFS UI as well as in my script; I'd prefer to just run the registered query that my team uses, but then just play with the results. When I write "registered query" I'm just referring to a query that I wrote in the TFS UI and saved as a shared query.
In other words: I'd like to use the TFS UI to create a query, save the file in my "shared queries" list, call it "foo", then access foo from the client object API in my script.
I see that there is a GetQueryDefinition(GUID) method off of WorkItemStore, but where would I get the GUID for a shared team query?
Sample code that should do what you need
///Handles nested query folders
private static Guid FindQuery(QueryFolder folder, string queryName)
{
foreach (var item in folder)
{
if (item.Name.Equals(queryName, StringComparison.InvariantCultureIgnoreCase))
{
return item.Id;
}
var itemFolder = item as QueryFolder;
if (itemFolder != null)
{
var result = FindQuery(itemFolder, queryName);
if (!result.Equals(Guid.Empty))
{
return result;
}
}
}
return Guid.Empty;
}
static void Main(string[] args)
{
var collectionUri = new Uri("http://TFS/tfs/DefaultCollection");
var server = new TfsTeamProjectCollection(collectionUri);
var workItemStore = server.GetService<WorkItemStore>();
var teamProject = workItemStore.Projects["TeamProjectName"];
var x = teamProject.QueryHierarchy;
var queryId = FindQuery(x, "QueryNameHere");
var queryDefinition = workItemStore.GetQueryDefinition(queryId);
var variables = new Dictionary<string, string>() {{"project", "TeamProjectName"}};
var result = workItemStore.Query(queryDefinition.QueryText,variables);
}
I am performing an insert operation with Entity Framework 5.
My code inserts a new row from a user input and parsed values in another method. The debug operation shows all object attributes have a value before the insert operation is called, the code executes without any exception, and the row is updated in the LocalDb, but content column value is missing or never saved.
Here is my entity framework code:
public async Task<IHttpActionResult> PostFormData()
{
var profile = db.ProfileRepository.dbSet.Where(m => m.profileId == 1).FirstOrDefaultAsync().Result;
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var research = new Research();
research.profile = profile;
string root = HttpContext.Current.Server.MapPath("~/documentSafe");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
research.title = provider.FormData["title"];
research.researchAbstract = provider.FormData["researchAbstract"];
research.publisher = provider.FormData["publisher"];
var areaList = new List<ResearchArea>();
string areas = provider.FormData["researchArea"];
foreach (var r in areas.Split(','))
{
var area = new ResearchArea()
{
name = r,
departmentId = profile.departmentId
};
areaList.Add(area);
}
research.researchArea = areaList;
research.researchType = new ResearchType()
{
name = provider.FormData["type"]
};
string content = WebUtility.HtmlEncode(parser.convert(provider.FileData[0]));
research.content = content;
using (var context = new AcademicContext())
{
context.Research.Add(research);
await context.SaveChangesAsync();
}
return Ok();
}
catch (System.Exception e)
{
return InternalServerError(e);
}
}
The missing column is a parsed html string encoded using webutility and has an average size of 15,000 characters. I have checked the database column attribute too, and it is set to nvarchar(MAX).
If I insert a sample plain text to the column, the value get saved, but if I pass the encoded html string it does not.
Any suggestions why my column will not be null but still not contain any value.
Solution: The sql server explorer in visual studio seem to display an empty column when the character size is greater than 4000. I ran multiple test to verity this. I could get the content of the empty column by running raw sql select query.
I was able to successfully insert a new document using the following code but I was not able to get the _id of the newly inserted document.
After the insert, user is null. Thank you!
MongoServer server = MongoServer.Create();
MongoDatabase test = server.GetDatabase("Test");
MongoCollection<BsonDocument> users = test.GetCollection("Users");
BsonDocument user = new BsonDocument();
user.Add("FirstName", "John");
user.Add("LastName", "Michael");
user.Add("Address", "123 Main Street");
user.Add("City", "Newport Beach");
user.Add("State", "CA");
user.Add("ZipCode", "92660");
user.Add("Email", "John.Michael#myemail.com");
user.Add("CreatedDate", DateTime.Now);
user.Add("IPAddress", "10.1.1.1");
user = users.Save(user);
string idSTring = user["_id"].ToString().Replace("\"", "");
I made some tests with the official driver and found that method MongoCollection.Save returns null; So do not assign result to your constructed user:
//user = users.Save(user);
users.Save(user);
string idStr = user["_id"].ToString();
Console.WriteLine("_id == {0}", idStr);
About drivers check this and this
Use this C# driver and your code will be like this:
var refMongo = new Mongo();
refMongo.Connect();
var test = refMongo.GetDatabase("Test");
var users = test.GetCollection("Users");
var user = new MongoDB.Document();
user.Add("FirstName", "John");
user.Add("LastName", "Michael");
user.Add("Address", "123 Main Street");
user.Add("City", "Newport Beach");
user.Add("State", "CA");
user.Add("ZipCode", "92660");
user.Add("Email", "John.Michael#myemail.com");
user.Add("CreatedDate", DateTime.Now);
user.Add("IPAddress", "10.1.1.1");
users.Save(user);
string idSTring = user["_id"].ToString();
Console.WriteLine(idSTring);
I got _id == 4cd9e240df53ca112c000001
Good luck!;)