Want to use a variable based on its name. It is hard to describe. Here is the example
var sections = new[] { "Personnel", "General", "Medical" };
foreach (var s in sections)
{
// want to retrieve the variable "lblPersonnel"
(Label)Type.GetType(string.Format("lbl{0}", s)).Text = "Test";
}
so that we don't have to :
lblPersonnel.Text = "Test";
lblGeneral.Text = "Test";
lblMedical.Text = "Test";
So, is it possible for this kind of "reflection"?
Type.GetType expects a fully-qualified type name but you are trying to pass it name of the variable.And also it returns a Type instance so you can't cast it to Label.It seems you are confused about types,instances and variables. If you have labels and you want to access them you can use Controls collection of your Form.
foreach (var s in sections)
{
var name = string.Format("lbl{0}", s);
if(this.Controls.ContainsKey(name))
{
var currentLabel = this.Controls[name] as Label;
if(currentLabel != null) currentLabel.Text = "Test";
}
}
Edit: If you are devoloping an ASP.NET project then you can use FindControl method to get your labels by name:
foreach (var s in sections)
{
var name = string.Format("lbl{0}", s);
var currentLabel = FindControl(name) as Label;
if(currentLabel != null) currentLabel.Text = "Test";
}
Why not just get the label using Controls?
var sections = new [] {"Personnel", "General", "Medical"};
foreach (var s in sections)
{
// want to retrieve the variable "lblPersonnel"
((Label)(Controls["lbl" + s])).Text = "Test";
}
foreach (var s in sections)
{
string name = string.Format("lbl{0}", s);
FieldInfo fi = typeof(Form1).GetField(name);
Label l = (Label)(fi.GetValue(this));
l.Text = "Test";
}
This is assuming the Labels are public fields. If they are properties - use GetProperty , if they are private fields, use:
GetField(name, BindingFlags.NonPublic | BindingFlags.Instance);
Related
I have found a way how to display the list without diacritic but how to display it with diacritic ? Here I am checking if the value is in the list twice, if it is then I need to display the one with diacritic but how do I check for diacritic?
{
var fields = new List<Field>()
{
new Field{ Value ="Kateřina Kučerová", IdentityDocumentFieldType = IdentityDocumentFieldType.unknown},
new Field{ Value = "Katerina Kucerova", IdentityDocumentFieldType = IdentityDocumentFieldType.Document},
};
foreach (var field in fields)
{
var value = field.Value;
//Console.WriteLine(StringExtenstion.RemoveDiacritics(value));
var exists = fields.Any(r => r.Desc == field.Desc);
if (!exists)
{
Console.WriteLine(field.Value);
}
else
{
Console.WriteLine(field.Value);
}
}}
string input =#"Kateřina Kučerová";
var samo = "řčěáíéě";
foreach (char c in samo)
{
if(input.Contains(c))
Console.WriteLine("ok");
}
This is what I needed
i have a gridview
INSEE1 Commune
------ -------
10002 AILLEVILLE
10003 BRUN
i have a script that return a list of object.
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1");
my Temp is a list of object of INSSE1 that i have selected.
but now i add Commune also, so my script become:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
and my Temp is list of object of INSEE1 and Commune look at image:
how can i acces 10002 and AILLEVILLE ?
i have try with cast it of my Pers_INSEE class:
public class Pers_InseeZone
{
string _Code_Insee;
public string Code_Insee
{
get { return _Code_Insee; }
set { _Code_Insee = value; }
}
string _Commune;
public string Commune
{
get { return _Commune; }
set { _Commune = value; }
}
}
foreach (var oItem in Temp )
{
Pers_InseeZone o = (Pers_InseeZone)oItem;
}
but I not work, I can not cast it.
I have tried like this:
foreach (var oItem in Temp )
{
var myTempArray = oItem as IEnumerable;
foreach (var oItem2 in myTempArray)
{
string res= oItem2.ToString();
....
the value of res = 10002, but how can I get the value of AILEVILLE ?
the value of Temp[0].GetType(); is:
Thanks in advance
Ok I thought so, so as already mentioned in the comments you have a array of objects inside each object so you need to cast first every object in your list into an array of objects: object[] then you can access each part. Here is an example that recreates your problem:
object[] array = new object[] {10002, "AILEEVILLE"};
List<object> Temp = new List<object> {array};
And the solution:
// cast here so that the compiler knows that it can be indexed
object [] obj_array = Temp[0] as object[];
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
Applied to your code it would look something like this:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
foreach (object oItem in Temp )
{
object [] obj_array = oItem as object[];
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
}
The problem is down to the fact your class doesn't match the same structure as the data you are getting, so it can't be cast into it.
Instead why don't you just iterate over the results and build a new instance of the class?
var tempList = new List<Pers_InseeZone>();
foreach (var oItem in Temp)
{
tempList.Add(new Pers_InseeZone(oItem[0], oItem[1]));
}
You will need to add a constructor to your Pers_InseeZone class, and assign the variables there.
I am pulling some data from a BigQuery table using the code below in C#
BigQueryClient client = BigQueryClient.Create("<Project Name>");
BigQueryTable table = client.GetTable("<Database>", "Students");
string sql = $"select * FROM {table} where Marks='50'";
BigQueryResults results = client.ExecuteQuery(sql);
foreach (BigQueryRow row in results.GetRows())
{
}
I want to be able to either read the entire results variable into JSON or be able to get the JSON out of each row.
Of course, I could create a class that models the table. And inside the foreach loop, I could just read each row into the class object. The class object I can try to serialize into JSON using a third party like "newton soft".
Something like :
class Student{
int id; // assume these are columns in the db
string name;
}
My foreach would now look like:
foreach (BigQueryRow row in results.GetRows())
{
Student s=new Student();
s.id = Convert.ToString(row["id"]);
s.name= Convert.ToString(row["name"]);
// something like string x=x+ s.toJSON(); //using newton soft
}
This way string x will have the JSON generated and appended for each row.
Or is there a way I can just add each student to a collection or List and then get the JSON from the whole list?
This whole reading row by row and field by field seems tedious to me and there must be a simpler way I feel. Did not see any support from Google BigQuery for C# to directly convert to JSON. They did have something in Python.
If not then the list to JSON would be better but I am not sure if it supported.
Update :
https://github.com/GoogleCloudPlatform/google-cloud-dotnet/blob/master/apis/Google.Cloud.BigQuery.V2/Google.Cloud.BigQuery.V2/BigQueryRow.cs
Looks like the Big Query Row class has a RawRow field which is of Type TableRow. And the class uses JSON references so , I am sure they have the data of the row in JSON format . How can I expose it to me ?
This might be a little late but you can use:
var latestResult = _bigQueryClient.ExecuteQuery($"SELECT TO_JSON_STRING(t) FROM `{ProjectId}.{DatasetId}.{TableName}` as t", null
All columns will be serialized as json and placed in the first column on each row. You can then use something like Newtonsoft to parse each row easily.
I ran into the same issue.
I am posting this solution which is not optimized for performance but very simple for multiple data types.
This allows you to deserialize anything (almost)
public class BQ
{
private string projectId = "YOUR_PROJECT_ID";
public BQ()
{
}
public List<T> Execute<T>(string sql)
{
var client = BigQueryClient.Create(projectId);
List<T> result = new List<T>();
try
{
string query = sql;
BigQueryResults results = client.ExecuteQuery(query, parameters: null);
List<string> fields = new List<string>();
foreach (var col in results.Schema.Fields)
{
fields.Add(col.Name);
}
Dictionary<string, object> rowoDict;
foreach (var row in results)
{
rowoDict = new Dictionary<string, object>();
foreach (var col in fields)
{
rowoDict.Add(col, row[col]);
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(rowoDict);
T o = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
result.Add(o);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
client.Dispose();
Console.WriteLine("Done.");
}
return result;
}
}
You can use Newtonsoft.Json. First download by PackageManager Console the Nuget Package, here you can get the command to do that.
After download you can use it as the following code:
List<Student> list = new List<Student>();
foreach (BigQueryRow row in results.GetRows())
{
Student s=new Student();
s.id = Convert.ToString(row["id"]);
s.name= Convert.ToString(row["name"]);
list.Add(s);
}
var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(list);
I hope this can help you.
Here is the complete solution for casting BigQueryResults or GetQueryResultsResponse or QueryResponse data to Model/JSON format using C# reflection:
public List<T> GetBQAsModel<T>(string query) where T : class, new()
{
var bqClient = GetBigqueryClient();
var res = bqClient.ExecuteQuery(query, parameters: null);
return GetModels<T>(res);
}
private List<T> GetModels<T>(BigQueryResults tableRows) where T : class, new()
{
var lst = new List<T>();
foreach (var item in tableRows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.RawRow.F.Count; i++)
{
var name = item.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.RawRow.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
private List<T> GetModels<T>(GetQueryResultsResponse getQueryResultsResponse) where T : class, new()
{
var lst = new List<T>();
foreach (var item in getQueryResultsResponse.Rows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.F.Count; i++)
{
var name = getQueryResultsResponse.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
private List<T> GetModels<T>(QueryResponse queryResponse) where T : class, new()
{
var lst = new List<T>();
foreach (var item in queryResponse.Rows)
{
var lstColumns = new T().GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
var newObject = new T();
for (var i = 0; i < item.F.Count; i++)
{
var name = queryResponse.Schema.Fields[i].Name;
PropertyInfo prop = lstColumns.FirstOrDefault(a => a.Name.ToLower().Equals(name.ToLower()));
if (prop == null)
{
continue;
}
var val = item.F[i].V;
prop.SetValue(newObject, Convert.ChangeType(val, prop.PropertyType), null);
}
lst.Add(newObject);
}
return lst;
}
I would do something like this:
var res = Result. Getrows. Select(x=> new student(){id=x[`ID']}).
And then:
var js = json. Conver(res);
This way is much faster and clearer.
I have 2 lists..
The first contains rows with mapping values inlcuding column name, xcord, ycord
The second contains the data I need to map..
I need to get the value in each row using the column name from the first row..
for example
List<SheetMappings> smaps = new List<SheetMappings>();
foreach(maplist m in mlist)
{
SheetMappings newMap = new SheetMappings();
foreach(vallist v in vlist)
{
newMap.Value = v.{m.ColumnName};
newMap.xCord = m.xCord;
newMap.yCord = m.yCord;
}
smaps.Add(newMap);
}
Any assitance appreciated
Cheers
Graham
EDIT:
List<SpreadMappings> spreadMapping = new List<SpreadMappings>();
foreach (var m in mappings)
{
foreach (var v in hvalues)
{
SpreadMappings map = new SpreadMappings();
switch (m.ColumnName)
{
case “DocHeading”:
map.ColumnX = m.ColumnX;
map.ColumnY = m.ColumnY;
map.ColumnValue = v.DocHeading;
map.ColumnName = m.ColumnName;
map.ColumnId = v.Id;
map.ColumnSheetName = sheetName; spreadMapping.Add(map);
break;
If I understand what you're trying to do, you'll need to use reflection to get the value of the property represented by m.ColumnName:
var smaps = new List<SheetMappings>();
foreach(maplist m in mlist)
{
var pi = typeof(vallist).GetProperty(m.ColumnName);
var newMap = new SheetMappings();
foreach(vallist v in vlist)
{
newMap.Value = pi.GetValue(v, null);
newMap.xCord = m.xCord;
newMap.yCord = m.yCord;
}
smaps.Add(newMap);
}
So that's using reflection to get a reference to the PropertyInfo for the property represented by m.ColumnName, then calling PropertyInfo.GetValue to get the value of that property from v.
Well I think the "newMap.Value = v.{m.ColumnName}" part would be something like:
newMap.Value = v.FirstOrDefault( vitem => vitem.ColumnName == m.ColumnName );
This would give you the first item within "v" that has a "ColumnName" property that matches the "ColumnName" property of "m". This assumes that the contents of "vallist" are objects that have a "ColumnName" property.
I am using c# & .NET 3.5. A vendor gives us an object that has properties of UserVarNbr1, UserVarData1, UserVarNbr2, UserVarData2,... UserVarNbrN, UserVarDataN. Not the way I would have coded it but nonetheless, this is what we have to work with. Another object in the application returns a collection of items used to represent these UserVariables.
The collection items have properties like this
public string VariableName
{
get { return _VariableName; }
set { _VariableName = value; }
}
public string VariableData
{
get { return _VariableData; }
set { _VariableData = value; }
}
I need to loop through the collection and create an instance of the vendor object and set the correct properties. UserVarNbrN, UserVarDataN needs to be put in the correct place. Note the collection returns a VariableName as a string "03", this needs to drive VendorObject properties UserVarNbr3, UserVarData3 **notice no "0" in the actual property name. How do I reference the correct property to get/set?
var o = new VendorObj();
I have something like this so far.
foreach (var item in userVars)
{
const string propPrefix = "UserVar";
int varNum;
var isNum = int.TryParse(item.VariableName, out varNum);
if(isNum)
{
PropertyInfo pi;
//this is where I am stuck
// I need to set the corresponding properties on o
// example if varNum == 38, how do I reference
// o.(propPrefix+"Nbr"+varNum.ToString())
// and
// o.(propPrefix+"Data"+varNum.ToString())
// so I may set them?
}
}
Any help is appreciated. I am a rookie when it come to reflection.
Thanks,
~ck in San Diego
VendorObj vndr = new VendorObj();
Console.WriteLine("\nInitial value of instance property: {0}", vndr.InstanceProperty);
PropertyInfo piInstance = typeof(VendorObj).GetProperty("InstanceProperty");
Object obj = piInstance.GetValue(vndr, null);
piInstance.SetValue(vndr, 37, null);
Console.WriteLine("Final value of instance property: {0}", vndr.InstanceProperty);
Try this:
const string propPrefix = "UserVar";
VendorObj o = new VendorObj();
foreach (var item in userVars)
{
int varNum = 0;
if (Int32.TryParse(item.VariableName, out varNum))
{
string name = String.Format("{0}Nbr{1}", propPrefix, varNum);
o.GetType().GetProperty(name).SetValue(o, "some value", null);
}
}
Since you will be setting many properties on the one object, you are better off getting the PropertyDescriptorCollection
var o = new VendorObj();
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(o);
foreach (var item in userVars)
{
const string propPrefix = "userVar";
int varNum;
if (int.TryParse(item.VariableName, out varNum))
{
PropertyDescriptor property = properties.Find(propPrefix + "Nbr" + varNum, true);
property.SetValue(o, item.VariableData);
}
}