How do I dynamically create an html table given only a table name in entity framework? - html

My code is more like creating an engine that when passed a table name variable, will construct the table dynamically. This is the code I'm already working on. In my controller,
public ActionResult ViewTable(string tablename)
{
ScsContext context = new ScsContext();
List<string> columnNames = new List<string>();
var html = "<table><thead><tr>";
switch(tablename)
{
case "table1":
columnNames = typeof(table1).GetProperties().Select(a => a.Name).ToList();
foreach(var c in columnNames)
{
html += "<td>" + c.ToString() + "</td>";
}
html += "</tr></thead><tbody>";
var rows = from c in context.table1.ToList()
select c;
foreach(var c in rows)
{
foreach(var p in c.GetType().GetProperties())
{
foreach(var s in columnNames)
{
if(p.Name == s.ToString())
{
// How do I get the value here?
}
}
}
}
break;
// more case statements here based on table names
default:
break;
}
// return empty for now
return new EmptyResult();
}
I was able to loop the names of my columns in my entities, as above, and now constructing my html table based on those values.. but when I need to get the value now, I'm stucked. How do I get the value from my properties above to construct my html table based on table name variable?
And since I have more hundred tables the user want rendered, is there a simpler and more efficient way to do this?
Thanks very much,

Related

json C# 7 Tuple Support

I want to get my C#7 tuple property names in my JSON (Newtonsoft.Json) output.
My problem is:
When I want to convert my tuple to JSON format that not support my parameters names.
For example this is my "Test2" method and you can see the JSON output:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(data);//JSON output is {"Item1":5,"Item2":"ok ali"}
}
public (int MyValue, string Name) GetMe2(string name)
{
return (5, name + " ali");
}
The JSON output is "{"Item1":5,"Item2":"ok ali"}" but i want "{"MyValue":5,"Name":"ok ali"}";
This is not impossible because I can get property names in runtime:
foreach (var item in this.GetType().GetMethods())
{
dynamic attribs = item.ReturnTypeCustomAttributes;
if (attribs.CustomAttributes != null && attribs.CustomAttributes.Count > 0)
{
foreach (var at in attribs.CustomAttributes)
{
if (at is System.Reflection.CustomAttributeData)
{
var ng = ((System.Reflection.CustomAttributeData)at).ConstructorArguments;
foreach (var ca in ng)
{
foreach (var val in (IEnumerable<System.Reflection.CustomAttributeTypedArgument>)ca.Value)
{
var PropertyNameName = val.Value;
Console.WriteLine(PropertyNameName);//here is property names of C#7 tuple
}
}
}
}
dynamic data = attribs.CustomAttributes[0];
var data2 = data.ConstructorArguments;
}
}
For the specific case here, it is impossible. That's because SerializeObject has no way of finding out where the tuple came from, all it sees is ValueTuple<int, string>.
The situation would be different if you were serializing an object with tuple properties, in which case SerializeObject could use reflection to find the TupleElementNames attributes (even though it currently doesn't).
The short answer it that tuples don't have properties.
A tuple is a bag of values used, mainly, to return multiple values from a method.
They were never intended to model entities.
The only way to solve your problem, if you don't want to create a type for that, is:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(new { data.MyValue, data.Name });//JSON output is {"Item1":5,"Item2":"ok ali"}
}

Add data in nested form to a json object from extjs form

I have a table coded in extjs, inside a panel, where the user types in information in the 2 columns of the table. I wish to add this data inside a json object which is inside the main json object.
e.g. : Table 'stats' has 2 fields x and y.
I wish my json looks like :
{
....
stats: [
{
x : ..,
y : ..
},
{
x : ..,
y : ..
}
// this goes on depending upon the number of rows of entries in the table
]
}
Please advice how do I implement this. If I take a HashMap with String as key and List<String> as value and then write
new JSONObject(map);
will this work?
You can choose to implement something like below which gives you this JSON string, which you can parse in js file to render extjs form :
{"stats":[{"y":"y0","x":"x0"},{"y":"y1","x":"x1"},{"y":"y2","x":"x2"},{"y":"y3","x":"x3"},{"y":"y4","x":"x4"}]}
Code :
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for (int i = 0; i < 5; i++) {
JSONObject element = new JSONObject();
element.put("x", "x" + i);
element.put("y", "y" + i);
array.put(element);
}
obj.put("stats", array);
System.out.println(obj);

How to get the document using view in couchbase

I have a requirement wherein I have get the document from couchbase.
Following in the Map function that I am using for the same -
function (doc, meta) {
if (meta.type == "json" && doc!=null) {
emit(doc);
}
}
There is no reduce function. Also following is my java code to get the document -
List<URI> hosts = Arrays.asList(
new URI("http://<some DNS with port>/pools")
);
// Name of the Bucket to connect to
String bucket = "Test-Sessions";
// Password of the bucket (empty) string if none
String password = "";
//System.setProperty("viewmode", "development");
// Connect to the Cluster
CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);
String designDoc = "sessions";
String viewName = "by_test";
View view = client.getView(designDoc, viewName);
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(String.valueOf(122));
ViewResponse result = client.query(view, query);
Object object = null;
for(ViewRow row : result) {
if(null != row) {
object = row.getDocument();
}// deal with the document/data
}
System.out.println("Object" + object);
And the data that I have in couchbase is key - "122" and value - "true". But for some reason , I do not get any rows in the ViewResponse. What is going wrong can anyone help?
I don't understand what you are trying to achieve here, you are using a view to get a document by it's key? Key == 122? Why can't you just do client.get(122) ?
If you just need a list of all the keys in your bucket (of which you can use to pull back all documents via include docs) then make your function like so:
function (doc, meta) {
if (meta.type == "json") {
emit();
}
}
The key of the document is always emitted as an ID (viewRow.getId()). You don't need to emit the document, try to emit as little data as possible to keep view sizes small.
If you are needing to manipulate all the documents in your bucket be careful as the size grows, perhaps you'd need to look at pagination to cycle through the results. http://tugdualgrall.blogspot.com.es/
Also once you have the ViewResponse loop over it like so:
for(ViewRow row : result) {
row.getDocument(); // deal with the document/data
}
You don't need to be doing checks for null on the rows.

Parse a string value using mysql

I have a value in a column in this manner
"id=Clarizen,ou=GROUP,dc=opensso,dc=java,dc=net|id=devendrat,ou=USER,dc=opensso,dc=java,dc=net"
I want to extract group name and user name from this string and will store it into separate columns of another table.
Desired result:
Clarizen as Groupname
devendrat as Username
Please help
You are looking for CharIndex and Substring option.
The following works for T-SQL. I am not sure about the Syntax in My SQL
SELECT REPLACE(SUBSTRING(ColumnName,1,CHARINDEX(',',ColumnName) - 1),'ID=','')
AS Groupname,
REPLACE(SUBSTRING(SUBSTRING(ColumnName,CHARINDEX('|',ColumnName),
LEN(ColumnName)),1,
CHARINDEX(',',ColumnName) - 1),'|ID=','') AS Username
(sorry this is C# I overlooked that you are using mysql, so the answer is useless to you but I'll leave it here unless someone is to remove it)
Using string split can get the job done, here is something that I whipped together, it won't be optimal but it definately works!
string parse_me = "id=Clarizen,ou=GROUP,dc=opensso,dc=java,dc=net|id=devendrat,ou=USER,dc=opensso,dc=java,dc=net";
string[] lines = parse_me.Split(',');
List<string> variables = new List<string>();
List<string> values = new List<string>();
foreach (string line in lines)
{
string[] pair = line.Split('=');
//Console.WriteLine(line);
variables.Add(pair[0]);
values.Add(pair[1]);
}
string group = "";
string user = "";
if (variables.Count == values.Count)
{
for (int i = 0; i < variables.Count; ++i )
{
Console.Write(variables[i]);
Console.Write(" : ");
Console.WriteLine(values[i]);
if (variables[i] == "ou")
{
if (group == "")
{
group = values[i];
}
else if (user == "")
{
user = values[i];
}
}
}
}
Console.WriteLine("Group is: " + group);
Console.WriteLine("User is: " + user);
Console.ReadLine();

Insert with Linq-to-SQL an object determined through reflection

I am trying to populate a row in a table given a key value list
Using DataContext.Mapping I am able to locate the correct table (given a table name) and create a row.
// Look up the table
MetaTable matchedTable = null;
foreach (MetaTable tableMetaData in db.Mapping.GetTables())
{
if (table.Equals(tableMetaData.TableName))
{
matchedTable = tableMetaData;
break;
}
}
if (matchedTable == null)
{
throw new Exception("Invalid table name specified");
}
I then iterate over the row properties and populate the values.
// Iterate through the dictionary and try to match up the keys with column names
foreach (KeyValuePair<string, string> listItem in list)
{
PropertyInfo propertyInfo = rowType.GetProperty(listItem.Key);
if (propertyInfo == null)
{
throw new Exception("Invalid column name specified");
}
// Set the value on the object
try
{
propertyInfo.SetValue(row, Convert.ChangeType(listItem.Value, propertyInfo.PropertyType), null);
}
catch
{
throw new Exception("Value specified cannot be converted to database type");
}
}
I now need to get this row object inserted back into the DB. I have been playing around with db.GetTable<rowType>(); with no luck. Thanks
I was overthinking it
db.GetTable(rowType).InsertOnSubmit(row);
db.SubmitChanges();