I have this code:
public IfStatement? m_IfStatement;
public struct IfStatement
{
public string Statement { get; private set; }
public string Comparison { get; private set; }
public string ConditionValue { get; private set; }
public string IfCondition_True { get; private set; }
public string IfCondition_False { get; private set; }
}
and when I'm trying to set values to the struct like this:
m_IfStatement = new IfStatement();
m_IfStatement.Statement = cboIfStatement.SelectedItem.ToString();
m_IfStatement.Comparison = cboComparison.SelectedItem.ToString();
m_IfStatement.ConditionValue = txtIfValue.Text;
m_IfStatement.IfTrue = "";
m_IfStatement.IfFalse = "";
I'm getting this error by the compailer:
'System.Nullable<Core.BaseControls.IntegrationTool.frmDataManipulation.IfStatement>'
does not contain a definition for 'Statement' and no extension method 'Statement'
accepting a first argument of type
'System.Nullable<Core.BaseControls.IntegrationTool.frmDataManipulation.IfStatement>'
could be found (are you missing a using directive or an assembly reference?)
What does it mean ? and how do I solve this...? please.
Both statements are in the same scope (e.g. in the same class).
Nullable types access with Value property. Nullable Types
public IfStatement? m_IfStatement;
public struct IfStatement
{
public string Statement { get; set; }
public string Comparison { get; set; }
public string ConditionValue { get; set; }
public string IfCondition_True { get; set; }
public string IfCondition_False { get; set; }
}
m_IfStatement = new IfStatement();
IfStatement ifStat = m_IfStatement.Value;
ifStat.Statement = cboIfStatement.SelectedItem.ToString();
ifStat.Comparison = cboComparison.SelectedItem.ToString();
ifStat.ConditionValue = txtIfValue.Text;
ifStat.TrueCondition = "";
ifStat.FalseCondition = "";
Since structs are value-types (and therefore cannot be null) and you want it be nullable, you should create a constructor to set the properties. This way you can keep your properties with private setters.
public struct IfStatement {
public IfStatement (string statement, string comparison, string conditionValue, string ifCondition_True, string ifCondition_False) {
Statement = statement;
Comparison = comparison;
ConditionValue = conditionValue;
IfCondition_True = ifCondition_True;
IfCondition_False = ifCondition_False;
}
public string Statement { get; private set; }
public string Comparison { get; private set; }
public string ConditionValue { get; private set; }
public string IfCondition_True { get; private set; }
public string IfCondition_False { get; private set; }
}
And use it like
m_IfStatement = new IfStatement(
cboIfStatement.SelectedItem.ToString(),
cboComparison.SelectedItem.ToString()
txtIfValue.Text,
"",
""
);
This will prevent any trouble you have setting a property of a nullable struct.
In your first section you have this:
public string Statement { get; private set; }
and your second
m_IfStatement.Statement = cboIfStatement.SelectedItem.ToString();
The second section you are setting Statement, which you have defined in your first that you can only do within the struct itself (i.e. marking it as private).
To fix this, simply change your definition(s) to read:
public string Statement { get; set; }
Related
how to convert dynamic variable to specific class.
dynamic variable has the same properties as my specific class.
public class PracovnikHmotZodpovednostDropDownListItem
{
[Column("ZAZNAM_ID")]
public int? ZaznamId { get; set; }
[Column("TEXT")]
public string Text { get; set; }
[Column("VALL")]
public int Value { get; set; }
public bool Disabled { get; set; } = false;
public UpdateStatusEnum UpdateStatus { get; set; }
}
void someMethod(dynamic dtos){
List<PracovnikHmotZodpovednostDropDownListItem> dto =
(List<PracovnikHmotZodpovednostDropDownListItem>)dtos;
}
If all you know is that the properties have the same names, you're in duck typing territory, casting won't help you.
Good news is, it's trivial to do, just tedious:
var dtoList = new List<PracovnikHmotZodpovednostDropDownListItem>();
foreach(var dto in dtos)
dtoList.Add(new()
{
ZaznamId = dto.ZaznamId,
Text = dto.Text,
// etc..
});
I hope this isn't a foolishly simple question. Im very simply trying to figure out how to manipulate a relatively simple table in SQLite through C#.
Im looking to take a parameter and search a List of Arrays for one such array where the parameter matches, and return a related variable within that same array.
For example where an array in the list might be.
Name IATA
Brisbane BNE
The sqlbind:
public static List<Airport> LoadAirports()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
return output.ToList();
}
}
The Class:
class Airport
{
int Id { get; set; }
string Name { get; set; }
string LocationName { get; set; }
string IATA { get; set; }
string PortType { get; set; }
string PortOwner { get; set; }
string MotherPort { get; set; }
bool Active { get; set; }
bool IsApplyMeetAndGreet { get; set; }
decimal MeetAndGreet { get; set; }
}
The main Program:
List<Airport> Airports = new List<Airport>();
public FreightCalculator()
{
LoadAirportsList();
string OriginName = OriginInput.Value;
var OriginAirport = Airports.Where(s => s.Name == OriginName);
}
private void LoadAirportsList()
{
Airports = SqliteDataAccess.LoadAirports();
}
Ive tried various combinations of Where, Equals, For each indexing etc. Always getting an error of some kind.
The Error with the above Airports.Where is that the s.Name is inaccessible due to its protection level.
If I do:
var OriginAirport = Airports.Where(Name => Name == OriginName);
I get an error where the operand == cannot be used with Airport and String (Though Name is a string in Airport.)
Im either missing something simple or making this more complicated than it needs to be. Once I find the matching Airport, I need to return the IATA code.
Which I envisage looking like this:
var OriginIATA = OriginAirport.IATA;
Im tired and feeling dumb. Please help :(
Since you declared all members of the Airport class as properties I assume you wanted to expose them publicly.
The error you get is because they are private members and can't be accessed outside the class.
Change "Airport" class to:
class Airport
{
public int Id { get; set; }
public string Name { get; set; }
public string LocationName { get; set; }
public string IATA { get; set; }
public string PortType { get; set; }
public string PortOwner { get; set; }
public string MotherPort { get; set; }
public bool Active { get; set; }
public bool IsApplyMeetAndGreet { get; set; }
public decimal MeetAndGreet { get; set; }
}
I have two classes with some similar fields, some different, and a form that utilizes two different objects depending on what mode it's in (insert/edit).
Instead of using two different objects and if statements checking the form mode, I'd like to have one struct to be hydrated with either of the two objects fields so I can manipulate one object through the page life-cycle. Then separated the struct back to its respective object for insert/updating the DB.
Example of classes:
public partial class SomeClass
{
public Int32 B {get;set;}
public String C {get;set;}
public Boolean D {get;set;}
}
public class SomeOtherClass
{
public Int32 A {get;set;}
public Int32 B {get;set;}
public String C {get;set;}
}
Update with Solution Example:
public interface IInsertable
{
string SharedName { get; set; }
string SharedID { get; set; }
string editedFieldValue { get; set; }
long GetSuperSecreteInfo();
}
internal class InsertableImplementation : IInsertable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return -1;
}
}
public interface IUpdateable
{
string SharedName { get; set; }
string SharedID { get; set; }
string updatedFieldValue { get; set; }
Guid GenerateStevesMagicGuid();
}
internal class UpdateableImplementation : IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
public static class WonderTwinFactory
{
public static WonderTwins GenerateWonderTwin(IUpdateable updateable, IInsertable insertable)
{
var wt = new WonderTwins();
// who will win?
wt.SharedID = updateable.SharedID;
wt.SharedID = insertable.SharedID;
// you decide?
wt.SharedName = updateable.SharedName;
wt.editedFieldValue = "stuff";
return wt;
}
}
public class WonderTwins : IInsertable, IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return 1;
}
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
class Program
{
static void Main(string[] args)
{
IUpdateable updateable = new UpdateableImplementation();
IInsertable insertable = new InsertableImplementation();
WonderTwins dualImplementatin = WonderTwinFactory.GenerateWonderTwin(updateable, insertable);
IUpdateable newUpdateable = dualImplementatin as IUpdateable;
IInsertable newInsertable = dualImplementatin as IInsertable;
}
}
Have both classes implement an interface that defines the operations common to each, including both the fields that are shared (assuming the view needs to access them) and also a method to actually perform the operation that they represent (insert/edit).
Other way of doing such things is using C# dynamic object and assign properties directly. It may help to avoid any new type or interface and directly utilizing new dynamic object any time, as much as required.
var newObject = new {
objectOfClass1 = x.prop1,
objectOfClass2 = x.prop2
}
I'm having some trouble storing and retrieving items into a list<> with a custom structure.
My structure looks like this:
public class list_rss_parameters
{
public string this_string { get; set; }
public string title_start { get; set; }
public string title_end { get; set; }
public string description_start { get; set; }
public string description_end { get; set; }
public string link_start { get; set; }
public string link_end { get; set; }
public string publish_date_start { get; set; }
public string publish_date_end { get; set; }
public string author_start { get; set; }
public string author_end { get; set; }
}
My stored procedure looks like this (and note that the variable names are the same as the custom Key names) Is this ok?
//this is the last part of a custom method that returns a list
List<list_rss_parameters> list_rss_items = new List<list_rss_parameters>();
list_rss_items.Add(new list_rss_parameters()
{
this_string = this_string,
title_start = title_start,
title_end = title_end,
description_start = description_start,
description_end = description_end,
link_start = link_start,
link_end = link_end,
publish_date_start = publish_date_start,
publish_date_end = publish_date_end,
author_start = author_start,
author_end = author_end
});
return list_rss_items;
If the above two setups are correct, how do I pull items out of the List once I return it?
List<list_rss_parameters> list_rss_parameters = new List<list_rss_parameters>();
list_rss_parameters = f_discover_rss_parameters(rss);
show(list_rss_parameters.Count.ToString());
show(list_rss_parameters[0].ToString()); //does not show this_string
show(list_rss_parameters[this_string'] //does not show this_string
show(list_rss_parameters[0][this_string'];//does not show this_string
What am I doing wrong?
You want the this_string property of the first item in your list it seems:
show(list_rss_parameters[0].this_string);
Or show all of them:
foreach(var item in list_rss_parameters)
{
Console.WriteLine(item.this_string);
}
As a side note your property names don't match the PascalCase naming convention for properties in .NET - so this_string really should be ThisString.
I am working on a trading API (activex from interactive brokers)which has a method called:
void reqMktDataEx(int tickerId, IContract contract, string generalDetails, int snapshot)
The issue is around the last parameter "int snapshot" which obviously requires an int input which actually indicates that whether trader wanna snapshot market data or not. So I guess that if I set it to non-zero, then the implicit conversion would convert this non-zero to be bool value "true".
However, I am using c# to connect to this api. Everything was fine until this one. I tried this:
A. void reqMktDataEx(1, AUDUSD, "100", 0)
Please ignore the first three parameters "1, AUDUSD, "100"", the only matter is the last one 0 as int. I got paused during debugging and the information is :
"Specified cast is not valid. Invalidcastexception is unhandled" and "when casting from a number, the number must not be infinity".
After this I learned that here is a difficulty for c# to treat 1 as bool true and 0 as bool false IMPLICITLY according this
web http://www.dotnetperls.com/convert-bool-int
B. I tried this
void reqMktDataEx(1, AUDUSD, "100", Convert.ToInt16(false)) I got similar error again.
C. I tried again this one:
void reqMktDataEx(1, AUDUSD, "100", int.Parse("false"))
the complaint is input string was not in a correct format. Make sure that you method arguments are in the right format.
MY GUESS:
Here is a inside configuration of C# which does not treat 0 as false and 1 as true. Is there any way to solve?
First Edit
As suspected by one professional programmer below, I post the contract class and audusd definition here for him.
namespace InteractiveBrokersTradingSystem
{
class Contract:TWSLib.IContract
{
public int conId { get; set; }
public string symbol { get; set; }
public string secType { get; set; }
public string expiry { get; set; }
public double strike { get; set; }
public string right { get; set; }
public string multiplier { get; set; }
public string exchange { get; set; }
public string primaryExchange { get; set; }
public string currency { get; set; }
public string localSymbol { get; set; }
public int includeExpired { get; set; }
public object comboLegs { get; set; }
public object underComp { get; set; }
public string comboLegsDescrip { get; set; }
public string secIdType { get; set; }
public string secId { get; set; }
}
}
namespace InteractiveBrokersTradingSystem
{
class Forex:Contract
{
public Forex(string preCurrency,string baseCurrency)
{
//conId = 14433401;
symbol = preCurrency;
secType = "CASH";
exchange = "IDEALPRO";
currency = baseCurrency;
strike = 0;
includeExpired = 0;
primaryExchange = "IDEALPRO";
}
}
}
The method I use to call the reqMktDataEx:
implementation first, simple inheritance:
public void MyReqMarketData(int tickId, IContract contract, string tickTypes, int snapshot)
{
reqMktDataEx(tickId, contract, tickTypes, snapshot);
}
private void AudButtonItemItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Forex audusd = new Forex("AUD", "USD");
_myTwsClass.MyReqMarketData(1,audusd, "100", 0);
}
Second Edit:
System.InvalidCastException was unhandled
Message=Unable to cast object of type 'InteractiveBrokersTradingSystem.Forex' to type 'TWSLib.IContract'.
Source=InteractiveBrokersTradingSystem
It seems that here is some casting problem between the forex class I defined and the Icontract com thing. Here is my new definition:
namespace InteractiveBrokersTradingSystem
{
class Forex
{
public int conId { get; set; }
public string symbol { get; set; }
public string secType { get; set; }
public string expiry { get; set; }
public double strike { get; set; }
public string right { get; set; }
public string multiplier { get; set; }
public string exchange { get; set; }
public string primaryExchange { get; set; }
public string currency { get; set; }
public string localSymbol { get; set; }
public int includeExpired { get; set; }
public object comboLegs { get; set; }
public object underComp { get; set; }
public string comboLegsDescrip { get;set; }
public string secIdType { get; set; }
public string secId { get; set; }
public Forex(string preCurrency,string baseCurrency)
{
//conId = 0;
//symbol = preCurrency;
//secType = "CASH";
//expiry = null;
//strike = double.Parse("0");
//right = null;
//multiplier = null;
//exchange = "IDEALPRO";
//primaryExchange = "IDEALPRO";
//currency = baseCurrency;
//localSymbol = null;
//includeExpired = 0;
//comboLegs = null;
//underComp = null;
//comboLegsDescrip = null;
//secType = null;
//secId = null;
}
}
}
As you can see that the Forex class inherits from the TWS.IContract. how it could not be cast to Icontract successively?
There is no implicit conversion of a bool to an int. Only an explicit one:
Convert.ToInt32(someBool)
// or...
someBool ? 1 : 0
From that site you linked:
First, you cannot implicitly convert from bool to int. The C# compiler uses this rule to enforce program correctness. It is the same rule that mandates you cannot test an integer in an if statement.
Edit
int doesn't have a concept of infinity. Only float and double do. This means it won't be related to that parameter, unless that parameter just controls the flow of the code that is actually crashing. Which still means it isn't the conversion causing the problem.
You're getting a different error for int.Parse("false") because it is expecting a number, not a true/false value. This will always throw an exception at runtime, but it will throw in your code, not in the library's code.
I'm starting to think it is the second parameter, contract, for which you've supplied AUDUSD.
One more way is to have extension method:
public static class BooleanExtensions
{
public static int ToInt(this bool value)
{
return value ? 1 : 0;
}
}
then it can be used:
bool result = false;
result.ToInt();
make field tinyint in database
tinyint fieldname;
c# code
convert.toint32(fieldname.tostring());//returns 1 or 0
to get boolean value
covert.tobool(fieldname.tostring()) ;
There's no implicit cast to int from bool. So make your own. Then add them up.
Boolean
byFinancialCenter = false,
byProvider = false,
byServiceSite = false,
byProcedure = false;
int b2i(bool source) => source ? 1 : 0;
int ForeignKeyCount() => b2i(byFinancialCenter) + b2i(byProvider) + b2i(byServiceSite) + b2i(byProcedure);
The b2i is generic, as I needed the specific count in several places, including the last function makes it easy to use. Also, for maintenance, having the embedded function just under the bools makes it more likely that subsequent developers will see what's happening.