Flag value source is not clear - c#

I have a component named dealsummary.ascx with the below code :
<asp:image id='status' runnat='server' imageurl='<%#GetDealstatusPicture(eval('flag'))%>'/>
And in code component dealsummary.ascx.cs GetDealstatusPicture() method is defined, but I am not able to find out the source of flag.
Can anyone point what could be the source, or what more information should I provide?
public string GetDealstatusPicture(object dataItem)
{
string ImageURL = string.empty
if dataItem != null {
int status = convert.ToInt32(dataItem);
if ((status==1))
{
ImageURL ==/*Path to image*/
}
if ((status==2))
{
ImageURL ==/*Path to image*/
}
if ((status==3))
{
ImageURL ==/*Path to image*/
}
}

Related

DataAnnotations: read out the Name property in code

I have decorated the following enum with Display DataAnnotation attributes:
public enum RequiredOptions
{
[Display(Name="Optional",Description ="Optional")]
Optional,
[Display(Name="Not Used",Description ="Not Used")]
NotUsed,
[Display(Name="Required",Description ="Required")]
Required
}
I'd like to read out the Name value of the Display attribute for a given enum value in my code. How do I do this?
public static string DisplayRequiredOptionName(RequiredOptions opt)
{
// Return the value of Name from the display attribute from opt
}
Well, after doing some digging in the MVC source code (see src\System.Web.Mvc\Html\SelectExtensions.cs, see GetDisplayName()), here's what I got to work:
public static string GetEnumDisplayName<T>(T enumInstance)
{
return GetDisplayName(enumInstance.GetType().GetField(enumInstance.ToString()));
}
private static string GetDisplayName(FieldInfo field)
{
DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);
if (display != null)
{
string name = display.GetName();
if (!String.IsNullOrEmpty(name))
{
return name;
}
}
return field.Name;
}

Reflection on IQueryable<T> can't find property

I created a custom gridview control and exported it into a dll so I can reuse it. Inside the dll I created a function to get the DataSource, I'm trying to fill a dropdown from there but is failing.
So on my website I have this
public partial class _Management : System.Web.UI.Page
{
public class _ManagementHelper
{
public int ID;
public string CompanyName;
public string ResourceName;
}
protected void Page_Load(object sender, EventArgs e)
{
ucGridViewEx.DataSource = ucGridViewEx_Source();
ucGridViewEx.DataBind();
}
private List<dynamic> ucGridViewEx_Source()
{
var source = dl.ComapniesResources.Select(x => new _ManagementHelper
{
ID = x.ResourceID,
CompanyName = x.Supplier1.SupplierName,
ResourceName = x.Name
});
return ucGridViewEx.GridViewExDataSource(source);
}
Then the custom control inside the dll have this relevant code
public List<dynamic> GridViewExDataSource<T>(IQueryable<T> query)
{
foreach (var column in this.Columns)
{
var gridViewExColumn = column as ColumnEx;
if (gridViewExColumn != null
&& gridViewExColumn.SearchType == SearchTypeEnum.DropDownList)
{
gridViewExColumn.DropDownDataSource = query.GetDropDownDataSource(gridViewExColumn.DataField);
}
}
return ((IQueryable<dynamic>)query).ToList<dynamic>();
}
Function GetDropDownDataSource() is inside another extension class inside the same dll as the gridview
internal static List<ListItem> GetDropDownDataSource<T>(this IQueryable<T> query,
string dataField)
{
var ddlSource = new List<ListItem>();
// x =>
var xParameter = Expression.Parameter(typeof(T), "x");
// x.Property
var propery = typeof(T).GetProperty(dataField);
// x => x.Property
var columnLambda = Expression.Lambda(Expression.Property(xParameter, propery), xParameter);
return ddlSource;
}
Code fails in this where I'm assingning the value to columnLambda because property is null, not because it does not exist (it does) because is not getting any property. I tried with GetProperties() and is not returning anything.
Is curious than this is happening since I moved to the DataSource to select into _ManagementHelper. I was using a dynamic ( Select(x => new {}) ) on ucGridViewEx_Source() before and it worked perfectly. Please don't provide the solution to keep using the dynamic because I need to allow both types, with dynamic and using custom objects.
_ManagementHelper has no property. It just contains three fields (as far as you told us). So GetPrperty returns nothing. Change the members of _ManagementHelper to properties:
public class _ManagementHelper
{
public int ID { get; set; }
public string CompanyName { get; set; }
public string ResourceName { get; set; }
}
I see one bug --
var source = dl.ComapniesResources.Select(x => new _ManagementHelper
{
// ResourceID = x.ResourceID, this was the old code
ID = x.ResourceID, // fixed code
CompanyName = x.Supplier1.SupplierName,
ResourceName = x.Name
});
also, where is ListItem defined?

GridView DataBinding

I have a problem with a GridView(I'm using Telerick but i think the .NET GridView is similar for this situation).
I have a List that contains some user define object with some properties that will be displayed in a GridView. This list is loaded from SQL.
My problem is that i have an int property that i want to be parsed and displayed in GridView with some strings.
public class Vehicles
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string vehName;
public string VehName
{
get { return vehName; }
set { vehName = value; }
}
private int gpsInterval;
public int GpsInterval
{
get { return gpsInterval; }
set { gpsInterval = value; }
}
private int isStolen;
public int IsStolen
{
get { return isStolen; }
set { isStolen = value; }
}
...
}
...
List<Vehicles> vehs = DBveh.getAllVehicles();
GridViewUnitsList.DataSource = vehs;
Is stolen is curently displayed as an int in the GridView. So is there a method to parse "isStolen" value and replace it with somenting like "YES"/"NO" without using a foreach and iterating throw the hole GridView after the binding?
There are 2 easy options:
1) Add a property to your object and reference that property in the DataGrid:
public string IsStolenStr
{
get { return isStolen == 1? "Yes" : "No"; }
}
2) Or add the logic to a <asp:template> column in the DataGrid:
<%# Eval("IsStolen") == 1 ? "Yes" : "No" %>
I would modify the SQL statement so that it returned the Yes/No string based on the isStolen value.

ASP.NET Server control with an additional bindable field

I have created a custom server control, deriving from System.Web.Contols.CheckBoxList to customize how a CheckBoxList is rendered. I also wanted to add another bindable field and get the value of the field within the CheckBoxList.RenderItem() method. The field I want to create, should contain a value specifying whether a CheckBoxListItem is checked. I've read some articles regarding custom DataFields, but it never gets explained in detail.
I've included a portion of my class to better explain what I can't seem to understand.
public class ListedCheckBoxList : CheckBoxList
{
protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
if (itemType != ListItemType.Item)
return;
var item = base.Items[repeatIndex];
string cbxHtml = string.Format("<input type=\"checkbox\" value=\"{0}\" name=\"{1}\" /> {2}",
item.Value,
string.Concat(this.ClientID, repeatIndex),
item.IsChecked, // <-- My custom bindable field
item.Text);
writer.Write(cbxHtml);
}
}
When using this control in the .aspx page, I'm attempting to bind it like this
<abc:ListedCheckBoxList ID="cbxList" runat="server"
DataValueField="UserId"
DataTextField="UserFullName"
DataIsCheckedField="UserIsActive" />
Here is a version I wrote a year or so ago. I wanted to be able to bind the checked status as well as a tooltip for the individual items. Hope it helps...
public class CheckBoxList_Extended : CheckBoxList
{
/// <summary>
/// Gets or sets the name of the data property to bind to the tooltip attribute of the individual CheckBox.
/// </summary>
[DefaultValue("")]
public string DataTooltipField
{
get
{
string value = base.ViewState["DataTooltipField"] as string;
if (value == null)
value = "";
return value;
}
set
{
if (value == null || value.Trim() == "")
{
base.ViewState.Remove("DataTooltipField");
}
else
{
base.ViewState["DataTooltipField"] = value.Trim();
}
}
}
/// <summary>
/// Gets or sets the name of the data property to bind to the Checked property of the individual CheckBox.
/// </summary>
[DefaultValue("")]
public string DataCheckedField
{
get
{
string value = base.ViewState["DataCheckedField"] as string;
if (value == null)
value = "";
return value;
}
set
{
if (value == null || value.Trim() == "")
{
base.ViewState.Remove("DataCheckedField");
}
else
{
base.ViewState["DataCheckedField"] = value.Trim();
}
}
}
protected override void PerformDataBinding(System.Collections.IEnumerable dataSource)
{
if (dataSource != null)
{
string dataSelectedField = this.DataCheckedField;
string dataTextField = this.DataTextField;
string dataTooltipField = this.DataTooltipField;
string dataValueField = this.DataValueField;
string dataTextFormatString = this.DataTextFormatString;
bool dataBindingFieldsSupplied = (dataTextField.Length != 0) || (dataValueField.Length != 0);
bool hasTextFormatString = dataTextFormatString.Length != 0;
bool hasTooltipField = dataTooltipField.Length != 0;
bool hasSelectedField = dataSelectedField.Length != 0;
if (!this.AppendDataBoundItems)
this.Items.Clear();
if (dataSource is ICollection)
this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;
foreach (object dataItem in dataSource)
{
ListItem item = new ListItem();
if (dataBindingFieldsSupplied)
{
if (dataTextField.Length > 0)
{
item.Text = DataBinder.GetPropertyValue(dataItem, dataTextField, null);
}
if (dataValueField.Length > 0)
{
item.Value = DataBinder.GetPropertyValue(dataItem, dataValueField, null);
}
}
else
{
if (hasTextFormatString)
{
item.Text = string.Format(CultureInfo.CurrentCulture, dataTextFormatString, new object[] { dataItem });
}
else
{
item.Text = dataItem.ToString();
}
item.Value = dataItem.ToString();
}
if (hasSelectedField)
{
item.Selected = (bool)DataBinder.GetPropertyValue(dataItem, dataSelectedField);
}
if (hasTooltipField)
{
string tooltip = DataBinder.GetPropertyValue(dataItem, dataTooltipField, null);
if (tooltip != null && tooltip.Trim() != "")
{
item.Attributes["title"] = tooltip;
}
}
this.Items.Add(item);
}
}
base.PerformDataBinding(null);
}
}
Checkbox already has a property for that, "Checked"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.checked.aspx
You can add a custom fairly easily though, just add a new public property. You can then set it programatically or in the aspx code.
public class ListedCheckBoxList : CheckBoxList
{
public string CustomTag { get; set; }
//...snip
}
<myControls:myCheckBox runat='server' Checked='True' CustomTag="123test" />

How do I make a virtual node using MPF?

I am creating a new project type using MPF.
I want to create a type of node where the backing for that node doesn't actually exist anywhere. To keep it simple, I just want to generate the captions on the fly.
I have created a new node subclass from HierarchyNode because it will eventually have children. I have subclassed the FolderNode so I can determine which folders will have these virtual nodes as children. I am using Get/SetMetadata to do that and it works fine. I overrode GetProperty in MyFolderNode so that if the folder type is a "normal" folder, it just routes to base. Otherwise it returns a VirtualNode for FirstChild. The VirtualNodes create their next sibling and set NextSibling to it. TL;DR: Code follows.
My problem is that it isn't working. Specifically, when I click on the "Expand this folder" icon, it turns blue (so the click is registering) but it stays blue and the node isn't expanded. Debugging shows that trying to expand the folder does hit GetProperty requesting FirstChild and it does return the id of the first child. After that the VirtualNode is queried twice to see if it is expandable. Then it is queried for the caption. Then the icon. Then nothing.
Here is the code for my FolderNode subclass:
public class AndroidFolderNode : FolderNode
{
public enum FolderType
{
Normal,
JavaSource
}
public string[] VirtualNodes = new[]
{
"Virtual Node One",
"Virtual Node Two",
"Virtual Node Three"
};
private FolderType mFolderType;
public FolderType Type
{
get
{
return mFolderType;
}
set
{
if (mFolderType != value)
{
mFolderType = value;
OnInvalidateItems(this);
}
}
}
private HierarchyNode mVirtualChild;
public AndroidFolderNode(ProjectNode root, string relativePath, ProjectElement element)
: base(root, relativePath, element)
{
var t = element.GetMetadata("Type");
if (string.IsNullOrWhiteSpace(t))
{
Type = FolderType.Normal;
}
else
{
FolderType tempType;
if (Enum.TryParse(t, true, out tempType))
{
Type = tempType;
}
}
}
protected override NodeProperties CreatePropertiesObject()
{
return new AndroidFolderNodeProperties(this);
}
public override object GetProperty(int propId)
{
object result = null;
switch ((__VSHPROPID) propId)
{
case __VSHPROPID.VSHPROPID_FirstChild:
goto case __VSHPROPID.VSHPROPID_FirstVisibleChild;
case __VSHPROPID.VSHPROPID_FirstVisibleChild:
if (Type == FolderType.Normal)
{
result = (int)((this.FirstChild != null) ? this.FirstChild.ID : VSConstants.VSITEMID_NIL);
}
else
{
if (mVirtualChild == null)
{
mVirtualChild = new VirtualFolderNode(this, 0);
}
result = mVirtualChild.ID;
}
break;
default:
result = base.GetProperty(propId);
break;
}
return result;
}
}
Here is the code for my VirtualNode:
class VirtualFolderNode : HierarchyNode
{
private static Guid _guid = new Guid("DD264E51-2E66-4BCC-A8A6-DE3BDE890DED");
private int mIdx;
private AndroidFolderNode mParent;
private VirtualFolderNode mSibling;
public VirtualFolderNode(AndroidFolderNode parent, int idx)
: base(parent.ProjectMgr)
{
mParent = parent;
mIdx = idx;
Parent = parent;
if (idx < parent.VirtualNodes.Length)
{
mSibling = new VirtualFolderNode(parent, idx + 1);
NextSibling = mSibling;
}
}
public override string Url
{
get { return Parent.Url + "\\VNode" + mIdx; }
}
public override string Caption
{
get { return mParent.VirtualNodes[mIdx]; }
}
public override Guid ItemTypeGuid
{
get { return _guid; }
}
}
Got it! (Side note: I've never had to answer my own question before.)
The problem, it appears, is that the HierarchyNode.GetIconHandle(bool open) simply returns null. Overriding GetIconHandle in VirtualNode allows it to be displayed as expected. So I added this to VirtualNode and bada bing, bada boom:
public override object GetIconHandle(bool open)
{
return ProjectMgr.ImageHandler.GetIconHandle(open ? (int)ProjectNode.ImageName.OpenFolder : (int)ProjectNode.ImageName.Folder);
}

Categories

Resources