Dynamic Field Name in dynamic type in ASP.NET MVC - entity-framework

I am using Entity Framework and my table structure is as below.
Key, dec2000, dec2001, dec2002,... dec2020
so, while update in loop if for all columns in i have to specify the column name like,
for (int j = 0; j < intEndYear - intStartYear; j++)
{
// Find value from FormCollection
// Assign it to object
OBJECT.DEC2000 = 1;
}
so, one way is i have to check for year and make condition check whether year = 2000 then use dec2000 field and so on.
So i tried to use Dynamic type so i can specify field name dynamically like
dynamic objLevel = objDetailSum.GetSingle(parameters);
so, while updating i am trying to do like
// trying to make field name
string stryear = "DEC" + year.ToString();
objLevel.stryear = 1; // should read objLevel.dec2000 = 1;
I know this will not work as i don't have strYear column in my table.
Question : Is there any other good way to handle this situation? so i don't have to check for each and every column and can use dynamic instead/.
Appreciate any direction.

You could use Reflection. See here for more information
//assuming "myInstance" is an instance of the EF class:
string strYear = "DEC"+year.ToString();
var pi =myInstance.GetType().GetProperty(styYear);
if (pi!=null)
{
pi.SetValue(MyInstance,1);
}

Related

Sort/Order an Undetermined Number of Columns (LINQ\Entity Framework)

Need to sort/order a list of data based on an undetermined number of columns (1 or more).
What i'm trying to do is loop through the desired columns and add an OrderBy or ThenBy based on their number to the query'd list, but i'm unsuccessful...
Done this, but it doesn't compile:
var query = GetAllItems(); //returns a IQueriable list of items
//for each selected column
for (int i = 0; i < param.Columns.Length; i++)
{
if (i == 0)
{
query = query.OrderBy(x => x.GetType().GetProperty(param.Columns[i].Name));
}
else
{
//ERROR: IQueriable does not contain a definition for "ThenBy" and no extension method "ThenBy"...
query = query.ThenBy(x => x.GetType().GetProperty(param.Columns[i].Data));
}
}
How can i resolve this issue? Or any alternative to accomplish this requirement?
SOLUTION: #Dave-Kidder's solution is well thought and resolves the compile errors i had. Just one problem, OrderBy only executes (actually sorts the results) after a ToList() cast. This is an issue because i can't convert a ToList back to an IOrderedQueryable.
So, after some research i came across a solution that resolve all my issues.
Microsoft assembly for the .Net 4.0 Dynamic language functionality: https://github.com/kahanu/System.Linq.Dynamic
using System.Linq.Dynamic; //need to install this package
Updated Code:
var query = GetAllItems(); //returns a IQueriable list of items
List<string> orderByColumnList = new List<string>(); //list of columns to sort
for (int i = 0; i < param.Columns.Length; i++)
{
string column = param.Columns[i].Name;
string direction = param.Columns[i].Dir;
//ex.: "columnA ASC"
string orderByColumn = column + " " + direction;
//add column to list
orderByColumnList.Add(orderBy);
}
//convert list to comma delimited string
string orderBy = String.Join(",", orderByColumnList.ToArray());
//sort by all columns, yay! :-D
query.OrderBy(orderBy).ToList();
The problem is that ThenBy is not defined on IQueryable, but on the IOrderedQueryable interface (which is what IQueryable.OrderBy returns). So you need to define a new variable for the IOrderedQueryable in order to do subsequent ThenBy calls. I changed the original code a bit to use System.Data.DataTable (to get a similar structure to your "param" object). The code also assumes that there is at least one column in the DataTable.
// using System.Data.DataTable to provide similar object structure as OP
DataTable param = new DataTable();
IQueryable<DataTable> query = new List<DataTable>().AsQueryable();
// OrderBy returns IOrderedQueryable<TSource>, which is the interface that defines
// "ThenBy" so we need to assign it to a different variable if we wish to make subsequent
// calls to ThenBy
var orderedQuery = query.OrderBy(x => x.GetType().GetProperty(param.Columns[0].ColumnName));
//for each other selected column
for (int i = 1; i < param.Columns.Count; i++)
{
orderedQuery = orderedQuery.ThenBy(x => x.GetType().GetProperty(param.Columns[i].ColumnName));
}
you should write ThenBy after OrderBy like this:
query = query
.OrderBy(t=> // your condition)
.ThenBy(t=> // next condition);

How to populate table with specific values instead of pseudo-random?

i'm trying to modify the vaadin addressbook app to a little different one with just the field names changed. but i do not know how to populate it with specific value instead of the pseudo-random as done in the vaadin tutorial example.
here is my code.
private static IndexedContainer createDummyDatasource() {
IndexedContainer ic = new IndexedContainer();
for (String p : fieldNames) {
ic.addContainerProperty(p, String.class, "");
}
String[] cnumber = { "1", "2", "3" };
String[] ctitle = { "a", "b", "c" };
String[] faculty = { "xxx" };
for (int i = 0; i < 3; i++) {
Object id = ic.addItem();
ic.getContainerProperty(id, CNUMBER).setValue(cnumber[(int) (cnumber.length * Math.random())]);
ic.getContainerProperty(id, CTITLE).setValue(ctitle[(int) (ctitle.length * Math.random())]);
ic.getContainerProperty(id, FACULTY).setValue(faculty[(int) (faculty.length * Math.random())]);
}
return ic;
}
please help..!!
You use the setValue to set the values shown in table. And also make sure the corresponding container property is set before populating them.
If you just want to know how to bind the address book demo to an MySQL database using SQLContainer, then you can have a look at https://vaadin.com/tutorial/sql which pretty much continues where the in-memory container left you.
Of course if you have some other binding to your data JPA, in-memory beans etc, you might want to have a look at the appropriate one for your needs.

Filter getElementsByTagName list by option values

I'm using getElementsByTagName to return all the select lists on a page - is it possible to then filter these based upon an option value, ie of the first or second item in the list?
The reason is that for reasons I won't go into here there are a block of select lists with number values (1,2,3,4,5 etc) and others which have text values (Blue and Black, Red and Black etc) and I only want the scripting I have to run on the ones with numerical values. I can't add a class to them which would more easily let me do this however I can be certain that the first option value in the list will be "1".
Therefore is there a way to filter the returned list of selects on the page by only those whose first option value is "1"?
I am pretty sure that there is a better solution, but for the moment you can try something like:
var allSelect = document.getElementsByTagName("select");
var result = filterBy(allSelect, 0/*0 == The first option*/, "1"/* 1 == the value of the first option*/);
function filterBy(allSelect, index, theValue) {
var result = [];
for (var i = 0; i < allSelect.length; i++) {
if(allSelect[i].options[index].value == theValue ) {
result.push(allSelect[i]);
}
}
return result;
}
I managed to get this working by wrapping a simple IF statement around the action to be performed (in this case, disabling options) as follows:
inputs = document.getElementsByTagName('select');
for (i = 0; i < inputs.length; i++) {
if (inputs[i].options[1].text == 1) {
// perform action required
}
}
No doubt there is a slicker or more economic way to do this but the main thing is it works for me.

Xcode>Instruments>Automation>Mac: is there a way to use regular expression within Automation in Instruments

I am totally new to Instruments>Automation. Trying to test the internal app using Automation in Instruments.
Here is my problem:
Our app has the UI cells generated on the fly. There is no way to predict how many cells will be created and what name they will have. But, all of them will contain a certain string (like "Courses"). The question is - How, using Automation, find out if particular cell contain that string in its name?
You are able to get total cells count simply using "length" property.
var cellsCount = <YourUIATableViewObject>.cells().length;
UIALogger.logMessage("total cells count = " + cellCount);
After that you will be able to get cell properties and operate with them:
for (var i = 0; i < cellsCount; i ++)
{
var cellValue = <YourUIATableViewObject>.cells()[i].value();
var cellName = <YourUIATableViewObject>.cells()[i].name();
UIALogger.logMessage("Cell #"+i+" properties: cellValue ="+cellValue+"; cellName ="+cellName);
//Try to use match() or search() functions to find what you need.
if ( cellName.search("Courses") != -1 )
//if (cellValue.search("Courses") != -1 )
{
UIAlogger.logMessage("Cell #"+i+" contains 'Courses'");
}
else
{
UIAlogger.logMessage("Cell #"+i+" does not contain 'Courses'");
}
}
This JavaScript tutorial will help you:

ADO.NET Entity Data Model - order of executing query

When I run this code:
korlenEntities2 _db = new korlenEntities2();
for (int i = 0; i < 10; i++)
{
klienci klient = new klienci();
klient.nazwa = "Janek_" + i.ToString();
klient.miejscowosc = "-";
_db.AddToklienci(klient);
};
_db.SaveChanges();
records are added to database in random order, so my field ID is not filled correctly. this is important to me since I want to use it for later ordering
You cannot control the order of query execution unless you call SaveChanges after every query. Nor can you depend on auto-incremented keys to be sequential in all cases (consider replication). If order is important, you should add a field for that.