Dynamics crm + how to get attribute value based on the type dynamically in plugin code - dynamics-crm

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.

Related

Loop through model and build SqlCommand obj

I have an MVC3 application and I want to pass my model to a method which builds a command object. The reason being that I have lots of methods with command objects and I want the code to be better written.
private static SqlCommand CommandObj(vw_UserManager_Model model)
{
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
foreach (var item in model)
{
switch (property.PropertyType.Name)
{
case "String":
command.Parameters.Add("#" + property.Name, SqlDbType.VarChar).SqlValue = property;
break;
case "Guid":
command.Parameters.Add("#" + property.Name, SqlDbType.UniqueIdentifier).SqlValue = property;
break;
case "Int32":
command.Parameters.Add("#" + property.Name, SqlDbType.Int).SqlValue = property;
break;
case "Boolean":
//switch (property.Name.FirstOrDefault())
//{
// case true:
// command.Parameters.Add("#isactive", SqlDbType.Bit).SqlValue = 1;
// command.Parameters.Add("#isapproved", SqlDbType.Bit).SqlValue = 1;
// break;
// case false:
// command.Parameters.Add("#isactive", SqlDbType.Bit).SqlValue = 0;
// command.Parameters.Add("#isapproved", SqlDbType.Bit).SqlValue = 0;
// break;
//}
break;
}
}
return command;
}
Currently this code won't compile because I can't enumerate through my model like this. What I want to do is loop through each item in the model and do a switch statement to build the correct dbType parameter.
Anyone have suggestions for how to change this code?
Thanks!!
Hopefully I understood your question. Seems like you may be trying to do something like this. Here's my model class:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool Married { get; set; }
}
Here's the code that loops through the model properties:
public static void Main(string[] args)
{
Person person = new Person();
var modelProperties = person.GetType().GetProperties();
foreach (var property in modelProperties)
{
switch (property.PropertyType.Name)
{
case "String":
Console.WriteLine("Property {0} is a string", property.Name);
break;
case "Int32":
Console.WriteLine("Property {0} is an int", property.Name);
break;
case "Boolean":
Console.WriteLine("Property {0} is a boolean", property.Name);
break;
default:
Console.WriteLine("Type unknown!");
break;
}
}
Hope this helps.

How to add QueryString in OnActionExecuting()?

i want to add two queryString in current request URL if it is not exsist
Edited:
I tried this ---
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.QueryString["mid"] == null && filterContext.RequestContext.HttpContext.Request.QueryString["mod"] == null)
{
mid = Convert.ToString(HttpUtility.ParseQueryString(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Query)["mid"]);
mod = Convert.ToString(HttpUtility.ParseQueryString(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Query)["mod"]);
if (!string.IsNullOrEmpty(mid) || !string.IsNullOrEmpty(mod))
{
RouteValueDictionary redirecttargetDictionary = new RouteValueDictionary();
NameValueCollection Qstr = null;
if (filterContext.HttpContext.Request.RequestType == "GET")
{
Qstr = HttpUtility.ParseQueryString(filterContext.HttpContext.Request.Url.Query);
foreach (string item in Qstr)
{
redirecttargetDictionary.Add(item, Qstr[item]);
}
if (Qstr["mid"] == null)
{
redirecttargetDictionary.Add("mid", mid);
}
if (Qstr["mod"] == null)
{
redirecttargetDictionary.Add("mod", mod);
}
filterContext.Result = new RedirectToRouteResult(redirecttargetDictionary);
}
}
}
This code works fine.
-check for quesrystring exsist if no
-then take qstring value from 'Urlreferrer'
-if request type is GET
-then add two querystring with exsisting querystring
But but I having problem if querystring in current request has null value url like http://localhost:53372/question/index?type=&stage.if this ll b the current request url then code ll check for mid n mod qstring as its not exsist it will add both the qstring with exsisting type n stage but value ll b null then before hitting action again OnActionExecuting() get call this time first 'if' is not true and then index method get call but I m not getting type n stage querystring which suppose to null I found url in address bar is http://localhost:53372/question/index?mid=1&mod=5.
If I remove filter the I got URL http://localhost:53372/question/index?type=&stage=&mid=1&mod=5 here I m getting both stage n type querystring though its null.
Edited--
[HttpGet]
public ActionResult Index(ProjectType? projectType, int? projectStageID, int? page)
{
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
IPagedList<ProjectModule> moduleList = null;
IDictionary<string, string> queryParam = new Dictionary<string, string>();
queryParam["ProjectType"] = string.Empty;
queryParam["ProjectStageID"] = string.Empty;
ViewBag.ProjectType = null;
ViewBag.ProjectStage = null;
ViewBag.message = "";
if ((projectType != null || projectType.HasValue) && projectStageID.HasValue && page.HasValue)
{
queryParam["ProjectType"] = Request.QueryString["ProjectType"];
queryParam["ProjectStageID"] = Request.QueryString["ProjectStageID"];
//
//Set View Bag
//
ViewBag.ProjectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]);
ViewBag.ProjectStage = Convert.ToInt32(Request.QueryString["ProjectStageID"]);
//
// Set Query String formcollection for Pagging purpose
//
ViewBag.QueryParam = queryParam;
moduleList = new ProjectModuleService().GetProjectModulesByProjectStageID(Convert.ToInt32(Request.QueryString["ProjectStageID"])).ToPagedList(currentPageIndex, Utility.ConstantHelper.AdminDefaultPageSize); ;
if (moduleList.Count == 0)
{
ViewBag.message = "Record(s) not found.";
}
return View(moduleList);
}
else
{
if (!string.IsNullOrEmpty(Request.QueryString["ProjectType"]) && !string.IsNullOrEmpty(Request.QueryString["ProjectStageID"]) && !string.Equals(Request.QueryString["ProjectStageID"], "0"))
{
if (!string.IsNullOrEmpty(Request.Params.Get("Index")))
{
queryParam["ProjectType"] = Request.QueryString["ProjectType"];
queryParam["ProjectStageID"] = Request.QueryString["ProjectStageID"];
//
//Set View Bag
//
ViewBag.ProjectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]);
ViewBag.ProjectStage = Convert.ToInt32(Request.QueryString["ProjectStageID"]);
//
// Set Query String formcollection for Pagging purpose
//
ViewBag.QueryParam = queryParam;
moduleList = new ProjectModuleService().GetProjectModulesByProjectStageID(Convert.ToInt32(Request.QueryString["ProjectStageID"])).ToPagedList(currentPageIndex, Utility.ConstantHelper.AdminDefaultPageSize); ;
if (moduleList.Count == 0)
{
ViewBag.message = "Record(s) not found.";
}
return View(moduleList);
}
else if (!string.IsNullOrEmpty(Request.Params.Get("Create")))
{
return RedirectToAction("Create", new { projectStageID = Convert.ToInt32(Request.QueryString["ProjectStageID"]) });
//return RedirectToAction("Create", new { projectStageID = Convert.ToInt32(Request.QueryString["ProjectStageID"]), projectType = Enum.Parse(typeof(ProjectType), Request.QueryString["ProjectType"]) });
}
}
if (Request.QueryString["ProjectType"] == "" || Request.QueryString["ProjectStageID"] == "" || string.Equals(Request.QueryString["ProjectStageID"], "0"))
{
ViewBag.message = "Please select all fields.";
return View();
}
return View();
}
}
What I m doing wrong?
Here what I understand that if there are no querystring in the URL,you need to add two query string parameters. If you are adding this two querystring parameters explicitly than, it will be default value for that queryparameters.
It's better to provide default value in action method instead of adding queryparameters in URL. You can achieve by following code.
public ActionResult ComposeEmail(int queryParameter1 = 0,string queryParameter2 = string.Empty)
{
}
Do let me know, if you have any query.

Fill RadGridView dynamically

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

EmitMapper and List

It's the first time that I use EmitMapper.
I have a list of object ex: Customer and I would like to map this list in a ienumerable of CustomerDTO how can I do that?
Tnx
It's straightforward if you have a list and want to convert it to list of DTOs:
var mapper = ObjectMapperManager.DefaultInstance.GetMapper<Customer, CustomerDTO>();
IEnumerable<CustomerDTO> dtos = listOfCustomer.Select(mapper.map);
The preblem is when the list is in another object, for example User and UserDTO:
class User {
public List<Customer> Customers { get; set; }
}
class UserDTO {
public IEnumerable<CustomerDTO> Customers { get; set; }
}
It seems that EmitMapper does not support conversion from List to Enumerable. A way to support it would be:
var customerMapper = ObjectMapperManager
.DefaultInstance.GetMapper<Customer, CustomerDTO>();
var mapper = ObjectMapperManager.DefaultInstance
.GetMapper<User, UserDTO>(
new DefaultMapConfig()
.ConvertUsing<List<Customer>, IEnumerable<CustomerDTO>>(
a => a.Select(customerMapper.Map))
);
This can be done creating a custom class, implementing the interface "ICustomConverterProvider" and adding a ConvertGeneric to the "DefaultMapConfig".
Looking on the source code of EmitMapper, i found a class named "ArraysConverterProvider", which is the default generic converter from ICollections to Arrays.
Adapting the code from this class to work with IEnumerable collections:
class GenericIEnumerableConverterProvider : ICustomConverterProvider
{
public CustomConverterDescriptor GetCustomConverterDescr(
Type from,
Type to,
MapConfigBaseImpl mappingConfig)
{
var tFromTypeArgs = DefaultCustomConverterProvider.GetGenericArguments(from);
var tToTypeArgs = DefaultCustomConverterProvider.GetGenericArguments(to);
if (tFromTypeArgs == null || tToTypeArgs == null || tFromTypeArgs.Length != 1 || tToTypeArgs.Length != 1)
{
return null;
}
var tFrom = tFromTypeArgs[0];
var tTo = tToTypeArgs[0];
if (tFrom == tTo && (tFrom.IsValueType || mappingConfig.GetRootMappingOperation(tFrom, tTo).ShallowCopy))
{
return new CustomConverterDescriptor
{
ConversionMethodName = "Convert",
ConverterImplementation = typeof(GenericIEnumerableConverter_OneTypes<>),
ConverterClassTypeArguments = new[] { tFrom }
};
}
return new CustomConverterDescriptor
{
ConversionMethodName = "Convert",
ConverterImplementation = typeof(GenericIEnumerableConverter_DifferentTypes<,>),
ConverterClassTypeArguments = new[] { tFrom, tTo }
};
}
}
class GenericIEnumerableConverter_DifferentTypes<TFrom, TTo> : ICustomConverter
{
private Func<TFrom, TTo> _converter;
public IEnumerable<TTo> Convert(IEnumerable<TFrom> from, object state)
{
if (from == null)
{
return null;
}
TTo[] result = new TTo[from.Count()];
int idx = 0;
foreach (var f in from)
{
result[idx++] = _converter(f);
}
return result;
}
public void Initialize(Type from, Type to, MapConfigBaseImpl mappingConfig)
{
var staticConverters = mappingConfig.GetStaticConvertersManager() ?? StaticConvertersManager.DefaultInstance;
var staticConverterMethod = staticConverters.GetStaticConverter(typeof(TFrom), typeof(TTo));
if (staticConverterMethod != null)
{
_converter = (Func<TFrom, TTo>)Delegate.CreateDelegate(
typeof(Func<TFrom, TTo>),
null,
staticConverterMethod
);
}
else
{
_subMapper = ObjectMapperManager.DefaultInstance.GetMapperImpl(typeof(TFrom), typeof(TTo), mappingConfig);
_converter = ConverterBySubmapper;
}
}
ObjectsMapperBaseImpl _subMapper;
private TTo ConverterBySubmapper(TFrom from)
{
return (TTo)_subMapper.Map(from);
}
}
class GenericIEnumerableConverter_OneTypes<T>
{
public IEnumerable<T> Convert(IEnumerable<T> from, object state)
{
if (from == null)
{
return null;
}
return from;
}
}
This code is just a copy with a minimum of adaptation as possible and can be applyed to objects with many levels of hierarchy.
You can use the above code with the following command:
new DefaultMapConfig().ConvertGeneric(
typeof(IEnumerable<>),
typeof(IEnumerable<>),
new GenericIEnumerableConverterProvider());
This saved my day and I hope to save yours too! hehehe

Anonymous types in LINQ

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";
}

Resources