Card Reader Excel timetable - c#

I would like to prevent the looping and when i display the card. It should only display my name once and my friends name one. It is constant looping now.
This is what i have declared
int row = 2;
int count = 0;
int num = 0;
int name = 0;
bool=false;
if (CardReader.CANSnr.Equals("8009140003484246"))
{
scan = true;
textBox1.Text = "Welcome Back";
textBox2.Text = "Jonathan";
DateTime theDate = DateTime.Now;
string todaysDate = theDate.ToString("d");
string todaysTime = theDate.ToString("T");
//add Data to to cells
excell_app.addData(row, 1, "Jonathan", "A1", "A1", "#,##0");
excell_app.addData(row, 2, "1", "B1", "B1", "");
excell_app.addData(row, 3, todaysDate, "C1", "C1", "#,##0");
excell_app.addData(row, 4, todaysTime, "D1", "D1", "#,##0");
row++;
}

I don't think there's enough information here to answer your question. You don't have a loop in the provided code, so any perceived looping must be happening at a higher level.
Otherwise, it looks like you have a var (scan) that you could use to prevent multiple scans from happening, if that's what you're after.
...
bool scan = false;
if (!scan && CardReader.CANSnr.Equals("8009140003484246"))
{
scan = true;
...
}

Related

How to Implement a method that finds the largest value, given two arrays(String[], Float[])

I have two arrays both with 12 elements each. One is a string array with 4 different colors, and the rest being duplicate colors. The second array is a float array with 12 distinct values.
string[] fishColor = new string[] {"blue", "red", "green", "pink", "blue", "pink", "blue", "red", "green", "blue", "red", "green"};
float[] fishLength = new float[12] { 8.2f, 17.1f, 23.2f, 2.3f, 5.5f, 7.83f, 9.6f, 10.7f, 12.3f, 4.2f, 8.71f, 9.17f };
The goal is to create a method that will find the largest float value for a given color. For example, there are a total of 4 strings with the value of "blue", and each of these has a corresponding float value:
fishColor[0] = "Blue" would be paired with fishLength[0] = 8.2
fishColor[4] = "Blue" would be paired with fishLength[4] = 5.5
etc...
The method must be able to find the largest amongst the duplicates.
For context, I have a menu that lists the four different colors in the string array. The only user input in this program would be the menu option the user picks, so one of the colors.
bool fin = false;
Console.WriteLine("\r\nWelcome to BigBlueFish!\r\n\r\nPlease select a fish color below...");
do
{
Console.WriteLine("\r\n[1] Blue");
Console.WriteLine("\r\n[2] Red");
Console.WriteLine("\r\n[3] Green");
Console.WriteLine("\r\n[4] Pink");
Console.WriteLine("\r\n[0] Exit to main menu");
string strSelect = Console.ReadLine();
int numSelect;
try
{
numSelect = int.Parse(strSelect);
}
catch (FormatException)
{
Console.WriteLine("\r\nPlease select a menu option!");
continue;
}
Console.WriteLine("\r\nYou have selected {0}", numSelect);
switch (numSelect)
{
case 0:
Console.WriteLine("\r\nTill next time!");
fin = true;
break;
case 1:
var mdata1 = FindBiggestFish(fishColor, fishLength);
Console.WriteLine("\r\nWell now seems like you found the biggest blue fish is {0}in", mdata1);
break;
case 2:
var mdata2 = FindBiggestFish(fishColor, fishLength);
Console.WriteLine("\r\nWell now seems like you found the biggest red fish is {0}in", mdata2);
break;
case 3:
var mdata3 = FindBiggestFish(fishColor, fishLength);
Console.WriteLine("\r\nWell now seems like you found the biggest green fish is {0}in", mdata3);
break;
case 4:
var mdata4 = FindBiggestFish(fishColor, fishLength);
Console.WriteLine("\r\nWell now seems like you found the biggest pink fish is {0}in", mdata4);
break;
}
} while (!fin);
}
public static float FindBiggestFish(string[] col, float[] len)
{
float bgstCol = 0;
var colAndLen = col.Zip(len, (c, l) => new { color = c, length = l });
foreach(var cl in colAndLen)
{
if (cl.color.Distinct().Count() != cl.color.Count())
{
rptCol = cl.color;
bgstCol = cl.length;
}
}
return bgstCol;
}
The user selects an option from the menu and the method is applied the result should look like this:
Selection was 1
Whoa, looks like the biggest blue fish is 9.6 inches
The method would see that there are 4 instances of "blue" fish and locate that the largest one of the 4 is 9.6.
All of that to ask, how would I correctly implement this as a method? I ended up trying to go the LINQ route so as to pair the two arrays together and iterate through them with a foreach, but I'm not really sure what I'm doing. Any insight on how to implement this would be much appreciated. If ya couldn't tell already I'm newer to programming so bear with me, you have my thanks.
You can try Zip in order to create color / length pairs
var result = fishColor
.Zip(fishLength, (c, l) => new {c, l})
.Where(item => item.c == givenColor)
.Max(item => item.l);
Loop over all entries and store the maximum per color:
var max_values = new Dictionary<string,double>();
for( int i=0; i<fishColor.Length; i++)
{
var clr = fishColor[i];
var len = fishLength[i];
if (! max_values.ContainsKey( clr ) )
{
max_values.Add( clr , len );
continue;
}
if (max_values[ clr ] < len )
max_values[ clr ] = len;
}
You can populate Dictionary with the required pair of values using the below code.
string[] fishColor = new string[] { "blue", "red", "green", "pink", "blue", "pink", "blue", "red", "green", "blue", "red", "green" };
float[] fishLength = new float[12] { 8.2f, 17.1f, 23.2f, 2.3f, 5.5f, 7.83f, 9.6f, 10.7f, 12.3f, 4.2f, 8.71f, 9.17f };
var dictFish = new Dictionary<string, float>();
int index = 0;
fishColor.ToList().ForEach(s =>
{
if (!dictFish.ContainsKey(s))
dictFish.Add(s, fishLength[index]);
else
{
if (dictFish[s] < fishLength[index])
dictFish[s] = fishLength[index];
}
index++;
});
You could do the following.
var lookupTable = fishColor.Zip(fishLength,(x,y)=>new {color=x,value=y}).ToLookup(x=>x.color);
var result = lookupTable[colorToSearch].Max(c=>c.value);
The ToLookup is immediately executed unlike GroupBy (which are differed executions). So if you intended to use the same collection for lookup for highest value of different color multiple times, it might be better you do the ToLookup once, and then search against it.

C# Xamarin.forms ListView population listview with list<string>

I am trying to parse a string of events into a list EventsList, then populate the fields in my listview (title, location, time, and date) with the correct strings from EventList.
The problem I have run into now is that the method used to populate EventsList is returning something that is no where to be found in my string. The string displayed from EventsList is:
System.Collections.GenericList'1[System.String]
If anyone could help me figure out why it is returning that it would be much appreciated - or if there is a better strategy to do this please enlighten me.
List<string> EventsList = new List<string>();
EventsList = EventDetails(EventsList);
List<string> EventDetails(List<string> arEvents)
{
int indexNum = 67;
string events = GetEvents();
//while (indexNum <= 78)
//{
int index1 = (events.IndexOf(indexNum.ToString())) + 2;
int commaIndex = events.IndexOf(",");
if ((commaIndex - index1) <= 0)
{
string Title = events.Substring(index1, 10);
indexNum++;
}
else
indexNum++;
// }
Title = events.Substring(index1, 10);
arEvents.Add(Title);
return arEvents;
}
MainListView.ItemsSource = new List<APBEvent>
{
new APBEvent()
{
EventTitle = GetEvents(),
EventLocation = "line break",
EventTime = EventsList.ToString(),
EventDate = "5/11/18",
},
};
EventsList.ToString()
EventList is list<string> and you can not convert list to string.
If you want to convert list<string> contents to string then you can join the contents by using string.join
string.join(",",EventList);

Isolate characters from string

So I have a string called today with the value "nick_george_james"
it looks like this
string today = "_nick__george__james_";
how can i isolate the text between the '_' into a new string? i want to get the 3 names into seperate strings so that in the end i have name1, name2, name3 with the values nick, george and james
my application is written in c#
use string.Split
string[] array = today.Split('_');
After editing your question, I realized that you have multiple _ in your string. You should try the following.
string[] array = today.Split("_".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Or
string[] array = today.Split(new []{"_"}, StringSplitOptions.RemoveEmptyEntries);
Later your array will contain:
array[0] = "nick";
array[1] = "george";
array[2] = "james";
string[] array = today.Split('_');
name1=array[0];
name2=array[1];
name3=array[2];
Thought of coming up with an idea other than string.Split.
string today = "_nick__george__james_";
//Change value nNoofwordstobeFound accordingly
int nNoofwordstobeFound = 3;
int nstartindex = 0;
int nEndindex = 0;
int i=1;
while (i <= nNoofwordstobeFound)
{
Skip:
nstartindex = today.IndexOf("_",nEndindex);
nEndindex = today.IndexOf("_", nstartindex + 1);
string sName = today.Substring(nstartindex + 1, nEndindex - (nstartindex + 1));
if (sName == "")
{
goto Skip;
}
else
{
//Do your code
//For example
string abc= sName;
}
i++;
}
I'd still prefer string.split method over this anytime.
string[] nameArray = today.Split('_');
Here you will get a array of names. You can get each name from by specifying index positions of the nameArray.
ie Now the the nameArray contains values as below
nameArray[0] = "nick", nameArray[1] = "george", nameArray[2] = "james"

Assigning a button tag based on random items from an array

{
var buttonnameString = new List<string> { "button1", ... , "button12" };
for(int i = 0; i < 12; i++)
{
// Random car assignment to button
Random myRandom = new Random();
var carString = new List<string> { "Camaro", ... , "Model T" };
int index = myRandom.Next(carString.Count);
var name = carString[index];
carString.RemoveAt(index);
Tag = name.ToString();
}
}
In advance, thank you for any help that is provided. I'm a first year C# student so I know I have a lot to learn, but I've exhausted the extent of my google skills on trying to get this to work.
What I'm trying to do, is make a matching program. This program will have 12 buttons, labeled "button1", "button2"....etc. When the button is clicked, it will display it's tag, which is provided from a random array. I've gotten the random feature to work on assigning only a single buttons tag. Where I'm hung up at, is repeating this to all the buttons in a groupbox. I've tried the foreach venue, but couldn't get it to work successfully. Eventually I tried other methods as well. Below is where I've stopped at as I'm unsure on where to go. The two major questions that I have are
How do I assign the random string to a wildcard button tag?
What is the best way to accomplish randomly assigning 12 car names, to 12 buttons? The use of two arrays?
Try this:
{
var numOfButtons = 12;
var matchingButtonIndex = 0;
// Random car assignment to button
Random myRandom = new Random();
var buttons = new List<Button> { button1, ... , button12 };
var carString = new List<string> { "Camaro", ... , "Model T" };
while (matchingButtonIndex < numOfButtons)
{
int index = myRandom.Next(carString.Count);
var name = carString[index];
if (name != null)
{
buttons[matchingButtonIndex].Tag = name;
carString[index] = null;
matchingButtonIndex = matchingButtonIndex + 1;
}
}
}
Notice I have changed the button names array to an array of buttons. I have also emptied out the carString as I find unused car names.
Iterating over buttons is easy when you iterate through the form's Controls
var carString = new List<string> { "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T", "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T" };
foreach(Control c in Controls)
{
if (c is Button)
{
Random myRandom = new Random();
int index = myRandom.Next(carString.Count);
c.Tag = carString[index];
}
}

Multiple Formats in one cell using c#

I want to have mutple format types in one cell in my workbook. For example I want my A1 cell to display " Name: Aaron Kruger ". When I programmatically add the name "Aaron Kruger" to the template, it automatically makes it bold. So instead it looks like this " Name:Aaron Kruger ". So I want Bold and non-bold both in the same cell. And maybe in the future I will want two different text sizes in the same cell.
Thanks,
Aaron Kruger
Here is the function I created:
public void inputData(int row, int column, string cellName, System.Windows.Forms.TextBox textBox, Excel.Worksheet sheet)
{
sheet.Cells[row, column] = sheet.get_Range(cellName, Type.Missing).Text + " " + textBox.Text; // adds value to sheet
}
Here are the arguments I pass in:
inputData(5, 1, "A5", tbTagNumber, xlSheet);
inputData(6, 1, "A6", tbCustomer, xlSheet);
inputData(7, 1, "A5", tbDataFile, xlSheet);
inputData(3, 6, "F3", tbJobNumber, xlSheet);
inputData(4, 6, "F4", tbMeterSN, xlSheet);
inputData(6, 6, "F6", tbPO, xlSheet);
inputData(7, 6, "F7", tbFlowplate, xlSheet);
inputData(4, 9, "I4", tbElectronicSN, xlSheet);
Range rng1 = ws.getRange("A1","E10");
for(int i=0;i<10;i++)
{
Range rngTst=rng.cells[i,i];
for(int j=0;j<rngTst.get_characters().count;j++)
{
rngTst.application.activecell.get_characters(j,j).font.color
}
}
or
int sFirstFoundAddress = currentFind.FormulaR1C1Local.ToString().IndexOf("NOT FOR CIRCULATION ");
get_Range(excel.Cells[1, 1],
excel.Cells[1, dtData.Columns.Count])
.get_Characters(sFirstFoundAddress, 20).Font.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
Use Microsoft.Office.Interop.Excel.Range which gives you each character as Characters type. Now use its Font and other properties to style them.
Refer an example here: http://www.bloodforge.com/post/Extract-Formatted-Text-From-Excel-Cell-With-C.aspx
Microsoft.Office.Interop.Excel.Range Range = (Microsoft.Office.Interop.Excel.Range)Cell;
int TextLength = Range.Text.ToString().Length;
for (int CharCount = 1; CharCount <= TextLength; CharCount++)
{
Microsoft.Office.Interop.Excel.Characters charToTest = Range.get_Characters(CharCount, 1);
bool IsBold = (bool)charToTest.Font.Bold;
bool IsItalic = (bool)charToTest.Font.Italic;
// other formatting tests here
}
I recorded a macro, it shouldn't be hard to translate it to C#:
ActiveCell.FormulaR1C1 = "Test test"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Test test"
With ActiveCell.Characters(Start:=1, Length:=5).Font
.Name = "Calibri"
.FontStyle = "Regular"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
With ActiveCell.Characters(Start:=6, Length:=4).Font
.Name = "Calibri"
.FontStyle = "Bold"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With

Categories