Trying to convert a DataTable to a POCO list. Found some answers to that topic at StackOverflow and I thougth everything should be O.K. but I doesn't get the correct result. The result is an empty list of five items. So there is no mapping from the DataRow to the POCO object.
Any thoughts what can be wrong?
AutoMapper is version 6.1.1
AutoMapper.Data version 1.0.0
class Program
{
static void Main( string[] args )
{
var config = new MapperConfiguration( cfg =>
{
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<IDataReader, Person>();
} );
var mapper = config.CreateMapper();
DataTable tbl = DataGenerator.MyPersons();
var result = mapper.Map<List<Person>>( tbl.CreateDataReader() );
}
}
public static class DataGenerator
{
public static DataTable MyPersons()
{
DataTable myPersonssDataTable = new DataTable();
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "FirstName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "LastName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "DateOfBirth",
DataType = typeof( DateTime )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "JobTitle",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "TakenName",
DataType = typeof( string )
} );
myPersonssDataTable.Columns.Add( new DataColumn()
{
ColumnName = "IsAmerican",
DataType = typeof( bool )
} );
myPersonssDataTable.Rows.Add( new object[] { "Lenny", "Belardo", new DateTime( 1971, 3, 24 ), "Pontiff", "Pius XIII", true } );
myPersonssDataTable.Rows.Add( new object[] { "Angelo", "Voiello", new DateTime( 1952, 11, 18 ), "Cardinal Secretary of State", "", false } );
myPersonssDataTable.Rows.Add( new object[] { "Michael", "Spencer", new DateTime( 1942, 5, 12 ), "Archbishop of New York", "", true } );
myPersonssDataTable.Rows.Add( new object[] { "Sofia", "(Unknown)", new DateTime( 1974, 7, 2 ), "Director of Marketing", "", false } );
myPersonssDataTable.Rows.Add( new object[] { "Bernardo", "Gutierrez", new DateTime( 1966, 9, 16 ), "Master of Ceremonies", "", false } );
return myPersonssDataTable;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string JobTitle { get; set; }
public string TakenName { get; set; }
public bool IsAmerican { get; set; }
}
You forgot to add the DataReader mapping.
cfg.AddDataReaderMapping();
Then your code should look similar to:
...
var config = new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<IDataReader, Person>();
});
...
I hope it helps.
Related
I using broadleaf-commerce famework for my program. I just want to know, how to visibility of AdminPresentationCollection in to config entity file. I config in js file but it doesn't work.
This's my entity. It use #AdminPresentation annotations and #AdminPresentationCollection annotations :
#Entity
#Table(name="BLC_PRICE_LIST")
#Inheritance(strategy = InheritanceType.JOINED)
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
#SQLDelete(sql="UPDATE BLC_PRICE_LIST SET ARCHIVED = 'Y' WHERE PRICE_LIST_ID = ?")
#DirectCopyTransform({
#DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true),
#DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_CATALOG)
})
public class PriceListImpl implements PriceList, PriceListAdminPresentation, AdminMainEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "PriceListId")
#GenericGenerator(
name="PriceListId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
#Parameter(name="segment_value", value="PriceListImpl"),
#Parameter(name="entity_name", value="com.community.core.pricelist.domain.PriceListImpl")
}
)
#Column(name = "CUSTOMER_RESTRICTION_RULE_TYPE")
#AdminPresentation(
friendlyName = "prices_rule_customer_title_group",
group = GroupName.Customer, order = FieldOrder.TargetCustomer,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
broadleafEnumeration="com.community.core.pricelist.service.type.PriceListCustomerRestrictionRuleType",
defaultValue = "prices_rule_customer_available_for_all_customer",
tooltip = "prices_rule_customer_tooltip"
)
protected String customerRestrictionRuleType;
#OneToMany(mappedBy = "priceList",
targetEntity = PriceListPriceListRuleXrefImpl.class,
cascade = { CascadeType.ALL },
orphanRemoval = true)
#MapKey(name = "key")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blPriceLists")
#AdminPresentationMapFields(
toOneTargetProperty = "priceListRule",
toOneParentProperty = "priceList",
mapDisplayFields = {
#AdminPresentationMapField(
fieldName = RuleIdentifier.CUSTOMER_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.Customer,
order = FieldOrder.CustomerRule,
ruleIdentifier = RuleIdentifier.CUSTOMER,
friendlyName = "RESTRICT TO THE FOLLOWING CUSTOMERS"
)
)
,
#AdminPresentationMapField(
fieldName = RuleIdentifier.PRICING_CONTEXT_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.PricingContext,
order = FieldOrder.PricingContext,
ruleIdentifier = RuleIdentifier.PRICING_CONTEXT,
friendlyName = "price_list_rule_pricing_context_lab")
)
,
#AdminPresentationMapField(
fieldName = RuleIdentifier.REQUEST_FIELD_KEY,
fieldPresentation = #AdminPresentation(
fieldType = SupportedFieldType.RULE_SIMPLE,
group = GroupName.PricingContext,
order = 9000,
ruleIdentifier = RuleIdentifier.REQUEST,
friendlyName = "LIMIT TO CERTAIN WEB REQUESTS?")
)
}
)
Map<String, PriceListPriceListRuleXref> priceListMatchRules = new HashMap<String, PriceListPriceListRuleXref>();
#OneToMany(mappedBy = "priceList", targetEntity = PriceModifierImpl.class,
cascade = { CascadeType.ALL }, orphanRemoval = true)
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blPriceLists")
#BatchSize(size = 50)
#AdminPresentationCollection( friendlyName = "Price Modifiers",
group = GroupName.PricingContext,
order = 20000,
addType = AddMethodType.PERSIST
,showIfFieldEquals={
#org.broadleafcommerce.common.presentation.FieldValueConfiguration(
fieldName = "customerRestrictionRuleType",
fieldValues = {"ALL_CUSTOMERS", "A","B", "a" , "b"}
)
}
)
protected List<PriceModifier> priceModifier = new ArrayList<PriceModifier>(100);
#Column(name = "ERROR_CODE")
#AdminPresentation(friendlyName = "productOption_errorCode",
group = GroupName.PricingContext, order = 21000)
protected String errorCode;
#Override
public Boolean getIsPricingContext() {
return isPricingContext;
}
#Override
public void setIsPricingContext(Boolean isPricingContext) {
this.isPricingContext = isPricingContext;
}
#Override
public Boolean getIsRequest() {
return isRequest;
}
#Override
public void setIsRequest(Boolean isRequest) {
this.isRequest = isRequest;
}
#Embedded
protected ArchiveStatus archiveStatus = new ArchiveStatus();
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
public String getCustomerRestrictionRuleType() {
return customerRestrictionRuleType;
//return DynamicTranslationProvider.getValue(this, "customerRestrictionRuleType", customerRestrictionRuleType);
}
public void setCustomerRestrictionRuleType(String customerRestrictionRuleType) {
this.customerRestrictionRuleType = customerRestrictionRuleType;
}
#Override
public Map<String, PriceListPriceListRuleXref> getPriceListMatchRulesXref() {
return priceListMatchRules;
}
#Override
public void setPriceListMatchRulesXref(Map<String, PriceListPriceListRuleXref> priceListMatchRulesXref) {
this.priceListMatchRules = priceListMatchRulesXref;
}
#Override
public List<PriceModifier> getPriceModifier() {
return priceModifier;
}
#Override
public void setPriceModifier(List<PriceModifier> priceModifier) {
this.priceModifier = priceModifier;
}
#Override
public Character getArchived() {
ArchiveStatus temp;
if (archiveStatus == null) {
temp = new ArchiveStatus();
} else {
temp = archiveStatus;
}
return temp.getArchived();
}
#Override
public void setArchived(Character archived) {
if (archiveStatus == null) {
archiveStatus = new ArchiveStatus();
}
archiveStatus.setArchived(archived);
}
#Override
public boolean isActive() {
return DateUtil.isActive(startDate, endDate, true) && 'Y'!=getArchived();
}
#Override
public <G extends PriceList> CreateResponse<G> createOrRetrieveCopyInstance(MultiTenantCopyContext context) throws CloneNotSupportedException {
CreateResponse<G> createResponse = context.createOrRetrieveCopyInstance(this);
if (createResponse.isAlreadyPopulated()) {
return createResponse;
}
PriceList cloned = createResponse.getClone();
cloned.setName(name);
return createResponse;
}
#Override
public String getMainEntityName() {
return getName();
}
#Override
public PriceList createPriceList(){
return new PriceListImpl();
}
}
And this is my enum:
public static final PriceListCustomerRestrictionRuleType ALL_A = new PriceListCustomerRestrictionRuleType("ALL_CUSTOMERS", "AVAILABLE TO ALL CUSTOMERS");
public static final PriceListCustomerRestrictionRuleType A_RULE_ASSIGNMENT_A = new PriceListCustomerRestrictionRuleType("CUSTOMER_RULE_ASSIGNMENT_CUSTOMERS", "CUSTOMER RULE AND ASSIGNMENT TO CUSTOMERS");
And this is my js file:
(function($, BLCAdmin) {
$.each(['com.community.core.pricelist.domain.PriceList'], function(idx, clazz) {
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceListMatchRules---CUSTOMER',
'CUSTOMER_RULE_ASSIGNMENT_CUSTOMERS'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isPricingContext',
'#field-priceListMatchRules---PRICING-CONTEXT',
'true'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isRequest',
'#field-priceListMatchRules---REQUEST',
'true'
);
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceModifier',
'ALL_CUSTOMERS'
);
/*BLCAdmin.addDependentFieldHandler(
clazz,
'#field-customerRestrictionRuleType',
'#field-priceModifier',
'ALL_CUSTOMERS'
);*/
});
/*$.each(['com.community.core.pricelist.domain.PriceModifier'], function(idx, clazz) {
BLCAdmin.addDependentFieldHandler(
clazz,
'#field-isTargetedItemsRule',
'#field-priceModifierMatchRules---PRODUCT',
'true'
);
});*/
})(jQuery, BLCAdmin);
Help me! Many thank!
I am trying to display variable columns in WebGrid in MVC5. Following shows the snippet. However, I am not sure how to render the list of columns and stuck at it.
public class gridmatx
{ public Grid Grid { get; set; }
}
public class Grid
{ public List<string> Columns { get; set; }
public List<GridRow> Rows { get; set; }
}
public class GridRow
{ public string Label { get; set; }
public List<decimal> Values { get; set; }
public List<GridRow> ChildRows { get; set; }
}
//----- controller-------
public ActionResult Index1()
{ gridmatx g = new gridmatx();
g.Grid = new Grid();
g.Grid.Columns = new List<string> { "2011", "2012", "2013", "2014", "2015" };
g.Grid.Rows = new List<GridRow>
{ new GridRow { Label = "First", Values = new List<decimal> { 5M, 2M, 1M, 8M, 10M } },
new GridRow { Label = "Second", Values = new List<decimal> { 2M, 2M, 4M, 8M, 9M } },
new GridRow { Label = "Third", Values = new List<decimal> { 12M, 8M, 1M, 9M, 3M } }
};
return View(g);
}
var grid = new WebGrid(Model.Grid.Rows, canSort: false, canPage: true, rowsPerPage: 5);
<div>
#{
for (int i = 0; i < Model.Grid.Columns.Count; i++)
{
var index = i;
#grid.GetHtml(columns:
grid.Columns
( grid.Column("Label", "items"),
grid.Column(Model.Grid.Rows[i].Values[index], "columnX")
), mode: WebGridPagerModes.Numeric);
}
I have one "label" column and variable number of "Values" columns.
Appreciate your help in advance.
I want to get String in List< String > but did not work.
Drools Rule
import schedule.Schedule
import schedule.Control_Exam_List
rule "People"
salience 5
when
$controlExamList : Control_Exam_List( ) from accumulate( $scheduleCheck : Schedule( $scheduleCECheck1 : control1 , $scheduleCECheck2 : control2 , $scheduleCECheck3 : control3 ) ,
init( Control_Exam_List CEL = new Control_Exam_List(); ),
action( CEL.addData($scheduleCECheck1); CEL.addData($scheduleCECheck2); CEL.addData($scheduleCECheck3); ),
result( CEL ) )
then
System.out.println("Test1: "+$controlExamList);
end
The result return list but I get all string from this list.
Result : Still list< String >
Test1: schedule.Control_Exam_List#22916a
Control_Exam_List Class : List< String >
import java.util.ArrayList;
import java.util.List;
public class Control_Exam_List {
private List<String> code = new ArrayList<String>();
public void addData(String code){
if(this.code.contains(code) != true && !code.equals(""))
this.code.add(code);
}
public List<String> getCode() {
return code;
}
}
Schedule Class : Accumulate from this class
public class Schedule {
private String control1 = "", control2 = "", control3 = "";
public String getControl1() {
return control1;
}
public String getControl2() {
return control2;
}
public String getControl3() {
return control3;
}
public void setControlExam1(String ce_code) {
this.control1 = ce_code;
}
public void setControlExam2(String ce_code) {
this.control2 = ce_code;
}
public void setControlExam3(String ce_code) {
this.control3 = ce_code;
}
}
This is almost as you'd do it Java, with $controlExamList being bound to a Control_Exam_List object; although, in Drools, you may have to cast:
then
for( Object obj: $controlExamList.getCode() ){
System.out.println( (String)obj );
}
end
But you can also try:
then
for( String str: $controlExamList.getCode() ){
System.out.println( str );
}
end
I am getting the token from acs as describe in this post Validating a SWT Token REST WCF Service
But i was not able to extract the ACS token.
Could you please help me in that.
Actually the class the extract the acs token "JsonNotifyRequestSecurityTokenResponse.FromJson"
I was not able to get that as the class as the link provided is not working.
I think you posted this question as an answer at my question some hours ago and then deleted it. So i looked up my old project and found the code you need:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Xml.Linq;
using Thinktecture.IdentityModel.Extensions;
namespace Security {
[DataContract]
public class JsonNotifyRequestSecurityTokenResponse {
[DataMember(Name = "appliesTo", Order = 1)]
public string AppliesTo { get; set; }
[DataMember(Name = "context", Order = 2)]
public string Context { get; set; }
[DataMember(Name = "created", Order = 3)]
public string Created { get; set; }
[DataMember(Name = "expires", Order = 4)]
public string Expires { get; set; }
[DataMember(Name = "securityToken", Order = 5)]
public string SecurityTokenString { get; set; }
[DataMember(Name = "tokenType", Order = 6)]
public string TokenType { get; set; }
public DateTime ValidFrom { get; set; }
public DateTime ValidTo { get; set; }
public GenericXmlSecurityToken SecurityToken { get; set; }
public static JsonNotifyRequestSecurityTokenResponse FromJson(string jsonString) {
JsonNotifyRequestSecurityTokenResponse rstr;
var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
var serializer = new DataContractJsonSerializer(typeof(JsonNotifyRequestSecurityTokenResponse));
rstr = serializer.ReadObject(memoryStream) as JsonNotifyRequestSecurityTokenResponse;
memoryStream.Close();
ParseValues(rstr);
return rstr;
}
private static void ParseValues(JsonNotifyRequestSecurityTokenResponse rstr) {
rstr.ValidFrom = ulong.Parse(rstr.Created).ToDateTimeFromEpoch();
rstr.ValidTo = ulong.Parse(rstr.Expires).ToDateTimeFromEpoch();
rstr.SecurityTokenString = HttpUtility.HtmlDecode(rstr.SecurityTokenString);
var xml = XElement.Parse(rstr.SecurityTokenString);
string idAttribute = "";
string tokenType = "";
switch (rstr.TokenType) {
case SecurityTokenTypes.Saml11:
idAttribute = "AssertionID";
tokenType = SecurityTokenTypes.Saml11;
break;
case SecurityTokenTypes.Saml2:
idAttribute = "ID";
tokenType = SecurityTokenTypes.Saml2;
break;
case SecurityTokenTypes.SWT:
idAttribute = "Id";
tokenType = SecurityTokenTypes.SWT;
break;
}
if (tokenType == SecurityTokenTypes.Saml11 || tokenType == SecurityTokenTypes.Saml2) {
var tokenId = xml.Attribute(idAttribute);
var xmlElement = xml.ToXmlElement();
SecurityKeyIdentifierClause clause = null;
if (tokenId != null) {
clause = new SamlAssertionKeyIdentifierClause(tokenId.Value);
}
rstr.SecurityToken = new GenericXmlSecurityToken(
xmlElement,
null,
rstr.ValidFrom,
rstr.ValidTo,
clause,
clause,
new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>()));
}
}
private class SecurityTokenTypes {
public const string Saml2 = "urn:oasis:names:tc:SAML:2.0:assertion";
public const string Saml11 = "urn:oasis:names:tc:SAML:1.0:assertion";
public const string SWT = "http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0";
}
}
}
You should get the Thinktecture.IdentityModel.Extensions assembly from: http://identitymodel.codeplex.com/
I hope this helps.
EDIT - SWT token handling
I don't know if it helps, but I've found a SWTModule which should handle a SWT token.
public class SWTModule : IHttpModule {
void IHttpModule.Dispose() {
}
void IHttpModule.Init(HttpApplication context) {
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e) {
//HANDLE SWT TOKEN VALIDATION
// get the authorization header
string headerValue = HttpContext.Current.Request.Headers.Get("Authorization");
// check that a value is there
if (string.IsNullOrEmpty(headerValue)) {
throw new ApplicationException("unauthorized");
}
// check that it starts with 'WRAP'
if (!headerValue.StartsWith("WRAP ")) {
throw new ApplicationException("unauthorized");
}
string[] nameValuePair = headerValue.Substring("WRAP ".Length).Split(new char[] { '=' }, 2);
if (nameValuePair.Length != 2 ||
nameValuePair[0] != "access_token" ||
!nameValuePair[1].StartsWith("\"") ||
!nameValuePair[1].EndsWith("\"")) {
throw new ApplicationException("unauthorized");
}
// trim off the leading and trailing double-quotes
string token = nameValuePair[1].Substring(1, nameValuePair[1].Length - 2);
// create a token validator
TokenValidator validator = new TokenValidator(
this.acsHostName,
this.serviceNamespace,
this.trustedAudience,
this.trustedTokenPolicyKey);
// validate the token
if (!validator.Validate(token)) {
throw new ApplicationException("unauthorized");
}
}
}
And you also need the TokenValidator:
public class TokenValidator {
private string issuerLabel = "Issuer";
private string expiresLabel = "ExpiresOn";
private string audienceLabel = "Audience";
private string hmacSHA256Label = "HMACSHA256";
private string acsHostName;
private string trustedSigningKey;
private string trustedTokenIssuer;
private string trustedAudienceValue;
public TokenValidator(string acsHostName, string serviceNamespace, string trustedAudienceValue, string trustedSigningKey) {
this.trustedSigningKey = trustedSigningKey;
this.trustedTokenIssuer = String.Format("https://{0}.{1}/",
serviceNamespace.ToLowerInvariant(),
acsHostName.ToLowerInvariant());
this.trustedAudienceValue = trustedAudienceValue;
}
public bool Validate(string token) {
if (!this.IsHMACValid(token, Convert.FromBase64String(this.trustedSigningKey))) {
return false;
}
if (this.IsExpired(token)) {
return false;
}
if (!this.IsIssuerTrusted(token)) {
return false;
}
if (!this.IsAudienceTrusted(token)) {
return false;
}
return true;
}
public Dictionary<string, string> GetNameValues(string token) {
if (string.IsNullOrEmpty(token)) {
throw new ArgumentException();
}
return
token
.Split('&')
.Aggregate(
new Dictionary<string, string>(),
(dict, rawNameValue) => {
if (rawNameValue == string.Empty) {
return dict;
}
string[] nameValue = rawNameValue.Split('=');
if (nameValue.Length != 2) {
throw new ArgumentException("Invalid formEncodedstring - contains a name/value pair missing an = character");
}
if (dict.ContainsKey(nameValue[0]) == true) {
throw new ArgumentException("Repeated name/value pair in form");
}
dict.Add(HttpUtility.UrlDecode(nameValue[0]), HttpUtility.UrlDecode(nameValue[1]));
return dict;
});
}
private static ulong GenerateTimeStamp() {
// Default implementation of epoch time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToUInt64(ts.TotalSeconds);
}
private bool IsAudienceTrusted(string token) {
Dictionary<string, string> tokenValues = this.GetNameValues(token);
string audienceValue;
tokenValues.TryGetValue(this.audienceLabel, out audienceValue);
if (!string.IsNullOrEmpty(audienceValue)) {
if (audienceValue.Equals(this.trustedAudienceValue, StringComparison.Ordinal)) {
return true;
}
}
return false;
}
private bool IsIssuerTrusted(string token) {
Dictionary<string, string> tokenValues = this.GetNameValues(token);
string issuerName;
tokenValues.TryGetValue(this.issuerLabel, out issuerName);
if (!string.IsNullOrEmpty(issuerName)) {
if (issuerName.Equals(this.trustedTokenIssuer)) {
return true;
}
}
return false;
}
private bool IsHMACValid(string swt, byte[] sha256HMACKey) {
string[] swtWithSignature = swt.Split(new string[] { "&" + this.hmacSHA256Label + "=" }, StringSplitOptions.None);
if ((swtWithSignature == null) || (swtWithSignature.Length != 2)) {
return false;
}
HMACSHA256 hmac = new HMACSHA256(sha256HMACKey);
byte[] locallyGeneratedSignatureInBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(swtWithSignature[0]));
string locallyGeneratedSignature = HttpUtility.UrlEncode(Convert.ToBase64String(locallyGeneratedSignatureInBytes));
return locallyGeneratedSignature == swtWithSignature[1];
}
private bool IsExpired(string swt) {
try {
Dictionary<string, string> nameValues = this.GetNameValues(swt);
string expiresOnValue = nameValues[this.expiresLabel];
ulong expiresOn = Convert.ToUInt64(expiresOnValue);
ulong currentTime = Convert.ToUInt64(GenerateTimeStamp());
if (currentTime > expiresOn) {
return true;
}
return false;
} catch (KeyNotFoundException) {
throw new ArgumentException();
}
}
}
There are a couple of answers out there for this already, but I have not been able to find anything conclusive. This is the jist of what I am trying to do:
EquityInstrument
public class EquityInstrument : INotifyPropertyChanged
{
private string _Symbol;
public string Symbol
{
get
{
return _Symbol;
}
set
{
_Symbol = value;
OnPropertyChanged("Symbol");
}
}
public EquityInstrument(string Symbol)
{
this.Symbol = Symbol;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
OptionInstrument
public class OptionInstrument : INotifyPropertyChanged;
{
public readonly EquityInstrument UnderlyingInstrument;
private double _StrikePrice;
public double StrikePrice
{
get
{
return _StrikePrice;
}
set
{
_StrikePrice = value;
OnPropertyChanged("StrikePrice");
}
}
private DateTime _Expiration;
public DateTime Expiration;
{
get
{
return _Expiration;
}
set
{
_Expiration = value;
OnPropertyChanged("Expiration");
}
}
public OptionInstrument(string Symbol, double StrikePrice, DateTime Expiration)
{
this.Symbol = Symbol;
this.StrikePrice = StrikePrice;
this.Expiration = Expiration;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string FieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(FieldName);
}
}
}
This code initiates the Option Table...
GridControl OptionGrid = new GridControl();
BindingList<OptionInstrument> BoundList = new BindingList<OptionInstrument>();
public void InitializeDataTable()
{
OptionGrid.DataSource = new BindingSource() { DataSource = BoundList };
BandedGridColumn Column0 = new BandedGridColumn();
Column0.FieldName = "Symbol";
BandedGridColumn Column1 = new BandedGridColumn();
Column1.FieldName = "StrikePrice";
BandedGridColumn Column2 = new BandedGridColumn();
Column2.FieldName = "Expiration";
BandedGridView MainView = (BandedGridView)OptionGrid.MainView;
MainView.Columns.Add(Column0);
MainView.Columns.Add(Column1);
MainView.Columns.Add(Column2);
BoundList.Add(new OptionInstrument("DELL", 12.22, new DateTime(2012, 10, 12));
BoundList.Add(new OptionInstrument("MSFT", 13.23, new DateTime(2012, 09, 16));
BoundList.Add(new OptionInstrument("SPY", 12.23, new DateTime(2012, 07, 18));
}
What do you think? Are there any good design patterns to accomplish this?