I'm simply trying to retrieve data from SQLite, but my code neither returns a value nor gives an error. Please help me out.
So far I've done
var test = new List<cdProdGroup>();
var db = new SQLiteConnection(path);
var test1 = db.Query<cdProdGroup>("SELECT * FROM cdProdGroup");
foreach (var item in test1) {
cdProdGroup cd = new cdProdGroup {
DIQ_PG_CD_EBS = item.DIQ_PG_CD_EBS,
DIQ_PG_DESC = item.DIQ_PG_DESC,
DVSN_CD = item.DVSN_CD
};
test.Add(cd);
}
I'm using Xamarin for coding
The SELECT * FROM cdProdGroup query is unnecessary as is the re-assignment into a new List<cdProdGroup>.
You can simplify the query like so:
var db = new SQLiteConnection(path);
var test = db.Table<cdProdGroup>().ToList();
Related
I want to retrieve the specific data using an array-values, but I don't know how to deal with it.
URL is like http://localhost/api/data?sym=aa&bb&cc
DB documents are like:
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
{"symbol":"dd","price":1.4}
{"symbol":"ee","price":1.5}
the expected result is:
[
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
]
My code is:
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
symbol = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
return _portf.Find(???).ToList();
}
??? is where I have failed to find a solution. or I am completely wrong with the find() method.
I really need your help. Thank you!
Find takes in a FilterDefinition object. For example, a common way of getting a document from MongoDB by its ID would be:
public T LoadRecordById<T>(string table, Guid id)
{
var collection = db.GetCollection<T>(table);
var filter = Builders<T>.Filter.Eq("Id", id);
return collection.Find(filter).First();
}
You can combine multiple FilterDefinition objects together using the Or method:
var filter1 = Builders<T>.Filter.Eq("symbol", symbol);
var filter2 = Builders<T>.Filter.Eq("symbol", symbol);
var filter3 = Builders<T>.Filter.Eq("symbol", symbol);
var filter = Builders<T>.Filter.Or(filter1, filter2, filter3);
Hope this helps (it does not hurt to be nice, does it, #Dharman?)
I've found a very promising way which works perfectly. Thanks to this video
rewrite the code"
[HttpGet()]
public IEnumerable<Data> Get(string sym)
{
var symlist = sym.Split('&');
//connect to database and collections
var client = new MongoClient("mongodb+srv://.....");
var db = client.GetDatabase("...");
var _portf = db.GetCollection<Data>("...");
-->var fitlerDefinition = Builders<Findata>.Filter.In(a => a.Symbol, symlist);
return _portf.Find(fitlerDefinition).ToList();
}
I am new in using Npgsql and I tried to make an helper in my asp.net project so that I can call it conveniently in my controllers method.
npgsqlqueryhelper
public DataSet ExecuteQueryWithParams(string commandText, params NpgsqlParameter[] parameters)
{
using (var connection = npgsqlcon.GetnpgsqlConnection())
using (NpgsqlCommand command = new NpgsqlCommand(commandText, connection))
{
DataSet ds = new DataSet();
command.Parameters.AddRange(parameters);
command.CommandTimeout = 5000;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(ds);
connection.Close();
return ds;
}
}
My Controller Method
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status()", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int>("get_payment_status")
}).ToList();
As I tried to run my program, I always encountered an error saying that function ln.get_payment_status() does not exist but when I tried to supply the parameters directly on the query
(e.g var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(1231,'06-18-2019')", parameterList).Tables[0];)
It gives me the data that I need. I don't know what is my mistake and I'm stuck here since yesterday. Can anyone help me with this? TIA
The parameter place holders are not automatically included in the function call. Try adding them:
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];
With the help of Sir #JGH, it turns out that my query is missing the parameter placeholders but after I edit it, I encountered an error regarding the datatype between the asp.net datetime and postgresql date so I added this code to remove the error.
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
So here is now the new code:
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int?>("get_payment_status")
}).ToList();
Thank you sir #JGH
Is it possible to dynamically ignore some properties when saving items with the .NET Object Persistence Model?
I don't want to decorate my class properties with DynamoDBIgnore because sometimes I do want to save the changes being made in those.
I have tried to set IgnoreNullValues to true however this did not work when saving items with a batch.
Code is as follows:
using (var context = new DynamoDBContext(awsClient, _dynamoDbContextConfig))
{
var batch = context.CreateBatchWrite<T>(
new DynamoDBOperationConfig {SkipVersionCheck = true, IgnoreNullValues = true});
batch.AddPutItems(items);
await context.ExecuteBatchWriteAsync(new BatchWrite[] {batch});
}
Shall I use the lower-level API for achieving this?
The lower level API (exposed through IAmazonDynamoDB / AmazonDynamoDbClient) is the only way I have found till now of updating individual properties of an existing DynamoDB document.
An example of this would be :
var updateItemRequest = new UpdateItemRequest
{
TableName = "search_log_table",
Key = new Dictionary<string, AttributeValue>
{
{"PK", new AttributeValue("pk_value")},
{"SK", new AttributeValue("sk_value")}
},
UpdateExpression = $"SET SearchCount = if_not_exists(SearchCount, :start) + :inc",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{":start", new AttributeValue {N = "0"}},
{":inc", new AttributeValue {N = "1"}}
},
ReturnValues = "UPDATED_NEW"
};
// _client is an instance of IAmazonDynamoDB
return _client.UpdateItemAsync(updateItemRequest);
This inserts a new record with PK = "pk_value", SK = "sk_value" if one does not exist.
The statement UpdateExpression = $"SET SearchCount = if_not_exists(SearchCount, :start) + :inc sets the SearchCount to 1 the first time, and increments the property by 1 on every subsequent invocation
Morning,
I am trying to pass a list of Amazon ASIN's so i can process them using the MWS API.
List<string> prodASINs = dc.aboProducts.Select(a => a.asin).ToList();
var count = prodASINs.Count();
//Loop through passing 10 at a time to AWS
for (var i = 0; i < count; i++)
{
var prodASINToSend = prodASINs.Skip(i * 10).Take(10).ToList();
//Send to AWS
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = productsURL;
MarketplaceWebServiceProducts.MarketplaceWebServiceProductsClient service = new MarketplaceWebServiceProductsClient(appname, version, accesskeyID, secretkey, config);
GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest();
request.SellerId = merchantID;
request.MarketplaceId = marketids[0];
request.ItemCondition = condition;
request.ASINList.ASIN = prodASINToSend;
However the request.ASINList.ASIN = prodASINToSend; is saying "Object reference not set to an instance of an object." However it is passing over the required List<string> prodASINToSend
Could anyone shed some light on this for em please?
The error means you forgot to declare a new instance of a class before trying to use the class object.
In your case the ASINList will need to be declared as a new instance of the ASINList class.
The following query is working successfully.
var tabs = (
from r in db.TabMasters
orderby r.colID
select new { r.colID, r.FirstName, r.LastName })
.Skip(rows * (page - 1)).Take(rows);
Now I want to return JsonResult as like
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs
select new { id = r.colID, cell = new string[] { r.FirstName, r.LastName } }).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
But it will gives me an error like:
The array type 'System.String[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List`1[System.String]' instead.
What should I do to get expected result?
I suspect that it's as simple as pushing the last part into an in-process query using AsEnumerable():
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs.AsEnumerable()
select new { id = r.colID,
cell = new[] { r.FirstName, r.LastName } }
).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
You may want to pull that query out of the anonymous type initializer, for clarity:
var rows = tabs.AsEnumerable()
.Select(r => new { id = r.colID,
cell = new[] { r.FirstName, r.LastName })
.ToArray();
var jsonData = new {
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page,
records = totalRecords,
rows
};
It's because it's adding to the LINQ query that is your tabs IQueryable. That is then trying to turn the LINQ expression into a SQL query and the provider doesn't support projecting arrays.
You can either change the assignment of the tabs variable's LINQ expression to use ToList to materialize the DB results right then and there, or you can add .AsEnumerable() to the LINQ expression assigned to the rows field of the anonymous type that is your JsonResult. AsEnumerable will demote the IQueryable to an IEnumerable which will prevent your second LINQ query from trying to be added to the DB query and just make it a LINQ-to-objects call like it needs to be.