C# Chart - data is repeated - c#

I have the following Data (from the database):
These are stored in objects that are stored in a list:
for creating the chart series i have created the following function:
public void CreateSeries(DateTime seriesTime)
{
while (true)
{
if (seriesTime.Date > _stopDate.Date) return;
foreach (var data in _datalist)
{
var currentData = (Email)data;
String xLabel;
switch (_timeType)
{
case DateUtils.TimeType.Weeks:
xLabel = seriesTime.Date.ToString("dd");
break;
case DateUtils.TimeType.Months:
xLabel = seriesTime.Date.ToString("MM");
break;
case DateUtils.TimeType.Years:
xLabel = seriesTime.Date.ToString("yyyy");
break;
default:
xLabel = seriesTime.Date.ToString("dd");
break;
}
AddData(currentData, xLabel);
}
if (DateConverter.GetDaysBetween(seriesTime, _stopDate) >= 0)
{
seriesTime = AppendDays(seriesTime);
continue;
}
break;
}
}
protected DateTime AppendDays(DateTime initialDateTime)
{
switch (_timeType)
{
case DateUtils.TimeType.Weeks:
initialDateTime = initialDateTime.AddDays(7);
break;
case DateUtils.TimeType.Months:
initialDateTime = initialDateTime.AddMonths(1);
break;
case DateUtils.TimeType.Years:
initialDateTime = initialDateTime.AddYears(1);
break;
default:
initialDateTime = initialDateTime.AddDays(1);
break;
}
return initialDateTime;
}
All of which executes without any issues.
Then when the series have been added i use the following loop in my Form class:
List<Series> chart = ((EmailModel)_controller.GetFactory().GetModel("Email")).GetEmailChart(from, to, current_timetype);
test_chart.Series.Clear();
foreach (Series s in chart)
{
test_chart.Series.Add(s);
}
Which produces the following chart:
if you look closely then you will see that it has repeated the data 7 times.
i just don't know what the issue is.
Can anyone tell me what i am doing wrong?
Please tell me if you need more info or code i will check back every often and update my question.

As i see the partern you repeat 7 times 7 column.
You have to add 1 serie.
Try:
test_chart.Series.Add(s);
Whitout the foreach!

Related

Why is it only returning the first characteristic for BLE service?

I have a scan for peripherals going for 60 seconds, in which I take the scanResult and put them in a listView adapter. Each item in listView has a button, onButtonClick, I am trying to read a list of characteristics from a service inside the adapter.
button1.Click += (object sender, EventArgs e) =>
{
string sensorId = (string)((Button)sender).Tag;
int index = Sensors.FindIndex(x => x.SensorId == sensorId);
Sensor currentSensor = Sensors[index];
if (currentSensor.SensorId != null)
{
BluetoothManager manager = (BluetoothManager)context.GetSystemService(Context.BluetoothService);
BluetoothAdapter adapter = manager.Adapter;
BluetoothDevice device = adapter.GetRemoteDevice(currentSensor.SensorId);
gattCallback.ServicesDiscoveredEvent += GattCallback_ServicesDiscoveredEventAsync;
gattCallback.CharacteristicReadEvent += GattCallback_CharacteristicReadEvent;
}
});
private void GattCallback_ServicesDiscoveredEventAsync(BluetoothGatt gatt)
{
service = gatt.GetService(Java.Util.UUID.FromString("0000180a-0000-1000-8000-00805f9b34fb"));
foreach (var c in service.Characteristics)
{
gatt.ReadCharacteristic(c);
}
}
private void GattCallback_CharacteristicReadEvent(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status)
{
switch (status)
{
case GattStatus.ConnectionCongested:
break;
case GattStatus.Failure:
break;
case GattStatus.InsufficientAuthentication:
break;
case GattStatus.InsufficientEncryption:
break;
case GattStatus.InvalidAttributeLength:
break;
case GattStatus.InvalidOffset:
break;
case GattStatus.ReadNotPermitted:
break;
case GattStatus.RequestNotSupported:
break;
case GattStatus.Success:
var val = BitConverter.ToString(characteristic.GetValue()).Replace("-", "");
Console.WriteLine("CHAR VAL : " + val);
break;
case GattStatus.WriteNotPermitted:
break;
default:
break;
}
}
With the following code above, I am only seeing the result of the first characteristic in the list. What am I doing wrong?
You are only allowed to have one outstanding GATT transaction per BluetoothGatt object. You can't just issue read requests for every characteristic in a foreach loop like that. Please wait for one read to complete before you execute the next request.

How can I optimize this code for better readability?

I'm not a good programmer, for my bodypart-based collision detection in a game in unity I'm making I've ended up with a switch that looks like this despite my best attempts to simplify and shorten it:
public void GetCollision(Collision2D col) {
if (attackType == -1) {
if (col.gameObject.name == "Sword") {
hitboxDisable();
} else if (col.gameObject.name == "Player") {
pim.PlayerDamage(5);
}
}
if (col.gameObject.name == "Player_Body") {
switch (attackType) {
case -2: {
pim.PlayerDamage(5);
}
break;
case 0:
if (!pa.playerIsDodging) {
pim.PlayerDamage(5);
} else {
pa.dodgeOnCooldown = false;
pa.resetDodgeRoutine();
hitboxDisable();
}
break;
case 1:
if (!swordSrc.isDefendingLegRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 2:
if (!swordSrc.isDefendingArmRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 3:
if (!swordSrc.isDefendingHeadRight) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 4:
if (!swordSrc.isDefendingLegLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 5:
if (!swordSrc.isDefendingArmLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
case 6:
if (!swordSrc.isDefendingHeadLeft) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
break;
}
if (weaponBlocked == true) {
hitboxDisable();
RandomOpening();
ApplyForce(testvar1, testvar2);
weaponBlocked = false;
}
}
}
How can this be shortened and optimized for better readability? I'm new to C# and what little of my programming has been in C, I know there are a lot of ways to improve readability in C# I just don't know when/how to apply them. Suggestions would be much appreciated, I'm willing to try and learn anything, I want to try and avoid ending up with big switch statements like this if possible. Even just a suggestion what to apply here would be really appreciated, an example would be great.
I made the attackTypes into integers, they could have been strings but I chose not to because to my understanding strings take longer to compare. The attackType value specifies in the switch where the attack is targeting and if/how to block it, then if it was blocked.
Case 1-6 seem very similar. You can make use of a local function
public void GetCollision(Collision2D col) {
// this is a local function which you can only use inside this function
// which can be useful if you have a short repeating pattern inside the function
// and don't need it anywhere else
void _handleHit(bool isDefending) {
if (isDefending) {
pim.PlayerDamage(5);
} else {
weaponBlocked = true;
}
}
[...] // your code
switch (attackType) {
[...] // your code
case 1: _handleHit(!swordSrc.isDefendingLegRight); break;
case 2: _handleHit(!swordSrc.isDefendingArmRight); break;
case 3: _handleHit(!swordSrc.isDefendingHeadRight); break;
...
}
}
You could also take a look at C# enums and replace attackType with a readable version.
// Declaring the enum
public enum AttackType { Direct, LeftArm, ... }
// Then in a switch case you can do:
switch (attackType) {
case AttackType.Direct: ...
case AttackType.LeftArm: ...
}
One thing would be to create a enum to describe the bodyparts, i.e.
public enum Bodypart{
None,
Head,
LeftArm,
RightArm,
LeftLeg,
RightLeg,
}
This could allow you to replace all the isDefendingArmLeft properties with a DefendingBodyPart. Likewise your attacks could be described by a combination of attack type and bodypart, this also removes the need to guess what attackType = -2 means:
public enum Attacktype{
Magic,
Sword,
Bodypart,
}
So that you can check first if the attacker attacks a specific body-part, and if the target is defending that specific body-part. If you want to allow defense or attack of multiple bodyparts you could use a [Flags] enum with one bit per bodypart.

How do you execute a method only if another one has been run?

I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.
//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
string title2 = "text";
int choice2 = menu(menuChoice2, title2);
switch (choice2)
{
case 0:
hotelRoom();
break;
case 1:
diningHall();
break;
}
Many lines of code later...
public static void save()
{
Console.Clear();
string[] menuChoice = {"Chapter 2", "Back to start"};
string title = "text";
int choice = menu(menuChoice, title);
switch (val)
{
case 0:
if (hotelRoom = true) //this if-statement does not work
{
withoutCross();
}
else if (diningHall = true)
{
withCross();
}
break;
case 1:
Main(new string[] { });
break;
}
}
When I understand your title of the question correctly, then this is a solution:
Make the return type of the method bool and fill it to a variable.
bool isMethodExecuted = MyMethod();
Later you can check with a if-Statement, if the method is executed:
if(isMethodExecuted)
MyOtherMethod();

Faster way to compare enums?

I'm looking for a better way to compare enums. Currently, I have an enum with 3 different possible values:
public enum Elements { fire, water, earth };
However, an example of a function where something happens when two Elements collide:
Public Void ElementCollisionExample(Elements element1, Elements element2){
if (element1 == Elements.fire){
if (element2 == Elements.fire){
//Do stuff
} else if (element2 == Elements.water){
// Do stuff
} else {
// Do stuff
}
} else if (element2 == Elements.water){...etc...}
}
And that is only for the Fire Element!
I've searched a while, and looked on similar SO questions, but I'm not sure how to formulate the problem. All I've found are questions such as "Is '==' or '.Equals()' faster to compare Enums???", which is entirely different.
Is there an easy way to do this? I already have these conditions being handled in a separate Manager, but it still irritates me.
EDIT:
A combination of elements always has the same outcome. So Fire + Water = X, and Water + Fire = X as well.
It will be cleaner code with C# switch conditions introduced in C# 7.0.
public void ElementCollisionExample(Elements element1, Elements element2)
{
// Do nothing on equal elements
if (element1 == element2) return;
switch (element1)
{
case Elements.fire when element2 == Elements.water:
case Elements.water when element2 == Elements.fire:
// Do stuff
break;
case Elements.fire when element2 == Elements.earth:
case Elements.earth when element2 == Elements.fire:
// Do stuff
break;
case Elements.water when element2 == Elements.earth:
case Elements.earth when element2 == Elements.water:
// Do stuff
break;
}
}
Updated: Order of element1 and element2 does not matter. Also ignoring equal elements.
One option is to have a dictionary of actions you can invoke. For example:
public class ElementActionFactory
{
// Somewhere to keep our actions, using tuple to pair up elements
private Dictionary<(Elements, Elements), Action> _elementActions;
public ElementActionFactory()
{
// Initialise the action dictionary
_elementActions = new Dictionary<(Elements, Elements), Action>
{
{(Elements.Fire, Elements.Fire), FireAndFire},
{(Elements.Fire, Elements.Water), FireAndWater},
{(Elements.Fire, Elements.Earth), FireAndEarth},
// etc.
};
}
public void Invoke(Elements element1, Elements element2)
{
// Try to get the action, and if we don't find it...
if (!_elementActions.TryGetValue((element1, element2), out var action))
{
// reverse the arguments and try again - this assumes the order is not important
if (!_elementActions.TryGetValue((element2, element1), out action))
{
return; //No action was found
}
}
// Actually run the method now
action.Invoke();
}
public void FireAndFire()
{
Console.WriteLine("Fire And Fire");
}
public void FireAndWater()
{
Console.WriteLine("Fire And Water");
}
public void FireAndEarth()
{
Console.WriteLine("Fire And Earth");
}
}
And to use it, it's simply:
var elementActionFactory = new ElementActionFactory();
var element1 = Elements.Fire;
var element2 = Elements.Water;
elementActionFactory.Invoke(element1, element2);
Assuming that the order in which the elements are combined does not matter, you could treat the enumeration as a bit field, that is, a set of flags - so you can combine them allowing you to have a simple switch. For example:
[Flags]
public enum Elements
{
none = 0b0000_0000_0000,
fire = 0b0000_0000_0001,
water = 0b0000_0000_0010,
earth = 0b0000_0000_0100
};
public void ElementCollisionExample(Elements element1, Elements element2)
{
switch (element1 | element2)
{
case Elements.fire | Elements.water:
Console.WriteLine("The fire is extinguished");
break;
case Elements.earth | Elements.fire:
Console.WriteLine("The earth goes black");
break;
}
}
For Cleaner Code i suggest using complex switch ...
Elements x, y;
switch (x)
{
case Elements.fire:
switch (y)
{
case Elements.fire:
break;
case Elements.water:
break;
case Elements.earth:
break;
}
break;
case Elements.water:
switch (y)
{
case Elements.fire:
break;
case Elements.water:
break;
case Elements.earth:
break;
}
break;
case Elements.earth:
switch (y)
{
case Elements.fire:
break;
case Elements.water:
break;
case Elements.earth:
break;
}
break;
}
With tuples, you can avoid the nested ifs:
public void ElementCollisionExample(Elements element1, Elements element2)
{
Tuple<Elements,Elements> elements = Tuple.Create(element1,element2);
if(elements.Equals(Tuple.Create(Elements.fire, Elements.earth))
{
//do something
}
else if(elements.Equals(Tuple.Create(Elements.fire, Elements.water))
{
// do something
}
// and so on
}
You can simplify it more if you create a separate function:
public void ElementCollisionExample(Elements element1, Elements element2)
{
Tuple<Elements,Elements> elements = Tuple.Create(element1,element2);
if(CompareElements(elements, Elements.fire, Elements.earth))
{
//do something
}
else if(CompareElements(elements, Elements.fire, Elements.water))
{
// do something
}
// and so on
}
private bool CompareElements(Tuple<Elements,Elements> actual, Elements expected1, Elements expected2)
{
return actual.Equals(Tuple.Create(expected1, expected2));
}

How to store outcome of switch statement into an object in c#

Is it possible to create an object that stores the outcome of the switch statement in c#? Because my end goal is to compare the object in an if statement, and if that's true then it will print a writeline.
switch (results)
{
case 1:
checkingWriter.WriteLine("text");
break;
case 0:
checkingWriter.WriteLine("text");
error_Found = true;
break;
case -1:
checkingWriter.WriteLine("text");
error_Found = true;
break;
case -2:
checkingWriter.WriteLine("text");
error_Found = true;
break;
case -3:
checkingWriter.WriteLine("text");
error_Found = true;
break;
}
You are mixing both side effects and the computation of a value; this is a bad code smell and you might consider separating that logic.
To address your specific question: at this time there is no easy way to get a value computed by a particular switch case section out of the switch. However, this feature has been proposed for C# 8.0, so it seems likely that you'll get some version of this. See the link below for the proposal:
https://neelbhatt.com/2018/05/19/c-8-0-expected-features-part-iii-switch-statments/
Yes, something like (but very basic since we do not have any details):
var objectToCheck = ...; // Some initialized value or null
switch(...)
{
case ...:
objectToCheck = ...
break;
case ...:
objectToCheck = ...
break;
...
default:
Error handling
}
if (objectToCheck ==/.Equals(...) ) // Check object
create variable before switch statement begins, store the switch case result in variable. After switch ends, use the variable in the if condition.
var result = null;
switch (caseSwitch)
{
case 1:
result = fn1();
break;
case 2:
result = fn2();
break;
default:
Console.WriteLine("Default case");
break;
}
if(result == 'your condition')
do something
There are not enough details but may this works, or give you a new idea:
public class Foo
{
public static bool operator !=(Foo foo1, int results){
return results <= 0;
}
public static bool operator ==(Foo foo1, int results){
switch(results)
{
case 1:
Console.WriteLine("All gones good");
return false;
case 0:
Console.WriteLine("Nothing happend");
break;
case -1:
Console.WriteLine("Error 183");
break;
case -2:
Console.WriteLine("Fatal Error");
break;
case -3:
Console.WriteLine("The user doesn't exists");
break;
default:
return false;
}
return true;
}
}
And when you use it:
public static void Main()
{
Foo foo = new Foo();
int results = 0;
// makes some logic that fills results
if(foo == results){
Console.WriteLine("Do Something Custom Here");
}
results = -1;
if(foo == results){
Console.WriteLine("Do Another Something Custom Here");
}
}
It will give you in console something like this:
//Nothing happend
//Do Something Custom Here
//Error 183
//Do Another Something Custom Here

Categories