C# - Missing definition of object of class - how to write? - c#

this is part of my source code:
var result = DiceWebAPI.PlaceAutomatedBets(
Session, baseBet, guessLow, guessHigh,
betCount > Session.MaxBetBatchSize ? Session.MaxBetBatchSize : betCount,
resetOnWin, resetOnLoss,
increaseOnWin, increaseOnLoss,
maxBet, resetOnMaxLoss, stopOnMaxLoss, stopMaxBalance);
the viusal c# studio 2010 says:
Error 1 No overload for method 'PlaceAutomatedBets' takes 13 arguments D:\Downloads\SampleBot_NET_3_5\SampleBot_NET_Source\Dice.Sample.Bot.3_5\Main.cs 359 30 DiceSampleBot35
I discovered that all arguments of method have definition except the Session one. Can anybody tell me how to write and where to place the definition?
maybe that would help:
in the other file
readonly SessionInfo Session;
and in another one
namespace Dice.Client.Web
{
public sealed class SessionInfo : INotifyPropertyChanged
{
public string AccountCookie { get; }
public long AccountId { get; }
public decimal Balance { get; }
public long BetCount { get; }
public decimal BetPayIn { get; }
public decimal BetPayOut { get; }
public long BetWinCount { get; }
public long ClientSeed { get; }
public string DepositAddress { get; }
public string Email { get; }
public string EmergencyAddress { get; }
public int MaxBetBatchSize { get; }
public string SessionCookie { get; }
public string Username { get; }
public event PropertyChangedEventHandler PropertyChanged;
}
}
UPDATE:
PlaceAutomatedBets.. definition
public static PlaceAutomatedBetsResponse PlaceAutomatedBets(SessionInfo session, AutomatedBetsSettings settings);

You need to go to PlaceAutomatedBets method, and, you will find that your PlaceAutomatedBets only takes 12 arguments, you will need to add the one who is missing.

you are passing extra arguments. Exception is self explanatory. and there is no need to re-define HttpContext.Session Property it's already there in System.Web if you haven't included this just put this line on top of your class Using System.Web;

The problem here is that you are calling a method that has a signature of two parameters:
public static PlaceAutomatedBetsResponse PlaceAutomatedBets(
SessionInfo session,
AutomatedBetsSettings settings);
However, you are calling it with 12:
var result = DiceWebAPI.PlaceAutomatedBets(
Session, baseBet, guessLow, guessHigh,
betCount > Session.MaxBetBatchSize ? Session.MaxBetBatchSize : betCount,
resetOnWin, resetOnLoss,
increaseOnWin, increaseOnLoss,
maxBet, resetOnMaxLoss, stopOnMaxLoss, stopMaxBalance);
C# cannot take your 12 parameters and automatically form them into an object. Instead, you have to build an AutomatedBetsSettings object and pass that in with Session. That's pretty standard in software design, where you want to reduce the number of parameters. The object with all the detail in is often called a context.
For example, you need to do something like:
// I am guessing the content of AutomatedBetsSettings here, you will need
// to check the actual property values.
var betSettingsContext = new AutomatedBetsSettings() {
BaseBet = baseBet,
GuessLow = guessLow,
GuessHigh = guessHigh,
BestCount = betCount > Session.MaxBetBatchSize ? Session.MaxBetBatchSize : betCount,
ResetOnWin = resetOnWin,
ResetOnLoss = resetOnLoss,
IncreaseOnWin = increaseOnWin,
IncreaseOnLoss = increaseOnLoss,
MaxBet = maxBet,
ResetOnMaxLoss = resetOnMaxLoss,
StopOnMaxLoss = stopOnMaxLoss,
StopMaxBalance = stopMaxBalance
};
var result = DiceWebAPI.PlaceAutomatedBets(Session, betSettingsContext);

Try to use like this.
var result = DiceWebAPI.PlaceAutomatedBets(
HttpContext.Current.Session, baseBet, guessLow, guessHigh,
betCount > Session["MaxBetBatchSize"] ? Session["MaxBetBatchSize"] : betCount,
resetOnWin, resetOnLoss,
increaseOnWin, increaseOnLoss,
maxBet, resetOnMaxLoss, stopOnMaxLoss, stopMaxBalance);

Related

Best way to group strings according to action

With "Best Way" I mean, maybe, without many If, clean code.
I have a function that receives as parameters (string currentVersion, string action)
and it should return a string versionToBe = "";
For action = "installOldVersion"
-------------if "currentVersion"----------------: -------------OldversionToInstall--------------
"windows10(pro)", "windows10(pro)(education)" : "windows81(pro)"
"windows10(enterprise)", "windows10(enterpise)(lstb)" : "windows81(enterprise)"
"windows7(home)", "windows7(home)(basic)", "windows7(basic)", "windows7": "windowsVista(starter)"
"windowsXP(starter)", "windowsXP(starter)(home)", "windowsXP(home)", "windowsXP": "windows2000(professional)"
"windowsNT(workstation)", "windowsNT": "windows95(sp1)"
For action = "installNewVersion"
-------------if "currentVersion"----------------: -------------NewVersionToInstall--------------
"windows81(pro)", "windows81(pro)(education)" : "windows10(pro)"
"windows81(enterprise)", "windows81(enterprise)(education)" : "windows10(enterprise)"
"windowsVista(starter)", "windowsVista(starter)(package)", "windowsVista(package)", "windowsVista": "windows7(home)"
"windowsVista(starter)", "windowsVista(starter)(praok)", "windowsVista(praok)", "windowsVista": "windowsXP(starter)"
"windows95(sp1)", "windows95(sp1)(versionE)", "windows95": "windowsNT(workstation)"
So,for example, everytime the string name comes like: "windows10(pro)" or "windows10(pro)(education)" it should return: "windows81(pro)".
I know this can get done with lots of if like:
if (version.Equals("windows10(pro)") || version.Equals("windows10(pro)(education)"))
{
versionToBe = "windows81(pro)";
}
and the same for the rest of them, anding with 10 If statements in Total.
But If there's a better way to do it, I'd want to know.
Another restriction, or other thing to consider:
if the action is "installOldVersion", versionToBe is OldversionToInstall,
and if the action is "installNewVersion", versionTobe would be NewVersionToInstall.
You could create a list of objects with CurrentVersion, Old Version and New Version and then extract the one you want from the list.
Example Instruction Class Definition
public class VersionInformation
{
public string CurrentVersion {get; set;}
public string NewVersion {get; set;}
public string OldVersion {get; set;}
}
then in your program, have a list of them, either hard coded or loaded from file or whatever datastore you want and do your version check as follows:
private List<VersionInformation> _versionInformation = //Load your list from wherever;
public void DoVersionCheck(string version)
{
var currentversionInfo = _versionInformation.Single(x=> x.CurrentVersion == version);
//Do Whatever you want with the upgrades and downgrades here based on whatever action you are doing
}
Set yourself up a dictionary and perform a lookup.
As an exercise for the reader:
You could drive the dictionary contents from some configuration or other...even from a database if you want.
You'd presumably want to set up your dictionary as a static and initialize it only once.
You'll want some handling for when there is no dictionary entry - you don't specify a default in your question.
Dictionary, string> ActionMatrix = new Dictionary, string>();
ActionMatrix.Add(Tuple.Create ("windows10(pro)", "installOldVersion"), "windows81(pro)");
ActionMatrix.Add(Tuple.Create ("windows10(pro)(education)", "installOldVersion"), "windows81(pro)");
ActionMatrix.Add(Tuple.Create ("windows10(enterprise)", "installOldVersion"), "windows81(enterprise)");
ActionMatrix.Add(Tuple.Create ("windows10(enterpise)(lstb)", "installOldVersion"), "windows81(enterprise)");
// etc
ActionMatrix.Add(Tuple.Create("windows81(pro)", "installNewVersion"), "windows10(pro)");
ActionMatrix.Add(Tuple.Create("windows81(pro)(education)", "installNewVersion"), "windows10(pro)");
ActionMatrix.Add(Tuple.Create("windows81(enterprise)", "installNewVersion"), "windows10(enterprise)");
ActionMatrix.Add(Tuple.Create("windows10(enterpise)(education)", "installNewVersion"), "windows10(enterprise)");
// etc
public string VersionToBe (string currentVersion, string action)
{
return ActionMatrix[Tuple.Create(currentVersion, action)];
}
A simple object with it's own list should do the trick and is visually better to follow.
public class VersionData
{
private static List<VersionData> VersionDatas { get; set; } = new List<VersionData>()
{
new VersionData( "OldversionToInstall", new [] {"windows10(pro)", "windows10(pro)(education)" }.ToList(), "windows81(pro)" ),
new VersionData( "OldversionToInstall", new [] {"windows10(enterprise)", "windows10(enterpise)(lstb)" }.ToList(), "windows81(enterprise)" )
};
public string Action { get; set; } = "";
public List<string> CurrentVersions { get; set; } = new List<string>();
public string Version { get; set; } = "";
public VersionData(string action, List<string> currentVersions, string version)
{
Action = action;
CurrentVersions = currentVersions;
Version = version;
}
public static string GetVersion(string action, string currentVersion)
{
return VersionDatas.FirstOrDefault(o => o.Action == action && o.CurrentVersions.Any(x => x == currentVersion)).Version;
}
}
and to call it's as simple as :
var oldVersion = VersionData.GetVersion("OldversionToInstall", "windows10(enterpise)(lstb)");

Enumeration Objects (Strings) in Entity Framework

I am building a model with Entity Framework and purchased responsive CSS.
The built in fixed icons comes with CSS. Like as follows (Name and Icon Class Value)
I need a way to keep the names of icons as fixed enums to access it from the VS intellisense. Currently we can't store as a entity table in entity framework (as it require relationship with tables difficult to maintain) and enum doesn't allows string type.
Code that did not work:
public sealed class IconType
{
public static readonly IconType Rupee_Icon = new IconType("rupee-icons");
public static readonly IconType Doller_Icon = new IconType("doller-icon");
private IconType(int EnumID,string EnumObjectValue)
{
IconValue = EnumObjectValue;
}
public string IconValue { get; private set; }
}
More code that did not work (CSS class names contains whitespaces like ui bell icon):
public enum Icon
{
NotSet=0,
Idea Icon=1,
Bell Icon =2
}
Is there any other ways to use names / objects as enums or constants in EF for easy intellisense in Visual Studio?
You could:
Omit the white spaces in the enums:
public enum Icon
{
NotSet = 0,
IdeaIcon = 1,
BellIcon = 2
}
Add a description or name (Or even some custom attribute) attributes to the enums:
public enum Icon
{
NotSet = 0,
[Description("ui idea icon")]
IdeaIcon = 1,
[Description("ui bell icon")]
BellIcon = 2
}
When needed get the description name. Example method to get the description attribute value:
public static string GetDescription<T>(this T enumerationValue)
where T : struct, IConvertible
{
var type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
// Tries to find a DescriptionAttribute for a potential friendly name for the enum
var memberInfo = type.GetMember(enumerationValue.ToString(CultureInfo.InvariantCulture));
if (memberInfo.Length > 0)
{
var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
// Pull out the description value
return ((DescriptionAttribute)attributes[0]).Description;
}
}
// If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString(CultureInfo.InvariantCulture);
}
Did you consider using string constants?
public static class IconType
{
public const string RUPEE_ICON = "rupee-icon";
public const string DOLLER_ICON = "doller-icon";
// ...
}
Store the icon's as plain old objects. Why make use of entity framework at all?
public static class Icons
{
public enum Type
{
IdeaIcon = 1,
BellIcon =2
}
public static Icon Get(Type type)
{
return IconCollection.Single(icon => icon.Type == type);
}
static IEnumerable<Icon> IconCollection
{
get
{
return new List<Icon>
{
new Icon(Type.IdeaIcon, "Idea Icon", "icon idea-icon"),
new Icon(Type.BellIcon, "Bell Icon", "icon bell-icon"),
};
}
}
public class Icon
{
public Icon(Type type, string description, string cssClass)
{
Type = type;
Description = description;
CssClass = cssClass;
}
public Type Type { get; private set; }
public string Description { get; private set; }
public string CssClass { get; private set; }
}
}
Use in code:
public class Class1
{
public void Method1()
{
var ideaIcon = Icons.Get(Icons.Type.IdeaIcon);
var x = ideaIcon.CssClass;
var y = ideaIcon.Description;
var bellIcon = Icons.Get(Icons.Type.BellIcon);
// etc...
}
}
Razor view:
#Icons.Get(Icons.Type.BellIcon).CssClass
If you needed to enumerate over the icon collection you could easily add another static accessor to the Icons class.

c# access child class from parent

I have two classes. Jewellery is base and Ring inherits from it.
class Jewellery
{
public string Name { get; set; }
......
public Jewellery(string name)
{
Name = name;
}
}
.
class Ring : Jewellery
{
public string Size { get; set; }
public Ring(string name, string size) :base(name)
{
Size = size
}
}
Now in main i created List of Jewellery and in that list i added Ring object.
Ring ring = new Ring("Diamond", "Very big");
List<Jewellery> jewellery = new List<Jewellery>();
jewellery.Add(ring);
Now when debugging i can access ring object from jewellery list. Can i do it from code? I think this should be done like this, but this doesn't work.
jewellery[0].Ring
You need to cast it, e.g.:
var myRing = (Ring)jewellery[0];
or
var maybeRing = jewellery[0] as Ring;
if (maybeRing != null)
{
// do stuff
}
or
if (jewellery[0] is Ring)
{
// Cast and do stuff
}
For multiple types you can
if (jewellery[0] is Ring)
{
// Cast and do stuff
}
else if(jewllery[0] is Necklace)
{
// and so on
}
See MSDN on safe casting.
Depending on what you want to do you can use Linq to filter by type:
Given:
List<Jewellery> things = new List<Jewllery>();
Then:
public IList<T> GetJewellery<T>(this jewellery) where T : Jewellery
{
return jewellery.OfType<T>().ToList();
}
Can:
IList<Necklace> necklaces = things.GetJewellery<Necklace>();
IList<Ring> rings = things.GetJewellery<Ring>();

Custom generic DTO Assembler

I'm trying to create a method which can be used like this:
Assembler.CreateTransfer(i);
i is an item inside a dynamic collection.
i is a domain object.
CreateTransfer() should return an instance of i type + Transfer (if my domain object is User, then it should return an instance of UserTransfer.
As for my models is like this:
public abstract class UserBase {
public long UserId { get; set; }
public string Username { get; set; }
}
public class UserTransfer : UserBase, ITransferObject { }
public partial class User : UserTransfer, IModelBase, IDomainObject {
public User() {
Roles = new List<Role>();
}
public virtual ICollection<Role> Roles { get; set; }
}
So far, I've accomplished this:
public static TTransfer CreateTransfer<TTransfer, TDomain>(TDomain d)
where TTransfer : ITransferObject
where TDomain : IDomainObject
{ ... }
This works, because I know the type of TTransfer and TDomain.
And I can call it like: CreateTransfer<UserTransfer, User>(d).
The problem comes when I try create the dto without specifying any type:
CreateTransfer(d);
Of course I've added an overload for this task and I hope I can magically accomplish the following:
public static ITransferObject CreateTransfer(IDomainObject d) {
// do magic
return CreateTransfer<transfer, domain>(d);
}
But in the real world, this is as far as I could get:
public static ITransferObject CreateTransfer(IDomainObject d) {
var dType = d.GetType();
var assemblyName = dType.Assembly.FullName;
var domainName = dType.FullName;
var transferName = domainName + "Transfer";
var domain = Activator.CreateInstance(assemblyName, domainName).UnWrap();
var transfer = Activator.CreateInstance(assemblyName, transferName).UnWrap();
return CreateTransfer< ?, ?>(d); // Problem
}
Both domain and transfer objects are being created correctly.
The main question is: Is there any way to be able to call CreateTransfer<domain, transfer>(d)? Any help will be appreciated.
You can use reflection to call the generic method.
Something like this:
var method = typeof(ClassThatDefinesCreateTransfer)
.GetMethods()
.Single(x => x.Name == "CreateTransfer" &&
x.IsGenericMethodDefinition)
.MakeGenericMethod(dType, transferType);
return (ITransferObject )method.Invoke(null, new object[] { d });
You probably want to cache at least the result of typeof(ClassThatDefinesCreateTransfer).GetMethods().

Inheritance and Multiple Constructors

I have a question regarding inheritance, so I will describe the scenario below:
I am reading a text file containing logs. (One log per line)
Each log-line will have the following format:
"Date Type Description"
However, depending on the "Type" of log, I will have to parse the "Description" differently and pull out different fields.
Here are some examples:
5/1/2011 Information Field1, Field2, Field3
5/2/2011 Error Field1
--
So, what I tried to do was this:
-Get a line out of the log
-Parse it according to the pattern "Date Type Description"
-Look at the "Type" field, and create new objects/parse description as necessary
public class Log
{
public DateTime Date;
public String Type;
public String Description;
public Log(String line)
{
this.Date = GetDate();
this.Type = GetType();
this.Description = GetDescription();
}
}
public class InformationLog : Log
{
public String Field1;
public String Field2;
public String Field3;
public InformationLog(Log log)
{
this.Field1 = GetField1(log.Description);
this.Field1 = GetField2(log.Description);
this.Field1 = GetField3(log.Description);
}
}
public class Client
{
public void Main()
{
String line = ReadFileAndGetLine(); // Get a line from the file
Log log = new Log(line);
if(log.Type == "Information")
log = new InformationLog(log); // Is this right?
}
}
This works how I want it to, but it seems like this cannot be a good practice. The "log" variable is using itself as a parameter to its own constructor.
My question is:
Is there a standard way of doing this? Or, is there anything wrong with this implemenation?
--
Edit:
Also, I should mention: My reasoning was that I would parse the line once to get out the date and type, and then parse it again to get the finer details.
I decided to use inheritance so I wouldn't have to parse out the Date and Type fields twice.
Try to use Factory pattern
static class LogFactory
{
public static Log Create(String line)
{
if(GetType(line) == "Information")
return CreateInformationLog(line);
return CreateLog(line);
}
private static Log CreateLog(String line)
{
return new Log(line);
}
private static Log CreateInformationLog(String line)
{
return new InformationLog(line);
}
}
And then try to use
String line = ReadFileAndGetLine(); // Get a line from the file
Log log = LogFactory.Create(line);
As per my comment, why not just do something a little like this:
public enum LogEntryType
{
Error = -1,
Information = 0,
}
public class LogEntry
{
public string Raw;
public DateTime Date;
public LogEntryType Type;
public string Description;
public LogEntry(String line)
{
Raw = line;
Date = ParseDate();
Type = ParseType();
Description = ParseDescription();
}
public string ParseDescription()
{
var result = string.Empty;
switch(Type)
{
case LogEntryType.Error:
//parse here
break;
case LogEntryType.Information:
//parse here
break;
}
return result;
}
}
I notice you have fields in the derivative class, but the description could be parsed here; though, I can see why people may want to shift it to the place that actually knows how the description should be parsed, in which case you could use a factory pattern suggested in another answer, or implement a 'property bag' type scenario - but drifting away from strong typing is generally frowned upon these days, I reckon.
Another suggestion, though very similar to your initial attempt, tends to encapsulate management of the types, as opposed to having a detached class handle such stuff - a pattern a little (superficially) like Exception where you have a root entry and inner entries:
public enum LogEntryType
{
Error = -1,
Information = 0,
}
public class LogEntry
{
public string Raw;
public DateTime Date;
public LogEntryType Type;
public string Description;
public InnerLogEntry InnerEntry;
public LogEntry(String line)
{
Raw = line;
Date = ParseDate();
Type = ParseType();
//parse the 'raw' description...
Description = ParseDescription();
//determine the inner entry type...
switch (Type)
{
case LogEntryType.Error:
InnerEntry = new ErrorLogEntry(this);
break;
case LogEntryType.Information:
InnerEntry = new InformationLogEntry(this);
break;
}
}
}
public abstract class InnerLogEntry
{
protected LogEntry Parent;
public InnerLogEntry(LogEntry logEntry)
{
Parent = logEntry;
}
}
public class InformationLogEntry : InnerLogEntry
{
public InformationLogEntry(LogEntry logEntry)
: base(logEntry)
{
//parse custom data
}
}
public class ErrorLogEntry : InnerLogEntry
{
public ErrorLogEntry(LogEntry logEntry)
: base(logEntry)
{
//parse custom data
}
}

Categories