I am using the following code to get a record from my database table tblDatabases. I then populate Controls on a Form based on the value. I have used some functions to get the values needed for displaying in a text box (e.g. the display value is different than the value.
The DetailData is an object in my base form class. Initially I just got the record from the table as is and I was able to cast the DetailData to the tblDatabases and use reflection to get all of the values for the data and populate the controls on my form.
I am no longer able to cast the DetailData to my table because of the anonymous types.
I would like to be able to use reflection on the DetailData to get the values.
Thanks,
Brad
DetailData = (from db in priorityDataContext.tblDatabases
where db.DatabaseID == Id
select new
{
db.DatabaseID,
db.DatabaseName,
db.Purpose,
db.BackEnd,
db.FrontEnd,
db.Version,
db.ProducesReports,
db.MultiUser,
db.UserDescription,
Developer = priorityDataContext.func_get_employee_name(db.Developer),
DeptOwner = priorityDataContext.func_get_dept_name(db.DeptOwner),
db.Source_Code_Path,
db.Notes,
db.Active,
db.row_entry_time_stamp,
row_oper_name = priorityDataContext.func_get_employee_name(db.Developer),
db.row_last_chng_time_stamp,
row_last_chng_oper_name = priorityDataContext.func_get_employee_name(db.Developer)
}).SingleOrDefault();
protected virtual void PopulateDetailControlsA(List<Control> controlContainers, string srcDataTableName)
{
switch (srcDataTableName)
{
case "tblDatabase" :
break;
}
var database = (tblDatabase) DetailData;
var type = typeof(tblDatabase);
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var controlContainer in controlContainers)
{
foreach (var propertyInfo in properties)
{
if (!ControlExists(controlContainer, propertyInfo.Name)) continue;
var txtExtControl = controlContainer.Controls[propertyInfo.Name] as ExtendedTextBox;
if (txtExtControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
txtExtControl.Text = value;
}
catch (NullReferenceException)
{
}
continue;
}
var lnklblControl = controlContainer.Controls[propertyInfo.Name] as ExtendedLinkLabel;
if (lnklblControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
lnklblControl.Text = value;
}
catch (NullReferenceException)
{
}
continue;
}
var chkControl = controlContainer.Controls[propertyInfo.Name] as ExtendedCheckBox;
if (chkControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
switch (value)
{
case "True":
chkControl.CheckState = CheckState.Checked;
break;
case "False":
chkControl.CheckState = CheckState.Unchecked;
break;
}
}
catch (NullReferenceException)
{
chkControl.CheckState = CheckState.Indeterminate;
}
continue;
}
var cmbControl = controlContainer.Controls[propertyInfo.Name] as ExtendedComboBox;
if (cmbControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
cmbControl.ValueMember = value;
}
catch (Exception ex)
{
}
continue;
}
}
}
}
What technology are you using for your UI? If you could use binding you would not need to worry about reflection on the anonymous type and then could also use converters if you need to format/calculate values from this.
From your response can't you just use the connection to the linq and then bind this to the combo box?
private void Form1_Load(object sender, System.EventArgs e)
{
var item = new DataClassesDataContext();
var stuff = item.Entity.Where(c => c.Property.Contains("something"));
comboBox1.DataSource = stuff;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "PIN";
}
Related
Here I have the SearchBar method, which, at the moment, searching keywords from my TITLE element of the Post Class. But I want to search by TITLE and LOCATION, which is the second element in my Post Class. How to add the LOCATION element from my Post class to the searchBar method?
private void searchBarmainPage_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
var keyword = e.NewTextValue;
conn.CreateTable<PostClass>();
var posts = conn.Table<PostClass>().ToList();
if(keyword.Length >= 1)
{
var results = posts.Where(x => x.Title.ToLower().Contains(keyword.ToLower()));
listViewMainPage.ItemsSource = results;
listViewMainPage.IsVisible = true;
}
else
{
listViewMainPage.IsVisible = false;
}
}
} catch (NullReferenceException r)
{
}catch (Exception m)
{
}
}
You can use the || operator to check if the keyword is contained inside the Title or inside the Location.
If you want the keyword to be in both places at the same type, you should use &&
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
var keyword = e.NewTextValue;
conn.CreateTable<PostClass>();
var posts = conn.Table<PostClass>().ToList();
if(keyword.Length >= 1)
{
var results = posts.Where(x => x.Title.ToLower().Contains(keyword.ToLower()) || x.Location.ToLower().Contains(keyword.ToLower()) );
listViewMainPage.ItemsSource = results;
listViewMainPage.IsVisible = true;
}
else
{
listViewMainPage.IsVisible = false;
}
}
I have the below requirement.
I need to perform the sum of each field across multiple records of the same entity However while performing the sum, I also need to check the type and cast them accrodingly. For eg, For whole number cast to Int, For Decimal cast to decimal. Also some of the values are aliased value too. I am looking for a generic function which I can call for both alias fields and direct fields and it will return me the value based on the type
Background on the code written below -
Attribute List is the list of all attributes that belong to the
entity.
Format in which the field values are stored in AttributeList-
AttributeList = { "price ", "quantity", "contact.revenue", "opportunity.sales"}
price, quantity - fields of main entity on which we are querying
contact.revenue, opportunity.sales - fields of the aliased entities,
entity name is appended to understand which entity's field it is
Below is the code which i have tried so far -
I only have decimal and whole number fields in my attributeList.
private void calculate(List<string> attributeList,List<Entity> mainEntityList,Guid targetId,Guid oppId,Guid contactId)
{
var mainentity = new mainEntity();
mainentity.Id = targetId;
var opportunity = new Opportunity();
opportunity.Id = oppId;
var contact = new Contact();
contact.Id = contactId;
foreach (var attribute in attributeList)
{
var fieldSum = new decimal(0);
int intFieldSum = 0;
bool attributeFound = false;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
var type = entity[attribute].GetType().Name;
attributeFound = true;
switch (type)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
if (aliasedFieldValue.Value.GetType().Name == "Decimal")
{
decimalFieldSum += (decimal)aliasedFieldValue.Value;
}
else
{
intFieldSum += (int)aliasedFieldValue.Value;
}
break;
case "Decimal":
decimalFieldSum += entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
intFieldSum += entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
}
}
if (attributeFound)
{
if (attribute.Contains("opportunity"))
{
opportunity[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
else if (attribute.Contains("contact"))
{
contact[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
else
{
mainentity[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
}
}
service.update(opportunity);
service.update(contact);
service.update(mainentity);
}
Any help would be appreciated.
Just a little bit edited your code.
...
var fieldSum = new decimal(0);
foreach (var entity in mainEntityList)
{
fieldSum += GetAttrValue(entity, attribute);
}
...
You can use this function to calculate fieldSum variable which is of decimal type.
private decimal GetAttrValue(Entity entity, string attribute)
{
var attrValue = new decimal(0);
if (!entity.Contains(attribute) || entity.Attributes[attribute] == null)
{
return attrValue;
}
var type = entity.Attributes[attribute].GetType().Name;
switch (type)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
attrValue = type == "Decimal" ? (decimal)aliasedFieldValue.Value : (int)aliasedFieldValue.Value;
break;
case "Decimal":
attrValue = entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
attrValue = entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
return attrValue;
}
On the other hand if you just need a generic function which will return decimal or int value for an attribute you can use this
private T GetAttrValue<T>(Entity entity, string attribute)
{
if (!entity.Contains(attribute) || entity.Attributes[attribute] == null)
{
return default(T);
}
T result;
var type = entity.Attributes[attribute].GetType().Name;
if (type == "AliasedValue")
{
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
result = (T)aliasedFieldValue.Value;
}
else
{
result = entity.GetAttributeValue<T>(attribute);
}
return result;
}
--Update--
So, here is the whole code if I understand you requirements right.
First of all add this class.
public class AttributeInfo
{
public string Name { get; set; }
public Type Type { get; set; }
public decimal DecimalSum { get; set; } = new decimal(0);
public int IntSum { get; set; } = 0;
}
And add this function
private void SetValue(Entity entity, AttributeInfo attributeInfo)
{
if (entity.Contains(attributeInfo.Name))
{
switch (attributeInfo.Type.Name)
{
case "Decimal":
entity[attributeInfo.Name] = attributeInfo.DecimalSum;
break;
case "Int32":
entity[attributeInfo.Name] = attributeInfo.IntSum;
break;
default:
break;
}
}
}
Then this is you Calculate function
private void Calculate(List<string> attributeList, List<Entity> mainEntityList, Guid targetId, Guid oppId, Guid contactId)
{
var mainentity = new mainEntity();
mainentity.Id = targetId;
var opportunity = new Opportunity();
opportunity.Id = oppId;
var contact = new Contact();
contact.Id = contactId;
var attributesInfo = new List<AttributeInfo>();
foreach (var attribute in attributeList)
{
var attributeInfo = new AttributeInfo
{
Name = attribute
};
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
attributeInfo.Type = entity[attribute].GetType();
switch (attributeInfo.Type.Name)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
if (aliasedFieldValue.Value.GetType().Name == "Decimal")
{
attributeInfo.DecimalSum += (decimal)aliasedFieldValue.Value;
}
else
{
attributeInfo.IntSum += (int)aliasedFieldValue.Value;
}
break;
case "Decimal":
attributeInfo.DecimalSum += entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
attributeInfo.IntSum += entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
}
}
attributesInfo.Add(attributeInfo);
}
foreach (var attributeInfo in attributesInfo)
{
if (attributeInfo.Type != null)
{
SetValue(mainentity, attributeInfo);
SetValue(opportunity, attributeInfo);
SetValue(contact, attributeInfo);
}
}
service.update(mainentity);
service.update(opportunity);
service.update(contact);
}
I should say that the structure of the calculate function still seems weird for me. However, here I tried to keep the main structure.
I am attempting to retrieve the names and phone number(s) of all contacts and show them into tableview in Xamarin.iOS. I have made it this far:
var response = new List<ContactVm>();
try
{
//We can specify the properties that we need to fetch from contacts
var keysToFetch = new[] {
CNContactKey.PhoneNumbers, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.EmailAddresses
};
//Get the collections of containers
var containerId = new CNContactStore().DefaultContainerIdentifier;
//Fetch the contacts from containers
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out
var error);
}
//Assign the contact details to our view model objects
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactVm
{
PhoneNumbers =item.PhoneNumbers,
GivenName = item.GivenName,
FamilyName = item.FamilyName,
EmailId = item.EmailAddresses.Select(m => m.Value.ToString()).ToList()
});
}
BeginInvokeOnMainThread(() =>
{
tblContact.Source = new CustomContactViewController(response);
tblContact.ReloadData();
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
and this is my update cell method
internal void updateCell(ContactVm contact)
{
try
{
lblName.Text = contact.GivenName;
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//var no = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
//NSString a = new NSString("");
// var MobNumVar = ((CNPhoneNumber)contact.PhoneNumbers[0]).ValueForKey(new NSString("digits")).ToString();
var c = (contact.PhoneNumbers[0] as CNPhoneNumber).StringValue;
}
catch(Exception ex)
{
throw ex;
}
}
I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value.
this line of code
lblContact.Text = ((CNPhoneNumber)contact.PhoneNumbers[0]).StringValue;
throw a run time exception as specified cast is not valid
Yes, exception is correct. First of all, you don't need any casts at all, contact.PhoneNumbers[0] will return you CNLabeledValue, so you just need to write it in next way
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelKey.Home).StringValue
//or
lblContact.Text = contact.PhoneNumbers[0].GetLabeledValue(CNLabelPhoneNumberKey.Mobile).StringValue
or you may try, but not sure if it works
contact.PhoneNumbers[0].Value.StringValue
I got solution. Here is my code if any one required.
CNLabeledValue<CNPhoneNumber> numbers =
(Contacts.CNLabeledValue<Contacts.CNPhoneNumber>)contact.PhoneNumbers[0];
CNPhoneNumber number = numbers.Value;
string str = number.StringValue;
lblContact.Text = str;
I am using RadControls for WinForms 2011 Q3
The datasource for a RadGridView is dynamically generated based on users' input/selection
Everytime when a datasource is generated, I will call SetDatasource2KeyValuesGrid()
What I expect to see is columns generated and values filled in gridview.
However what I see is columns generated but no value filled even though the number of rows in gridview match the number of items in its datasource(keyValuesList)
I must have missed something simple. Please help. thanks
Edit:
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
Just wonder if there's a better way. thanks
private void CreateTableSetDatasource(List<FeedKeyValueOneSet>) keyValueList)
{
if(keyValueList==null) return;
var table = new DataTable();
table.Columns.Add("Check");
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
table.Columns.Add(oneKey.key);
}
break;
}
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
var numOfCol = oneset.Length + 1;
var obj = new object[numOfCol];
obj[0] = "false";
int idx = 1;
foreach (var oneKey in oneset)
{
obj[idx] = oneKey.value;
idx++;
}
table.Rows.Add(obj);
}
radGridKeyValues.DataSource = table;
}
private void SetDatasource2KeyValuesGrid()
{
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Clear();
radGridKeyValues.AutoGenerateColumns = false;
radGridKeyValues.EnableFiltering = false;
radGridKeyValues.ShowFilteringRow = false;
radGridKeyValues.ShowHeaderCellButtons = false;
radGridKeyValues.AllowDragToGroup = false;
radGridKeyValues.AllowAddNewRow = false;
radGridKeyValues.EnableGrouping = false;
var keyValueList = (List<FeedKeyValueOneSet>)TimeSeries.FeedValuesCache[m_strFeedName + "_KEYVALUES"];
if(keyValueList==null) return;
GridViewDataColumn checkBoxColumn = new GridViewCheckBoxColumn("columnState", "columnState");
checkBoxColumn.HeaderText = string.Empty;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(checkBoxColumn);
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
var textboxCol = new GridViewTextBoxColumn(oneKey.key, oneKey.key);
textboxCol.Width = 150;
textboxCol.ReadOnly = true;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(textboxCol);
}
break;
}
radGridKeyValues.DataSource = keyValueList;
}
public class FeedKeyValueOneSet
{
public FeedFieldValues[] KeyValueOneSet;
}
public class FeedFieldValues
{
public string key { get; set; }
public string value { get; set; }
}
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
see code in edit to the question
I am getting the result from linq query as var(IEnumrable<'T'> anonymous type<'string,int>')
i want the result to be in the datatable or dataset.
I found two sample for that issue;
Sample I:
I created a public method called LINQToDataTable as following:
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others
will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
==typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
Sample II
Here is my second method:
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
IDbCommand cmd = ctx.GetCommand(query as IQueryable);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = (SqlCommand)cmd;
DataTable dt = new DataTable("sd");
try
{
cmd.Connection.Open();
adapter.FillSchema(dt, SchemaType.Source);
adapter.Fill(dt);
}
finally
{
cmd.Connection.Close();
}
return dt;
}