I need to retrieve the last row one data field. id is the primary key of my table. I'm trying to retrieve my final row data using its id
public AddExpenses[] GetFinalExpense(int numberOfExpenses)
{
return Conn.Table<AddExpenses>()
.OrderByDescending(expenses => expenses.Id)
.Take(numberOfExpenses)
.ToArray();
}
In my view model I have
var finalexpense = database.GetFinalExpense(1);
this is my code. when I tried to use this final row data to retrieve single data
ExpenseLabel = "Your expense is"+finalexpense;
in here final expense it does not show properties of the table to call. I need my finalexpense property to call it does not work
Concatenating a string with an object uses the default implementation of ToString which will yield something like AddExpenses[] for you, if finalexpense has a value !=null, since it is an array.
First of all, you'll have to get the item in the array
var finalExpenses = database.GetFinalExpense(1);
var finalExpense = finalExpenses[0];
Furthermore you'll have to make sure that your object is formatted properly. You could implement your own ToString method in AddExpenses class, but the simplest way would be to use string interpolation
var formattedExpense = $"{finalExpense.Expense} ({finalExpense.Date}, {finalExpense.Category})";
ExpenseLabel = $"Your expense is {formattedExpense}";
How you build formattedExpense is up to you, take the proposed string as a starting point and adapt it to your needs.
Related
I have a Pages smart search index which uses the Standard analyzer. When I examine the generated index in Luke I can see that integer fields have a specific format. For example, all pages created by global administrator have the documentcreatedbyuserid field set to 10000000053.
Reading the documentation I see that integer fields like this need to be searched using a particular syntax:
+DocumentCreatedByUserID;(int)53;Administrator
However, when I pass this string to the following code as the searchQuery variable I get no results.
// Get search results
var parameters = new SearchParameters()
{
AttachmentOrderBy = "",
AttachmentWhere = "",
CheckPermissions = false,
ClassNames = null,
CombineWithDefaultCulture = false,
CurrentCulture = this.Context.CultureCode,
DefaultCulture = CultureHelper.GetDefaultCultureCode(this.Context.SiteName),
DisplayResults = resultsPerPage,
NumberOfProcessedResults = 100,
Path = startPath,
SearchFor = searchQuery,
SearchInAttachments = false,
SearchIndexes = index,
SearchSort = sort,
StartingPosition = (page - 1) * resultsPerPage,
User = this.Context.User.UserInfo
};
ds = CMS.Search.SearchHelper.Search(parameters);
This same code works fine for text field search queries. Can anyone explain:
Is there anything obvious I'm doing wrong?
What is the purpose of the final part of the +DocumentCreatedByUserID;(int)53;Administrator query. Why should I need to pass a text value here?
The field I actually want to search is a custom page type field called newstypeid, which I can see is storing its value in the same way in the index (e.g. a value of 34 is stored as 10000000034).
In Luke if I query +newstypeid:10000000034 I get results. So maybe an easier solution is to find a way to translate an integer to this Lucene format? (i.e. 34 to 10000000034)
UPDATE WITH SOLUTION
Thanks to #richard-Šůstek for pointing me in the right direction. The following method will return a search clause in the required format:
protected string GetIntegerIdClause(string field, int id)
{
var condition = string.Format("{0}:(int){1}", field, id).ToLower();
return SearchSyntaxHelper.CombineSearchCondition(null, new SearchCondition(condition, SearchModeEnum.ExactPhrase, SearchOptionsEnum.NoneSearch));
}
I think you should use SearchValueConverter class from the namespace CMS.Search. This class has static methods to convert specific data type values (int,datetime,etc.) to it's string representation for search terms construction.
Can you try using something like this to transform the searchQuery?:
var condition = new SearchCondition(null, searchModeEnum, SearchOptionsEnum.FullSearch);
searchQuery = SearchSyntaxHelper.CombineSearchCondition(searchText, condition);
I noticed that Kentico is internally calling this method when passing the value from search text box to SearchParameters. I haven't had a chance to test this though. Maybe some other method in SearchSyntaxHelper would be useful too.
I have to dynamically execute queries which will come from database.The query has dynamic fields,which needs to be converted into map as key value pairs and send to view.For ex
one query may return only one fields and other may return more than two field of multiple rows.I have to write code in such way that it will work for n no.of fields and return it as map using spring jdbc.
Spring offers two ways to solve your problem.
Approach 1: use queryForList method from JdbcTemplate class. this will return List of Map populated by column names as key , and DB record as value. you have to manualy iterate over the list. each map object inside the list represents a single row in resultset.
example :
List<Map<String, Object>> result = jdbcTemplate.queryForList(query, new Object[]{123});
Iterator items = result.iterator();
while(items.hasNext()){
Map<String, Object> row = (Map<String, Object>) items.next();
System.out.println(row);
}
Approach 2 : this dosen't exactly match your requirements, but little faster than the first approach also more coding involved. you can use queryForRowSet method.
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(query, new Object[]{3576});
int columnCount = rowSet.getMetaData().getColumnCount();
System.out.println(columnCount);
while(rowSet.next()){
for(int id =1 ; id <= columnCount ; id ++){
System.out.println(rowSet.getString(id)) ;
// your custom logic goes here
}
}
I'm trying to access a map column type using Astyanax.
From the examples I've taken the following. I'm looping the rows and can get the data from all the columns except the column storename which has datatype MAP. I assume I need to loop over the elements of the map to get the data into my object but I can't figure out how to do get the map data from the column.
I'm trying column.getValue and have tried getByteBuffer but can't get either to work. I can get a column object and I see there is a ColumnMap interface but I can't figure out how to get the data into an object that extends or uses it. I also see a MapSerializer interfaces but not sure how to implement that either...
List<Store> stores = new ArrayList<Store>();
for (Row<Integer, String> row : result.getResult().getRows()) {
Store store = new Store();
ColumnList<String> columns = row.getColumns();
store.setStoreID(columns.getStringValue("store_id", null));
store.setShopName(columns.getStringValue("shopname", null));
// lost trying to get the columns Map data here
// should I loop the map or pass the data straight to my store object as a map?
// How do I access the map data in this column?
for ( Map<String, String> map : columns.getValue("storename", imap, result).getResult() )
{
store.setStoreNames( "lang", "storename");
}
stores.add(store);
}
I'm a bit confused with getValue() as it takes a Serializer as it's 2nd argument and a default as it's 3rd. How do I pass the MapSerializer in as the 2nd argument or should I even be using getValue() method? Is the default a key value from the Map? If I want to return all values in the map what then? Thanks.
In the end this worked for me. And I was able to loop through the entries in the Map using the technique provided for looping maps here.
Map<String, String> map = columns.getValue("storename",
new MapSerializer<String, String>(UTF8Type.instance, UTF8Type.instance)
, new HashMap<String ,String>());
I have updated my meteor yesterday and tried using the new Meteor.Collection.ObjectID.
But since with no success. First i updated my collections in this way:
myCollection = new Meteor.Collection('mycollection', {idGeneration: 'MONGO'}
Now, normal new inserts have an _id like Wi2RmR6CSapkmmdfn... (?)
Then i have a collection with an array included. I like to have an unique id for every object in this array. So i $push an object with a field like id: new Meteor.Collection.ObjectID() into my array. The result in the database is like this: ObjectId("5b5fc278305d406cc6c33756"). (This seems to be normal.)
But later i want to update my pushed object, if the id equals an id, which i stored as data attribute in an html tag before.
var equals = EJSON.equals(dbId, htmlId); (This results every time in false. So i logged the values dbId and htmlId into the console with console.log(typeof dbId, dbId);)
The values of this two variables is as follows:
object { _str: 'a86ce44f9a46b99bca1be7a9' } (dbId)
string ObjectID("a86ce44f9a46b99bca1be7a9") (htmlId; this seems to be correct, but why is a custom type a string?)
How to use the Meteor.Collection.ObjectID correct?
When placing your htmlId in your html you need to put it in as a string and not as an object, remember _id is an object now, handlebars is guessing and using toString() & thats why it shows up as ObjectID("...").
So if you're using {{_id}} in your html you now need to use {{_id.toHexString}} to properly extract the string part of it out
When you extract this html value with your javascript you need to make it back into an objectid:
js:
var valuefromhtml = "a86ce44f9a46b99bca1be7a9"; //Get with Jquery,DOM,etc
htmlId = new Meteor.Collection.ObjectID(valuefromhtml); //see: http://docs.meteor.com/#collection_object_id
EJSON.equals(htmlId, dbId); //Should be true this time
Hey all, I was able to do this via a SELECT CASE statement, however I'm always trying to improve my code writing and was wondering if there was a better approach. Here's the scenario:
Each document has x custom fields on it.
There's y number of documents
However there's only 21 distinct custom fields, but they can obviously have n different combinations of them depending on the form.
So here's what I did, I created an object called CustomFields like so:
Private Class CustomFields
Public agentaddress As String
Public agentattorney As String
Public agentcity As String
Public agentname As String
Public agentnumber As String
Public agentstate As String
Public agentzip As String
... more fields here ....
End Class`
Then I went ahead and assigned the values I get from the user to each of those fields like so:
Set All of Our Custom Fields Accordingly
Dim pcc As New CustomFields()
pcc.agentaddress = agent.address1
pcc.agentattorney = cplinfo.attorneyname
pcc.agentcity = agent.city
pcc.agentname = agent.agencyName
pcc.agentnumber = agent.agentNumber
pcc.agentstate = agent.state
pcc.agentzip = agent.zip ....other values set to fields etc.
Now the idea is based upon what combo of fields come back based upon the document, we need to assign the value which matches up with that custom field's value. So if the form only needed agentaddress and agentcity:
'Now Let's Loop Through the Custom Fields for This Document
For Each cf As vCustomField In cc
Dim customs As New tblCustomValue()
Select Case cf.fieldname
Case "agentaddress"
customs.customfieldid = cf.customfieldid
customs.icsid = cpl.icsID
customs.value = pcc.additionalinfo
Case "agentcity"
customs.customfieldid = cf.customfieldid
customs.icsid = cpl.icsID
customs.value = pcc.additionalinfo
End Select
_db.tblCustomValues.InsertOnSubmit(customs)
_db.SubmitChanges()
This works, however we may end up having 100's of fields in the future so there a way to somehow "EVAL" (yes I know that doesn't exist in vb.net) the cf.fieldname and find it's corresponding value in the CustomFields object?
Just trying to write more efficient code and looking for some brainstorming here. Hopefully my code and description makes sense. If it doesn't let me know and I'll go hit my head up against the wall and try writing it again.
If I am reading your question correctly, you are trying to avoid setting the value of fields, when the field isn't used. If so, I would recommend you just go ahead and set the field to nothing in that case.