I want that when I click the button "List all Customers", the code should read the Customer.csv file and display the information on the form called "List All Customers".
How can I do that?
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
int count = 0;
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
Customer tempCust = new Customer();
tempCust.customerName = lineHolder[0];
tempCust.customerAddress = lineHolder[1];
tempCust.customerZip = Convert.ToInt32(lineHolder[2]);
myCustArray[count] = tempCust;
count++;
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
I'm not sure what kind of control you want to display this data in but your method could just return a list of Customer, then you can add to a ListBox, ListView or DataGrid
public static IEnumerable<Customer> LoadCustomers(string filename)
{
if (File.Exists(filename))
{
foreach (var line in File.ReadAllLines(filename).Where(l => l.Contains(',')))
{
var splitLine = line.Split(',');
if (splitLine.Count() >= 3)
{
yield return new Customer
{
customerName = splitLine[0].Trim(),
customerAddress = splitLine[1].Trim(),
customerZip = Convert.ToInt32(splitLine[2].Trim())
};
}
}
}
}
ListBox
listBox1.DisplayMember = "customerName";
listBox1.Items.AddRange(LoadCustomers(#"G:\Customers.csv").ToArray());
First, take advantage of the list object:
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
var retList = new List<Customer>();
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
retlist.add(new Customer(){
customerName = linerHolder[0],
customerAddress = lineHolder[1],
customerZip = Convert.ToInt32(lineHolder[2])
});
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
just wrap it up in a class, call if from the controller and populate up the results. Depending on how often you will be updating this data, you might look into caching it, so you don't have to run this process every X seconds for each user.
Related
I'm new to C# and i'm trying to check whether a guest has checked in on a hotel app. I'm trying to get all bookings in a text file pass them in to a list then read through the list looking for the booking in reference.
The problem i'm having is that it only seems to put the first line of the text file into the list. Could anyone help me solve this?
One way i've tried:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
break;
}
else
{
throw new Exception("BookingNotFoundException");
}
}
}
Another way i've also tried:
public void CheckBookingReference()
{
List<string> BookingList = new List<string>();
using (var sr = new StreamReader(BookingFilePath))
{
while (sr.Peek() >= 0)
BookingList.Add(sr.ReadLine());
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
//throw new Exception("GuestAlreadyCheckedInException");
Console.WriteLine("booking found");
break;
}
else if (_BookingReferenceNumber != BookingReferenceNumber)
{
Console.WriteLine("not found");
break;
}
}
}
}
With the code you have, if the first line doesn't match, you throw the exception.
Try this:
public void CheckBookingReference()
{
List<string> BookingList = File.ReadAllLines(BookingFilePath).ToList();
foreach (var BookingLine in BookingList.ToList())
{
string[] bookings = BookingLine.Split(',');
int _BookingReferenceNumber = int.Parse(bookings[5]);
if (_BookingReferenceNumber == BookingReferenceNumber)
{
Console.WriteLine("Booking found, check in complete.");
return;
}
}
throw new Exception("BookingNotFoundException");
}
I have a problem. I have 2 Android.Support.V4.App.Fragments
In the first Framgent I use this code:
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);
}
In the second Fragment I call this line:
dbValue = Fragment1.AgentSpinnerAdapter.GetItem(0);
But it says that AgentSpinnerAdapter is a nullreference, which is weird, because it get's filled. I have set the AgentSpinnerAdapter to Public static. Also in my MainActivity I first create Fragment1 and then Fragment2 like this:
Fragment1 = Fragment1.NewInstance();
Fragment2 = Fragment2.NewInstance();
What am I doing wrong?
UPDATE
Here is the full Fragment1.cs method
public void LoadAgentSpinner()
{
string json = "";
try
{
string html = string.Empty;
string url = "https://www.efy.nl/app/getagents.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
IgnoreBadCertificates();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
catch (Exception ex1)
{
try
{
WebClient client = new WebClient();
NameValueCollection fields = new NameValueCollection();
fields.Add("error", ex1.GetBaseException().ToString());
string url = "https://www.mywebsite.com";
IgnoreBadCertificates();
byte[] respBytes = client.UploadValues(url, fields);
string resp = client.Encoding.GetString(respBytes);
SelectedQuantity.Text = "";
SelectedLimit.Text = "";
}
catch (Exception ex2)
{
string exFullName = (ex2.GetType().FullName);
string ExceptionString = (ex2.GetBaseException().ToString());
}
}
//Parse json content
var jObject = JObject.Parse(json);
//Create Array from everything inside Node:"Coins"
var agentPropery = jObject["Agents"] as JArray;
//Create List to save Coin Data
agentList = new List<agent>();
//Find every value in Array: coinPropery
foreach (var property in agentPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<agent>>(property.ToString());
//Add all strings to List
agentList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = agentList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Owner, i.Exchange, i.Remark })
.Distinct()
.ToArray();
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark); // format your string here
}
if(MainActivity.db.CheckExistTableSettings("Default Agent") == true)
{
string Value = MainActivity.db.SelectValueFromTableSettings("Default Agent");
int spinnerPosition = AgentSpinnerAdapter.GetPosition(Value);
AgentSpinner.SetSelection(spinnerPosition);
}
else
{
AgentSpinner.SetSelection(0);
}
}
In a few of my applications it's necessary to access the other fragments from my main Activity, so we do the following:
public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener
{
public static Dictionary<string, Fragment> FragmentList { get; set; }
private Fragment currentFragment = null;
private BottomNavigationView navigation;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout_mainactivity);
// create our fragments and initialise them early.
if (FragmentList == null)
{
FragmentList = new Dictionary<string, Fragment>
{
{ "main", MainFragment.NewInstance() },
{ "bugreport", BugReportFragment.NewInstance() },
{ "settings", SettingsFragment.NewInstance() }
};
}
navigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_nav);
navigation.SetOnNavigationItemSelectedListener(this);
navigation.SelectedItemId = Resource.Id.navigation_main;
}
public bool OnNavigationItemSelected(IMenuItem item)
{
if (!popAction)
{
navigationResourceStack.Push(item.ItemId);
}
switch (item.ItemId)
{
case Resource.Id.navigation_main:
currentFragment = FragmentList["main"];
break;
case Resource.Id.navigation_settings:
currentFragment = FragmentList["settings"];
break;
case Resource.Id.navigation_bugreport:
currentFragment = FragmentList["bugreport"];
break;
}
if (currentFragment == null)
{
return false;
}
else
{
FragmentManager.BeginTransaction().Replace(Resource.Id.frame_content, currentFragment).Commit();
return true;
}
}
}
What this means is you could do something like MainActivity.FragmentList["main"] and then call any public method on the actual initialized class because a pointer to it is stored within the dictionary.
I have a problem.
In my Android app I use a: Android.Support.V4.View.ViewPager to swap between a summary and a wallet. The summary page is filled with 3 TextViews and the Wallet is created with 1 GridView. Both the pages are getting filled with data from a HTTPS call from where the response will be parsed into a List. Now I want to refresh both the pages every second. So I tried this:
public void LoadOrderPage()
{
Android.Support.V4.View.ViewPager SummaryWalletSwitcher = FindViewById<Android.Support.V4.View.ViewPager>(Resource.Id.SummaryWalletSwitcher);
List<View> viewlist = new List<View>();
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentSummary, null, false));
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentWallet, null, false));
SummaryWalletAdapter ViewSwitchAdapter = new SummaryWalletAdapter(viewlist);
SummaryWalletSwitcher.Adapter = ViewSwitchAdapter;
Timer AgentInfo_Timer = new Timer();
AgentInfo_Timer.Interval = 1000;
AgentInfo_Timer.Elapsed += LoadAgentInfo;
AgentInfo_Timer.Enabled = true;
}
public void LoadAgentInfo(object sender, ElapsedEventArgs e)
{
TextView TextPortfolioValue = FindViewById<TextView>(Resource.Id.txtPortfolioValue);
TextView TextValueUSDT = FindViewById<TextView>(Resource.Id.txtValueUSDT);
TextView TextTotalValue = FindViewById<TextView>(Resource.Id.txtTotalValue);
GridView GridviewWallet = FindViewById<GridView>(Resource.Id.GridviewWallet);
if (FirstWalletRun == true)
{
List<wallet> EmptyWalletList = new List<wallet>();
WalletListAdapter = new WalletListAdapter(this, EmptyWalletList);
GridviewWallet.Adapter = WalletListAdapter;
FirstWalletRun = false;
}
PortfolioValue = 0;
ValueUSDT = 0;
TotalValue = 0;
string response = "";
AgentId = getSelectedAgentId();
if (AgentId == 0)
{
AgentId = 1;
}
try
{
WebClient client = new WebClient();
var reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("agentid", AgentId.ToString());
reqparm.Add("devicetoken", DeviceToken);
byte[] responsebytes = client.UploadValues("https://www.test.nl/getagentwallet.php", "POST", reqparm);
IgnoreBadCertificates();
response = Encoding.UTF8.GetString(responsebytes);
response = response.Replace("\n", "").Replace("\t", "");
}
catch (Exception ex)
{
string exFullName = (ex.GetType().FullName);
string ExceptionString = (ex.GetBaseException().ToString());
TextPortfolioValue.Text = "Unknown";
TextValueUSDT.Text = "Unknown";
TextTotalValue.Text = "Unknown";
}
if (response != "No updates")
{
//Parse json content
var jObject = JObject.Parse(response);
//Create Array from everything inside Node:"Coins"
var walletPropery = jObject["Wallet"] as JArray;
//Create List to save Coin Data
walletList = new List<wallet>();
//Find every value in Array: coinPropery
foreach (var property in walletPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<wallet>>(property.ToString());
//Add all strings to List
walletList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = walletList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Coin, i.Quantity.ToString(), i.AvgPrice.ToString(), i.Value.ToString() })
.Distinct()
.ToArray();
foreach (string[] str in NamesArray)
{
if (str[1] != "USDT")
{
PortfolioValue += decimal.Parse(str[4]);
}
else
{
ValueUSDT += decimal.Parse(str[4]);
}
}
TotalValue = PortfolioValue + ValueUSDT;
TextPortfolioValue.Text = Math.Round(PortfolioValue, 8).ToString();
TextValueUSDT.Text = Math.Round(ValueUSDT, 8).ToString();
TextTotalValue.Text = Math.Round(TotalValue, 8).ToString();
SortedWalletList = walletList.OrderBy(o => o.Coin).ToList();
if (WalletListAdapter == null)
{
//Fill the DataSource of the ListView with the Array of Names
WalletListAdapter = new WalletListAdapter(this, SortedWalletList);
GridviewWallet.Adapter = WalletListAdapter;
}
else
{
WalletListAdapter.refresh(SortedWalletList);
AgentInfoNeedsUpdate = true;
}
}
else
{
AgentInfoNeedsUpdate = false;
}
}
And in my WalletListAdapter I created the refresh function:
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
But the GridviewWallet never get's filled or doesn't get shown. What am I doing wrong?
EDIT:
Maybe there is something wrong in the WalletListAdapter, so here is the code of the class:
public class WalletListAdapter : BaseAdapter<wallet>
{
public List<wallet> mItems;
private Context mContext;
public WalletListAdapter(Context context, List<wallet> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get { return mItems.Count; }
}
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
public override long GetItemId(int position)
{
return position;
}
public override wallet this[int position]
{
get { return mItems[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.walletlist_row, null, false);
var txtWalletCoin = row.FindViewById<TextView>(Resource.Id.txtWalletCoin);
var txtWalletQuantity = row.FindViewById<TextView>(Resource.Id.txtWalletQuantity);
var txtAvgPrice = row.FindViewById<TextView>(Resource.Id.txtWalletAvgPrice);
var txtWalletValue = row.FindViewById<TextView>(Resource.Id.txtWalletValue);
var txtProfitUSDT = row.FindViewById<TextView>(Resource.Id.txtWalletProfitUSDT);
var txtProfitPerc = row.FindViewById<TextView>(Resource.Id.txtWalletProfitPerc);
row.Tag = new WalletViewHolder()
{
txtWalletCoin = txtWalletCoin,
txtWalletQuantity = txtWalletQuantity,
txtAvgPrice = txtAvgPrice,
txtWalletValue = txtWalletValue,
txtProfitUSDT = txtProfitUSDT,
txtProfitPerc = txtProfitPerc
};
}
var holder = (WalletViewHolder)row.Tag;
holder.txtWalletCoin.Text = mItems[position].Coin;
holder.txtWalletQuantity.Text = Math.Round(mItems[position].Quantity, 2).ToString();
holder.txtAvgPrice.Text = Math.Round(mItems[position].AvgPrice, 2).ToString();
holder.txtWalletValue.Text = Math.Round(mItems[position].Value, 2).ToString();
if (mItems[position].Coin != "USDT")
{
holder.txtProfitUSDT.Text = Math.Round(mItems[position].ProfitUSDT, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(mItems[position].ProfitPerc, 1).ToString();
}
else
{
holder.txtProfitUSDT.Text = Math.Round(0.00, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(0.00, 1).ToString();
}
return row;
}
}
Hope this discussion provides some insights to fix the gridview refresh using Xamarin. According to it, the grid has to be recreated.
https://forums.xamarin.com/discussion/115256/refresh-a-gridview
I've got a List of Document
public class Document
{
public string[] fullFilePath;
public bool isPatch;
public string destPath;
public Document() { }
public Document(string[] fullFilePath, bool isPatch, string destPath)
{
this.fullFilePath = fullFilePath;
this.isPatch = isPatch;
this.destPath = destPath;
}
The fullFilepath should a List or an Array of Paths.
For example:
Document 1
---> C:\1.pdf
---> C:\2.pdf
Document 2
---> C:\1.pdf
---> C:\2.pdf
---> C:\3.pdf
etc.
My problem if I am using an array string all Documents got "null" in its fullFilePath.
If I'm using a List for the fullFilePath all Documents got the same entries from the last Document.
Here is how the List is filled:
int docCount = -1;
int i = 0;
List<Document> Documents = new List<Document>();
string[] sourceFiles = new string[1];
foreach (string file in filesCollected)
{
string bc;
string bcValue;
if (Settings.Default.barcodeEngine == "Leadtools")
{
bc = BarcodeReader.ReadBarcodeSymbology(file);
bcValue = "PatchCode";
}
else
{
bc = BarcodeReader.ReadBacrodes(file);
bcValue = "009";
}
if (bc == bcValue)
{
if(Documents.Count > 0)
{
Array.Clear(sourceFiles, 0, sourceFiles.Length);
Array.Resize<string>(ref sourceFiles, 1);
i = 0;
}
sourceFiles[i] = file ;
i++;
Array.Resize<string>(ref sourceFiles, i + 1);
Documents.Add(new Document(sourceFiles, true,""));
docCount++;
}
else
{
if (Documents.Count > 0)
{
sourceFiles[i] = file;
i++;
Array.Resize<string>(ref sourceFiles, i + 1);
Documents[docCount].fullFilePath = sourceFiles;
}
}
}
You are using the same instance of the array for every document. The instance is updated with a new list of files at every inner loop, but an array is a reference to an area of memory (oversimplification, I know but for the purpose of this answer is enough) and if you change the content of that area of memory you are changing it for every document.
You need to create a new instance of the source files for every new document you add to your documents list. Moreover, when you are not certain of the number of elements that you want to be included in the array, it is a lot better to use a generic List and remove all that code that handles the resizing of the array.
First change the class definition
public class Document
{
public List<string> fullFilePath;
public bool isPatch;
public string destPath;
public Document() { }
public Document(List<string> fullFilePath, bool isPatch, string destPath)
{
this.fullFilePath = fullFilePath;
this.isPatch = isPatch;
this.destPath = destPath;
}
}
And now change your inner loop to
foreach (string file in filesCollected)
{
string bc;
string bcValue;
....
if (bc == bcValue)
{
List<string> files = new List<string>();
files.Add(file);
Documents.Add(new Document(files, true, ""));
docCount++;
}
else
Documents[docCount].fullFilePath.Add(file);
}
Notice that when you need to add a new Document I build a new List<string>, add the current file and pass everything at the constructor (In reality this should be moved directly inside the constructor of the Document class). When you want to add just a new file you could add it directly to the public fullFilePath property
Moving the handling of the files inside the Documents class could be rewritten as
public class Document
{
public List<string> fullFilePath;
public bool isPatch;
public string destPath;
public Document()
{
// Every constructory initializes internally the List
fullFilePath = new List<string>();
}
public Document(string aFile, bool isPatch, string destPath)
{
// Every constructory initializes internally the List
fullFilePath = new List<string>();
this.fullFilePath.Add(aFile);
this.isPatch = isPatch;
this.destPath = destPath;
}
public void AddFile(string aFile)
{
this.fullFilePath.Add(aFile);
}
}
Of course, now in you calling code you pass only the new file or call AddFile without the need to check for the list initialization.
The issue should be here:
string[] sourceFiles = new string[1];
If you move this line of code in your foreach you should solve this problem because in your foreach you always use the same variable, so the same reference.
int docCount = -1;
int i = 0;
List<Document> Documents = new List<Document>();
foreach (string file in filesCollected)
{
string[] sourceFiles = new string[1];
string bc;
string bcValue;
if (Settings.Default.barcodeEngine == "Leadtools")
{
bc = BarcodeReader.ReadBarcodeSymbology(file);
bcValue = "PatchCode";
}
else
{
bc = BarcodeReader.ReadBacrodes(file);
bcValue = "009";
}
if (bc == bcValue)
{
if(Documents.Count > 0)
{
Array.Clear(sourceFiles, 0, sourceFiles.Length);
Array.Resize<string>(ref sourceFiles, 1);
i = 0;
}
sourceFiles[i] = file ;
i++;
Array.Resize<string>(ref sourceFiles, i + 1);
Documents.Add(new Document(sourceFiles, true,""));
docCount++;
}
else
{
if (Documents.Count > 0)
{
sourceFiles[i] = file;
i++;
Array.Resize<string>(ref sourceFiles, i + 1);
Documents[docCount].fullFilePath = sourceFiles;
}
}
}
I am trying to get events to occur one at a time within my button_Click, but for some reason everything seems to wait to run until everything is complete. For instance image changes don't occur until everything else has occured.
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Properties.Resources.running;
iTunesAppClass itunes = new iTunesAppClass();
IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
IITTrackCollection ittracks = mainLibrary.Tracks;
List<string> files = new List<string>();
List<string> musicfiles = new List<string>();
List<string> badfiles = new List<string>();
List<string> songlist = new List<string>();
int state = ((int)itunes.PlayerState);
string statestring = null;
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state == 1)
{
do
{
label5.Text = ("Pausing iTunes to maintain file integrity");
itunes.Pause();
state = (int)itunes.PlayerState;
}
while (state == 1);
}
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state != 1)
{
label5.Text = "Itunes is " + statestring;
}
string[] extensions = { "*.mp3", "*.mp4", "*.m4a", "*.m4v", "*.m4p", "*.m4b", "*.flac" };
string filepath = label4.Text;
foreach (string extension in extensions)
{
this.pictureBox1.Image = Properties.Resources.running;
try
{
files.AddRange(Directory.GetFiles(filepath, extension, SearchOption.AllDirectories));
}
catch (UnauthorizedAccessException) { }
}
foreach (string file in files)
{
try { string taglibfile = TagLib.File.Create(file).Tag.Title; musicfiles.Add(file); Console.WriteLine(taglibfile); }
catch { badfiles.Add(file); }
}
XDocument baddoc = new XDocument
(new XElement("Corrupt",
badfiles.Select(badfile =>
new XElement("File", badfile))));
baddoc.Save(label4.Text + "\\badfiles.xml");
// foreach(string musicfile in musicfiles)
//{ String Title = (TagLib.File.Create(musicfile).Tag.Title); }
this.pictureBox1.Image = Properties.Resources.skinitunes;
}