I have a query that needs to return a product and all its information by its "_id" but when I print the results I get the cursor and not the values in the MongoDB collection?
var query_id = dbCollection.Find(Query.EQ("_id", "50ed4ea05baffd13a44d0154"));
return query_id.ToString();
The result is
MongoDB.Driver.MongoCursor`1[MongoDB.Bson.BsonDocument]
EDIT
I have tried the .ToJson() method but that only returns []
var query_id = dbCollection.Find(Query.EQ("_id", "50ed4ea05baffd13a44d0154"));
var r = query_id.ToJson();
EDIT
Here is the Code, its a basic Windows Form App that I am doing basic tests with:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "mongodb://127.0.0.1";
var server = MongoServer.Create(connectionString);
if (server.State == MongoServerState.Disconnected)
{
server.Connect();
label1.Text = ("Server is connected to: " + connectionString);
button1.Enabled = false;
}
else
{
label1.Text = ("Server Error Check DB location");
}
var conn = server.GetDatabase("Acord");
var dbCollection = conn.GetCollection("Mappings");
var query = dbCollection.FindAll();
//textBox2.Text = query.ToList().ToJson();
var query_first = query.First();
//textBox2.Text = cursorResult.ToString();
var query_id = Query.EQ("_id", "1");//What ID do I put in here? This is were the error is now!
var entity = dbCollection.FindOne(query_id);
textBox2.Text = entity.ToString();
}
}
Here is the error I get:
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe
I am clearly missing something here?
As you've noticed, Find() returns a cursor, which could be used to traverse the query results one-by-one. But you need only a single returned item, so use FindOne() - it will return you an item instead of a cursor.
You should also use the correct query. E.g. By-Default MongoDB uses internal 12-bytes ObjectID, so Query.EQ("_id", "1") is simply wrong. If you are not sure about the query, call FindOne() without any arguments.
I would recommend you trying the online MongoDB shell (at http://mongodb.org) which contains an interactive MongoDB tutorial.
Related
I have database connection setup with Entity Framework. I've created multiple stored procedures and one of them has an output parameter that I need in my application.
Procedure in c# :
public virtual ObjectResult<Nullable<System.Guid>> AjouterProfesseur(string prenom, string nom, ObjectParameter identity)
{
var prenomParameter = prenom != null ?
new ObjectParameter("prenom", prenom) :
new ObjectParameter("prenom", typeof(string));
var nomParameter = nom != null ?
new ObjectParameter("nom", nom) :
new ObjectParameter("nom", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<System.Guid>>("AjouterProfesseur", prenomParameter, nomParameter, identity);
}
To retrieve the output parameter I use following (this is also where I have to put my breakpoint and step over it for it to work):
public static Guid AddProfesseur(string prenom, string nom)
{
using (ExamenProjetIntegrationEntities db = new ExamenProjetIntegrationEntities())
{
ObjectParameter objParam = new ObjectParameter("identity", typeof(Guid));
var resultToReturn = db.AjouterProfesseur(prenom, nom, objParam);
return Guid.Parse(objParam.Value.ToString());
}
}
Then I have a business layer who calls that method again :
public static Guid addProfesseur(string prenom, string nom)
{
try
{
var data = Data.AddProfesseur(prenom, nom);
return data;
}
catch (Exception e)
{
var sqlex = e.InnerException as SqlException;
if (sqlex != null)
{
switch (sqlex.Number)
{
default:
throw new Exception(sqlex.Number + " - " + sqlex.Message);
}
}
throw e;
}
}
And finally in my API controller I'm using following statement :
var idProfesseur = BL.addProfesseur(professeur.prenom, professeur.nom);
I call the method with ajax in my ASP.NET MVC view.
Does anyone has any idea why this is and how I can solve this issue?
EDIT :
Following link is exactly what I'm doing : Executing SQL Stored Procedure with Output Parameter from Entity Framework .But my problem is the fact that I need to step through it for it to work
Output parameters are not available until the return result has been read completely, or the underlying DbDataReader is closed.
See the Parameters section of ObjectContext.ExecuteFunction, and the second sentence of this section on DataReaders
You can force this by evaluating the result with LINQ.
public static Guid AddProfesseur(string prenom, string nom)
{
using (ExamenProjetIntegrationEntities db = new ExamenProjetIntegrationEntities())
{
ObjectParameter objParam = new ObjectParameter("identity", typeof(Guid));
var resultToReturn = db.AjouterProfesseur(prenom, nom, objParam).Count();
return Guid.Parse(objParam.Value.ToString());
}
}
You could also use .ToList(), .FirstOrDefault(), or whatever method you prefer to read the underlying result.
Using the underlying SqlParameter would require .Direction = ParameterDirection.Output. ObjectParameter doesn't have an equivalent setting. Instead I believe the parameter direction is configured in your model.
I have an invoice with multiple lines that I want to consolidate into one line. It takes the and iterates through each . It sums each to a variable. After the loop, it should create a new line on the invoice and delete the others.
I keep getting a "TxnLineID: required field is missing" even though I am providing it as "-1" for a new line:
private static void Main(string[] args)
{
// creates the session manager object using QBFC
var querySessionManager = new QBSessionManager();
// want to know if a session has begun so it can be ended it if an error happens
var booSessionBegun = false;
try
{
// open the connection and begin the session with QB
querySessionManager.OpenConnection("", "Test Connection");
querySessionManager.BeginSession("", ENOpenMode.omDontCare);
// if successful then booSessionBegin = True
booSessionBegun = true;
// Get the RequestMsgSet based on the correct QB Version
var queryRequestSet = GetLatestMsgSetRequest(querySessionManager);
// Initialize the message set request object
queryRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// QUERY RECORDS **********************
// appendInvoiceQuery to request set
// only invoices that start with the consulting invoice prefix
// include all of the line items
// only unpaid invoices
var invoiceQ = queryRequestSet.AppendInvoiceQueryRq();
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.MatchCriterion.SetValue(ENMatchCriterion.mcStartsWith);
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.RefNumber.SetValue("ML-11");
invoiceQ.ORInvoiceQuery.InvoiceFilter.PaidStatus.SetValue(ENPaidStatus.psNotPaidOnly);
invoiceQ.IncludeLineItems.SetValue(true);
// DELETE INVOICE ***********************************
// var deleteI = queryRequestSet.AppendTxnDelRq();
// deleteI.TxnDelType.SetValue(ENTxnDelType.tdtInvoice);
// deleteI.TxnID.SetValue("3B57C-1539729221");
// Do the request and get the response message set object
var queryResponseSet = querySessionManager.DoRequests(queryRequestSet);
// Uncomment the following to view and save the request and response XML
var requestXml = queryRequestSet.ToXMLString();
// Console.WriteLine(requestXml);
SaveXML(requestXml, 1);
var responseXml = queryResponseSet.ToXMLString();
// Console.WriteLine(responseXml);
SaveXML(responseXml, 2);
// Get the statuscode of the response to proceed with
var respList = queryResponseSet.ResponseList;
var ourResp = respList.GetAt(0);
var statusCode = ourResp.StatusCode;
// Test what the status code
if (statusCode == 0)
{
// Parse the string into an XDocument object
var xmlDoc = XDocument.Parse(responseXml);
// Set the xmlDoc root
var xmlDocRoot = xmlDoc.Root.Element("QBXMLMsgsRs")
.Element("InvoiceQueryRs")
.Elements("InvoiceRet");
var i = 1;
// Iterate through the elements to get values and do some logic
foreach (var invoiceElement in xmlDocRoot)
{
// Create connection to update
var updateSessionManager = new QBSessionManager();
updateSessionManager.OpenConnection("", "Test Connection");
updateSessionManager.BeginSession("", ENOpenMode.omDontCare);
// Make the request set for updates
var updateRequestSet = GetLatestMsgSetRequest(updateSessionManager);
updateRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// Set the variables required to edit a file
var txnId = (string) invoiceElement.Element("TxnID");
var editSequence = (string) invoiceElement.Element("EditSequence");
var xmlLineItemRoot = invoiceElement.Elements("InvoiceLineRet");
var feeAmount = 0.0f;
foreach (var invoiceLineItemElement in xmlLineItemRoot)
{
if (invoiceLineItemElement.Element("ItemRef").Element("FullName").Value == "Consulting Fees:Consulting")
{
feeAmount = float.Parse(invoiceLineItemElement.Element("Amount").Value) + (float) feeAmount;
}
}
//// UPDATING RECORDS ******************************
//// TxnID and EditSequence required
var invoiceM = updateRequestSet.AppendInvoiceModRq();
invoiceM.TxnID.SetValue(txnId);
invoiceM.EditSequence.SetValue(editSequence);
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.TxnLineID.SetValue("-1");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.Amount.SetValue((double)feeAmount);
updateSessionManager.DoRequests(updateRequestSet);
i++;
updateSessionManager.EndSession();
updateSessionManager.CloseConnection();
}
}
// end and disconnect after done
querySessionManager.EndSession();
booSessionBegun = false;
querySessionManager.CloseConnection();
}
catch (Exception e)
{
// if it couldn't connect then display a message saying so and make sure to EndSession/CloseConnection
Console.WriteLine(e.Message.ToString() + "\nStack Trace: \n" + e.StackTrace + "\nExiting the application");
if (booSessionBegun)
{
querySessionManager.EndSession();
querySessionManager.CloseConnection();
}
}
}
Furthermore, I want it to remove the lines from the invoice that were used in the sum. I've read conflicting information on how to do this.
One camp says, don't specify those lines and it will erase them when the updateRequestSet is executed. Another contradicts by saying that not specifying them, it will retain them. Can someone please clear this up. I haven't gotten far enough to test, however.
Oh and here is the entirety of the error:
InvoiceMod
ORInvoiceLineModList:
element(2) - InvoiceLineMod:
TxnLineID: required field is missing
End of InvoiceLineMod
End of ORInvoiceLineModList
End of InvoiceMod
Stack Trace:
at Interop.QBFC13.IQBSessionManager.DoRequests(IMsgSetRequest request)
at ConsolidateInvoiceLineItems.Program.Main(String[] args) in C:\qb\QuickBooks\ConsolidateInvoiceLineItems\ConsolidateInvoiceLineItems\Program.cs:line 226
Exiting the application
Wish I could take credit for this, but actually got help from the Intuit Developers forum.
Need to change the multiple Append() to the following:
var invoiceModLineItems = invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod;
invoiceModLineItems.TxnLineID.SetValue("-1");
invoiceModLineItems.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceModLineItems.Amount.SetValue((double)feeAmount);
I've done a fair bit of research, but I can't find anyone who has the same problem as me (sadly). I am using LiteDB to create a NoSQL database.
When the program first runs and the database is created, the query in the example below works just fine. When I restart the program, it fails saying that it is null. The weird thing is, if I do a count it returns 8 records. So something exists - why can't I pull it out?
Here is my code:
public class ExternalTools
{
public int Id { get; set; }
public string Name { get; set; }
public string[] Types { get; set; }
}
public void GetAll()
{
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var folderPath = localFolder.Path;
var filePath = Path.Combine(folderPath, #"MyData4.db");
using (var db = new LiteDatabase(filePath))
{
Tools = db.GetCollection<ExternalTools>("externalTools");
if (Tools.Count() == 0)
{
CreateToolList();
// Index document using document Name property
Tools.EnsureIndex(x => x.Name);
}
}
Debug.WriteLine(Tools.Count());
var temp = Tools.FindAll(); // null error
var test = Tools.FindById(1); // another null error
Debug.WriteLine(test.Name); //
}
Thanks!
Well, I figured it out (so many hours of debugging wasted!) My code is in the wrong spot, if I move it into the using statement it works just fine. I suspect this has to do with the fact that on the first run it's adding stuff into the colection so it has the proper reference. Regardless, this code works:
using (var db = new LiteDatabase(filePath))
{
Tools = db.GetCollection<ExternalTools>("externalTools");
if (Tools.Count() == 0)
{
CreateToolList();
// Index document using document Name property
Tools.EnsureIndex(x => x.Name);
}
Debug.WriteLine(Tools.Count());
var temp = Tools.FindAll(); // null error
var test = Tools.FindById(1); // another null error
Debug.WriteLine(test.Name); //
}
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);
I am learning C# and am using Visual Studio 2010 to build a payroll program. I get an error "Cannot implicitly convert type 'int' to 'short'".
My code is :
private void btn_add_Click(object sender, EventArgs e)
{
try
{
// Get service instance
var employerPeriodService = Program.Kernel.Get<IEmployerPeriodService>();
// Get new code
var newCode = employerPeriodService.GenerateSAPCode();
// Create object
var employerPeriodAdd =
new EmployerPeriod
{
Code = newCode,
Name = newCode,
U_Tax_year = int.Parse(cb_tax_year.Text),
//U_Day_hrs = cb_number_hours.Text,
//U_Week_days = cb_number_days_week.Text,
//U_Week_hrs = txt_number_hours_week.Text,
//U_Month_days = cb_number_days_month.Text,
//U_Month_hrs = txt_number_hours_month.Text,
//U_Fortnight_days = cb_number_days_fortnight.Text,
//U_Fortnight_hrs = txt_number_hours_fortnight.Text,
//U_Weeks_in_month = cb_avg_weeks_month.Text,
//U_No_of_Fortnights = cb_avg_fortnights_month.Text,
U_Starting_period = Convert.ToDateTime(dateTimePicker1.Text),
U_Ending_period = Convert.ToDateTime(dateTimePicker2.Text)
//U_Comments = txt_comments.Text
};
// Save record
employerPeriodService.AddEmployerPeriod(employerPeriodAdd);
MessageBox.Show("Employer Payroll Period Added Successfully. Intake Ref: " + newCode.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (RulesException ex)
{
MessageBox.Show(ex.GetErrorMessages(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
In Microsoft SQL Server where my database is, U_Tax_year is defined as smallint. What do I need to do to solve this error. Do I convert what I get from the combo box 'cb_tax_year.Text' to int and how do I achieve this.
Any help appreciated.
I suspect it's as simple as changing this:
U_Tax_year = int.Parse(cb_tax_year.Text),
to this:
U_Tax_year = short.Parse(cb_tax_year.Text),
Basically you should check the type of the U_Tax_year property and make sure you parse the text appropriately so that the result of the RHS of the = sign is assignment-compatible with the property type.
SQLServer's smallint is the equivalent of c#'s short. so try short.Parse() instead of int.Parse()
Use short.Parse rather than int.Parse