ViewModel Method Not Reloading View - c#

I have a problem with Xamarin.Forms whereby the View is not refreshing as I would expect it to.
I have bound a View to a ViewModel, and I have a series of methods to perform various functions.
On the successful completion of a function, I want it to execute my LoadResults() method.
The LoadResults() method works fine when I load the view initially. However, when I execute any other method (DeleteScan(id) method shown below) it should re-fire the LoadResults() method and reload the page.
I know it is entering the LoadResults() method as I've put a break point in there and stepped through it. But by the end of it, it doesn't reload the view.
I also know the view can refresh, as I have other simple methods which are simply updating properties in the VM and those changes are reflecting in the UI.
So for whatever reason, LoadResults() is not reloading the page.
Any ideas what I've done wrong here?
View Model Constructor and Properties
public class ResultsProcessViewModel : INotifyPropertyChanged
{
public ICommand AddTimingCommand { get; set; }
public ICommand AddScanCommand { get; set; }
public ICommand InsertTimingCommand { get; set; }
public ICommand InsertScanCommand { get; set; }
public ICommand DeleteTimingCommand { get; set; }
public ICommand DeleteScanCommand { get; set; }
public ICommand PublishCommand { get; set; }
public ICommand LoadResultsCommand { get; set; }
public ICommand CancelMissingFinisherCommand { get; set; }
public ICommand CancelMissingTimingCommand { get; set; }
public int RaceId { get; set; }
public DateTime RaceDate { get; set; }
//public ResultsViewModel(Race race)
public ResultsProcessViewModel(Race race)
{
AddTimingCommand = new Command<string>(AddTiming);
InsertTimingCommand = new Command(InsertTiming);
AddScanCommand = new Command<string>(AddScan);
InsertScanCommand = new Command(InsertScan);
DeleteTimingCommand = new Command<int>(DeleteTiming);
DeleteScanCommand = new Command<int>(DeleteScan);
PublishCommand = new Command(Publish);
LoadResultsCommand = new Command<int>(LoadResults);
CancelMissingFinisherCommand = new Command(CancelMissingFinisher);
CancelMissingTimingCommand = new Command(CancelMissingTiming);
Invalid = false;
PublishStatus = race.ResultStatus;
Published = false;
PublishVisibility = false;
AddTimingVisibility = false;
AddScanVisibility = false;
AddVisibility = true;
IsBusy = false;
RaceId = race.Id;
RaceDate = race.RaceDate;
RaceStartTime = Convert.ToDateTime(race.RaceStartTime);
Scans = ScansAPI.GetScans(RaceId);
Timings = TimingsAPI.GetTimings(RaceId);
Entries = EntriesAPI.GetEntries(RaceId);
LoadResults(RaceId);
}
ObservableCollection<GroupedResultModel> _grouped;
public ObservableCollection<GroupedResultModel> grouped
{
get { return _grouped; }
set
{
if (_grouped == value)
return;
_grouped = value;
OnPropertyChanged("Grouped");
}
}
DateTime _raceStartTime;
public DateTime RaceStartTime
{
get { return _raceStartTime; }
set
{
if (_raceStartTime == value)
return;
_raceStartTime = value;
OnPropertyChanged("RaceStartTime");
}
}
int _timingPosition;
public int TimingPosition
{
get { return _timingPosition; }
set
{
if (_timingPosition == value)
return;
_timingPosition = value;
OnPropertyChanged("TimingPosition");
}
}
int _addScanTimingId;
public int AddScanTimingId
{
get { return _addScanTimingId; }
set
{
if (_addScanTimingId == value)
return;
_addScanTimingId = value;
OnPropertyChanged("AddScanTimingId");
}
}
int _addTimingScanId;
public int AddTimingScanId
{
get { return _addTimingScanId; }
set
{
if (_addTimingScanId == value)
return;
_addTimingScanId = value;
OnPropertyChanged("AddTimingScanId");
}
}
int _scanPosition;
public int ScanPosition
{
get { return _scanPosition; }
set
{
if (_scanPosition == value)
return;
_scanPosition = value;
OnPropertyChanged("ScanPosition");
}
}
bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set
{
if (_isBusy == value)
return;
_isBusy = value;
OnPropertyChanged("IsBusy");
}
}
bool _published;
public bool Published
{
get { return _published; }
set
{
if (_published == value)
return;
_published = value;
OnPropertyChanged("Published");
}
}
bool _publishVisibility;
public bool PublishVisibility
{
get { return _publishVisibility; }
set
{
if (_publishVisibility == value)
return;
_publishVisibility = value;
OnPropertyChanged("PublishVisibility");
}
}
bool _error;
public bool Error
{
get { return _error; }
set
{
if (_error == value)
return;
_error = value;
OnPropertyChanged("Error");
}
}
bool _addVisibility;
public bool AddVisibility
{
get { return _addVisibility; }
set
{
if (_addVisibility == value)
return;
_addVisibility = value;
OnPropertyChanged("AddVisibility");
}
}
bool _addTimingVisibility;
public bool AddTimingVisibility
{
get { return _addTimingVisibility; }
set
{
if (_addTimingVisibility == value)
return;
_addTimingVisibility = value;
OnPropertyChanged("AddTimingVisibility");
}
}
bool _addScanVisibility;
public bool AddScanVisibility
{
get { return _addScanVisibility; }
set
{
if (_addScanVisibility == value)
return;
_addScanVisibility = value;
OnPropertyChanged("AddScanVisibility");
}
}
ObservableCollection<Result> _results;
public ObservableCollection<Result> Results
{
get
{
return _results;
}
set
{
if (_results != value)
{
_results = value;
OnPropertyChanged("Results");
}
}
}
ObservableCollection<Scan> _scans;
public ObservableCollection<Scan> Scans
{
get
{
return _scans;
}
set
{
if (_scans != value)
{
_scans = value;
OnPropertyChanged("Scans");
}
}
}
ObservableCollection<Timing> _timings;
public ObservableCollection<Timing> Timings
{
get
{
return _timings;
}
set
{
if (_timings != value)
{
_timings = value;
OnPropertyChanged("Timings");
}
}
}
ObservableCollection<RaceEntry> _entries;
public ObservableCollection<RaceEntry> Entries
{
get
{
return _entries;
}
set
{
if (_entries != value)
{
_entries = value;
OnPropertyChanged("Entries");
}
}
}
bool _invalid;
public bool Invalid
{
get { return _invalid; }
set
{
if (_invalid == value)
return;
_invalid = value;
OnPropertyChanged("Invalid");
}
}
bool _resultsInvalid;
public bool ResultsInvalid
{
get { return _resultsInvalid; }
set
{
if (_resultsInvalid == value)
return;
_resultsInvalid = value;
OnPropertyChanged("ResultsInvalid");
}
}
bool _insertScanVisibility;
public bool InsertScanVisibility
{
get { return _insertScanVisibility; }
set
{
if (_insertScanVisibility == value)
return;
_insertScanVisibility = value;
OnPropertyChanged("InsertScanVisibility");
}
}
string _validationError;
public string ValidationError
{
get { return _validationError; }
set
{
if (_validationError == value)
return;
_validationError = value;
OnPropertyChanged("ValidationError");
}
}
string _resultsValidationError;
public string ResultsValidationError
{
get { return _resultsValidationError; }
set
{
if (_resultsValidationError == value)
return;
_resultsValidationError = value;
OnPropertyChanged("ResultsValidationError");
}
}
string _missingBib;
public string MissingBib
{
get { return _missingBib; }
set
{
if (_missingBib == value)
return;
_missingBib = value;
OnPropertyChanged("MissingBib");
}
}
string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set
{
if (_errorMessage == value)
return;
_errorMessage = value;
OnPropertyChanged("ErrorMessage");
}
}
public Race SelectedRace { get; set; }
private bool _raceCountZero;
public bool RaceCountZero
{
get { return _raceCountZero; }
set
{
if (_raceCountZero == value)
return;
_raceCountZero = value;
OnPropertyChanged("RaceCountZero");
}
}
string _aboveBelow;
public string AboveBelow
{
get { return _aboveBelow; }
set
{
if (_aboveBelow == value)
return;
_aboveBelow = value;
OnPropertyChanged("AboveBelow");
}
}
string _aboveBelowPosition;
public string AboveBelowPosition
{
get { return _aboveBelowPosition; }
set
{
if (_aboveBelowPosition == value)
return;
_aboveBelowPosition = value;
OnPropertyChanged("AboveBelowPosition");
}
}
string _publishStatus;
public string PublishStatus
{
get { return _publishStatus; }
set
{
if (_publishStatus == value)
return;
_publishStatus = value;
OnPropertyChanged("PublishStatus");
}
}
string _newBatchCode;
public string NewBatchCode
{
get { return _newBatchCode; }
set
{
if (_newBatchCode == value)
return;
_newBatchCode = value;
OnPropertyChanged("NewBatchCode");
}
}
string _addHH;
public string AddHH
{
get { return _addHH; }
set
{
if (_addHH == value)
return;
_addHH = value;
OnPropertyChanged("AddHH");
}
}
string _addMM;
public string AddMM
{
get { return _addMM; }
set
{
if (_addMM == value)
return;
_addMM = value;
OnPropertyChanged("AddMM");
}
}
string _addSS;
public string AddSS
{
get { return _addSS; }
set
{
if (_addSS == value)
return;
_addSS = value;
OnPropertyChanged("AddSS");
}
}
string _scanBatchCode;
public string ScanBatchCode
{
get { return _scanBatchCode; }
set
{
if (_scanBatchCode == value)
return;
_scanBatchCode = value;
OnPropertyChanged("ScanBatchCode");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
DeleteScan method
void DeleteScan(int scanid)
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a scan whilst you are offline");
//We are good to go
else
{
var deletescan = ScansAPI.DeleteScan(scanid);
if (deletescan.Code != "NoContent")
throw new Exception("Error deleting scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
var newscans = ScansAPI.GetScans(RaceId);
var sortednewscans = new ObservableCollection<Scan>(newscans.OrderBy(c => c.Position));
Scans = sortednewscans;
Device.BeginInvokeOnMainThread(() => Published = false);
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => AddScanVisibility = false);
Device.BeginInvokeOnMainThread(() => IsBusy = false);
}
});
}
LoadResults Method
void LoadResults(int raceid)
{
var results = new ObservableCollection<Result>();
//Start with the timings
foreach (Timing timing in Timings)
{
var result = new Result();
//Basic details
result.RaceId = RaceId;
result.RaceDate = RaceDate;
result.Status = "Processing";
result.BackgroundColour = "White";
result.ScanTrashVisibility = true;
result.TimingTrashVisibility = true;
//Timing Data
result.TimingId = timing.Id;
result.TimingPosition = timing.Position;
result.TimingStatus = timing.Status;
result.StartTime = timing.StartTime;
result.EndTime = timing.EndTime;
result.TimingBatchCode = timing.BatchCode;
result.TimingBatchPosition = timing.BatchCode + timing.Position.ToString();
var elapsed = result.EndTime - result.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis;
if (elapsed.Milliseconds.ToString().Length > 2)
{
elapsedmillis = elapsed.Milliseconds.ToString().Substring(0, 2);
}
else
{
elapsedmillis = elapsed.Milliseconds.ToString();
}
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if((elapsedhours == "00"))
{
result.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
result.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(result);
}
//Add in the scans
foreach (Result result1 in results)
{
var scan = Scans.Where(p => p.BatchCode == result1.TimingBatchCode)
.FirstOrDefault(p => p.Position == result1.TimingPosition);
if (scan != null)
{
result1.ScanId = scan.Id;
result1.ScanPosition = scan.Position;
result1.ScanStatus = scan.Status;
result1.ScanBibNumber = scan.BibNumber;
result1.ScanBatchCode = scan.BatchCode;
result1.ScanBatchPosition = scan.BatchCode + scan.Position.ToString();
}
else
{
result1.ScanId = 0;
result1.ScanPosition = 0;
result1.ScanStatus = 99;
result1.ScanBibNumber = "UNKNOWN";
result1.AddScanButtonVisibility = true;
result1.ScanBatchCode = result1.TimingBatchCode;
}
}
//Add any scans which there are no times for
var notimescans = new ObservableCollection<Scan>();
foreach (Scan scan in Scans)
{
var checkscan = results.FirstOrDefault(s => s.ScanId == scan.Id);
if (checkscan == null)
{
var newresult = new Result();
newresult.RaceId = RaceId;
newresult.RaceDate = RaceDate;
newresult.Status = "Processing";
newresult.ScanId = scan.Id;
newresult.ScanPosition = scan.Position;
newresult.ScanStatus = scan.Status;
newresult.ScanBibNumber = scan.BibNumber;
newresult.ScanBatchCode = scan.BatchCode;
newresult.ScanBatchPosition = scan.BatchCode + scan.Position.ToString();
newresult.ScanTrashVisibility = true;
newresult.AddTimingButtonVisibility = true;
newresult.TimingId = 0;
newresult.TimingPosition = 99999;
newresult.TimingStatus = 99;
newresult.Elapsed = "N/A";
results.Add(newresult);
}
}
//Then add in the entries
foreach (Result result2 in results)
{
var entry = Entries.FirstOrDefault(p => p.BibNumber == result2.ScanBibNumber);
if (entry != null)
{
result2.EntryId = entry.Id;
result2.FirstName = entry.FirstName;
result2.LastName = entry.LastName;
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = entry.Gender;
result2.DateOfBirth = entry.DateOfBirth;
result2.Club = entry.Club;
result2.Team = entry.Team;
result2.EntryBibNumber = entry.BibNumber;
if (result2.Club == null)
{
result2.FormattedClub = "";
}
else
{
result2.FormattedClub = entry.Club.ToUpper();
}
}
else
{
result2.EntryId = 0;
result2.FirstName = "Unknown";
result2.LastName = "ATHLETE";
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = "Unknown";
result2.DateOfBirth = DateTime.Now;
result2.Club = "";
result2.Team = "";
result2.EntryBibNumber = result2.ScanBibNumber + " (Unrecognised)";
}
if(result2.ScanBatchCode == "NULLBATCH")
{
result2.ScanBatchCode = "Default";
}
if (result2.TimingBatchCode == "NULLBATCH")
{
result2.TimingBatchCode = "Default";
}
}
if(Scans.Count() != Timings.Count())
{
ResultsInvalid = true;
ResultsValidationError = "Your scan count and timing count's don't match. Please continue processing your results until these match and you will then be able to publish.";
}
else
{
Invalid = false;
PublishVisibility = true;
}
var sortedresults = new ObservableCollection<Result>(results.OrderBy(c => c.Elapsed));
int newposition = 1;
foreach (Result sortedresult in sortedresults)
{
sortedresult.OverallPosition = newposition;
newposition = newposition + 1;
}
//Create batches
grouped = new ObservableCollection<GroupedResultModel>();
foreach (Result result in results)
{
GroupedResultModel resultGroup = new GroupedResultModel();
var groupcheck = grouped.FirstOrDefault(b => b.BatchCode == result.ScanBatchCode);
if (groupcheck == null)
{
resultGroup.BatchCode = result.ScanBatchCode;
var BatchOfResults = results.Where(r => r.ScanBatchCode == resultGroup.BatchCode).OrderBy(r => r.Elapsed);
int batchposition = 1;
foreach (Result batchedresult in BatchOfResults)
{
batchedresult.OverallPosition = batchposition;
resultGroup.Add(batchedresult);
batchposition = batchposition + 1;
}
grouped.Add(resultGroup);
}
}
Results = sortedresults;
OnPropertyChanged("Invalid");
}

Related

Network Map with full detail and hierarchy

I wrote a piece of code to run from the first IP address to the last and retrieve the MAC and Hostname of devices in my network.
But, i do not know how to get the hierachy of then. Information like what router is the device conected (via Cable of WiFi also). And some routers are not managed (they don't have IP - they are just "switchs").
First, i didn't think it was possible, since a "tracert" on the CMD does not show then, but when i call the "Network Complete Map" on Windows Control Panel, they get all the information i need - so there is a way. See the image below:
The "switchs" circled in red have no IP, the "TL-xxxx" are routers with DHCP turned of. The "gateway" is a server that has the DHCP and provides connection to the internet.
Thus far, i wrote the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net;
using System.Runtime.InteropServices;
namespace Network
{
[Serializable] public sealed class Map
{
private bool mMARKED = true;
private long mDB = 0L;
private string mIP = string.Empty;
private string mMAC = string.Empty;
private string mBRAND = string.Empty;
private string mNAME = string.Empty;
public bool Save { get { return this.mMARKED; } set { this.mMARKED = value; } }
public long DBId { get { return this.mDB; } set { this.mDB = value; } }
public string IP { get { return this.mIP; } set { this.mIP = value; } }
public string MAC { get { return this.mMAC; } set { this.mMAC = value; } }
public string BRAND { get { return this.mBRAND; } set { this.mBRAND = value; } }
public string NAME { get { return this.mNAME; } set { this.mNAME = value; } }
}
[Serializable] public sealed class Scanner
{
public const string WebOUIFile = "http://standards-oui.ieee.org/oui.txt";
public const string LocalOUIFileName = "oui.txt";
private const long MaxOUIAge = (TimeSpan.TicksPerDay * 90L);
internal Dictionary<string, string> OUIList;
private List<Map> mDevices = new List<Map>(50);
public List<Map> Devices { get { return this.mDevices; } }
public static Scanner Scan;
public Thread Worker;
public bool AutoSave { get; set; }
private string Node;
private byte mInitial;
public static string UploadPath { get; set; }
public byte Initial { get { return this.mInitial; } set { this.mInitial = value; } }
public byte Current { get; private set; }
public byte Limit { get; set; }
public bool Working { get; private set; }
public string Errors;
public string Message { get; private set; }
public bool UpdatingOUI { get; private set; }
public void Interrupt()
{
this.Working = false;
if (this.Worker != null)
{
this.Worker.Abort();
this.Worker = null;
}
this.Node = string.Empty;
this.Initial = 0;
this.Current = 0;
this.Limit = 0;
this.Working = false;
}
public void ToDestroy()
{
this.Interrupt();
this.Errors = string.Empty;
this.Message = string.Empty;
}
public void Stop(bool immediate) { if (immediate) { this.Interrupt(); } }
[DllImport("iphlpapi.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int SendARP(int DestIP, int SrcIP, out long pMacAddr, ref int PhyAddrLen);
public void ToBegin() { }
public void Stop() { this.Stop(true); }
private static int IPToInt(string Expression)
{
try
{
byte[] IPAddress = System.Net.IPAddress.Parse(Expression).GetAddressBytes();
return (Convert.ToInt32(IPAddress[3]) << 24) | (Convert.ToInt32(IPAddress[2]) << 16) | (Convert.ToInt32(IPAddress[1]) << 8) | Convert.ToInt32(IPAddress[0]);
} catch { return 0; }
}
private Map GetBasics(string IPString)
{
int res = Scanner.IPToInt(IPString);
if (res > 0)
{
long mem = 0L;
int PhyAddrLen = 6;
if (Scanner.SendARP(res, 0, out mem, ref PhyAddrLen) == 0)
{
Map dev = new Map();
byte[] macbytes = BitConverter.GetBytes(mem);
dev.IP = IPString;
string Tmp = BitConverter.ToString(macbytes, 0, 3);
if (this.OUIList != null && this.OUIList.ContainsKey(Tmp)) { dev.BRAND = this.OUIList[Tmp]; }
dev.MAC = Tmp + "-" + BitConverter.ToString(macbytes, 3, 3);
try { dev.NAME = Dns.GetHostEntry(IPString).HostName.ToLower(); } catch { dev.NAME = "unknow"; }
return dev;
}
}
return null;
}
private static void GetNode(ref string IP, ref string Node, ref byte Device)
{
string[] NodeComp = IP.Split('.');
Node = NodeComp[0] + "." + NodeComp[1] + "." + NodeComp[2] + ".";
Device = Convert.ToByte(NodeComp[3]);
}
public static Dictionary<string, string> DonwloadOUTFile(bool ForceUpdate = true)
{
Dictionary<string, string> List = null;
try
{
string Aux = Scanner.UploadPath;
if (Aux == null) { Aux = string.Empty; }
else if (Aux != string.Empty)
{
string Tmp = Aux + "~" + Scanner.LocalOUIFileName;
Aux += Scanner.LocalOUIFileName;
bool FileExists = File.Exists(Aux);
if (FileExists && ((DateTime.UtcNow.Ticks - (new FileInfo(Aux)).CreationTimeUtc.Ticks) > Scanner.MaxOUIAge))
{
File.Delete(Aux);
ForceUpdate = true;
}
string Aux2 = string.Empty;
if (ForceUpdate)
{
List = new Dictionary<string, string>(25000);
using (WebClient Downloader = new WebClient()) { Downloader.DownloadFile(Scanner.WebOUIFile, Tmp); }
using (StreamReader Reader = new StreamReader(Tmp))
using (StreamWriter Writer = new StreamWriter(Aux))
{
do
{
Aux = Reader.ReadLine();
if (Aux.ToLower().Contains("(hex)"))
{
Aux2 = Aux.Substring(0, 8).ToUpper();
Aux = Aux.Substring(Aux.LastIndexOf('\t') + 1);
if (!List.ContainsKey(Aux2))
{
List.Add(Aux2, Aux);
Writer.WriteLine(Aux2 + "\t" + Aux);
}
}
} while (Reader.Peek() >= 0);
Reader.Close();
Writer.Close();
}
try { File.Delete(Tmp); } catch { /* NOTHING */ }
}
else if (FileExists)
{
List = new Dictionary<string, string>(25000);
using (StreamReader Reader = new StreamReader(Aux))
{
do
{
Aux = Reader.ReadLine();
if (Aux != null && Aux.Length > 9)
{
Aux2 = Aux.Substring(0, 8);
if (!List.ContainsKey(Aux2)) { List.Add(Aux2, Aux.Substring(9)); }
}
} while (Reader.Peek() >= 0);
Reader.Close();
}
}
}
}
catch
{
if (List != null) { List.Clear(); }
List = null;
}
return List;
}
private void ReadScaner()
{
this.UpdatingOUI = true;
try { this.OUIList = Scanner.DonwloadOUTFile(ForceUpdate: false); } catch { /* NOTHING */ }
this.UpdatingOUI = false;
if (this.OUIList == null || this.OUIList.Count == 0) { this.Errors += "\nErrorOUIFileDownload"; }
Map Dev = null;
this.Current = this.Initial;
if (this.Limit < this.Initial)
{
Dev = this.GetBasics(this.Node + this.Initial.ToString());
if (Dev != null) { this.Devices.Add(Dev); }
}
else
{
bool ToAdd = true;
while (this.Current <= this.Limit)
{
Dev = this.GetBasics(this.Node + this.Current.ToString());
this.Current += 1;
if (Dev != null)
{
ToAdd = true;
foreach (Map iDev in this.Devices)
{
if (iDev.MAC == Dev.MAC)
{
ToAdd = false;
break;
}
}
if (ToAdd) { this.Devices.Add(Dev); }
}
}
}
this.Message = "Finished!";
this.Interrupt();
}
public void GetRange(string IPInitial, byte Limit, bool AutoSave = true)
{
if (!this.Working)
{
this.AutoSave = AutoSave;
this.Working = true;
Scanner.GetNode(ref IPInitial, ref this.Node, ref this.mInitial);
this.Limit = Limit;
this.Worker = new Thread(this.ReadScaner);
this.Worker.IsBackground = true;
this.ToBegin();
this.Worker.Start();
}
}
public static void GetRange(bool AutoSave, string IPInitial, byte Limit)
{
if (Scanner.Scan == null)
{
Scanner.Scan = new Scanner();
Scanner.Scan.GetRange(IPInitial, Limit, AutoSave: AutoSave);
}
}
~Scanner()
{
if (this.OUIList != null)
{
this.OUIList.Clear();
this.OUIList = null;
}
}
}
}
How do i make that code able to get the hierarchy like windows does?

Huge List<T> processing and Pdf generate

I have a pdf file as Byte[] and I'm using iTextSharp to modify the file and embed a specific details in it.
in the List I have min. 25K objects, and I need to generate 25K pdf files.
I'm using Parallel.ForEach but it takes 16.40 mins to be done in Total.
I used ToLookUp method like this:
var valuesToLookupWith = Recipients.ToLookup(item => item.ID);
List<int> Ids = Recipients.Select(item => item.ID).ToList();
Partitioner<int> partitioner = Partitioner.Create(Ids, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions { MaxDegreeOfParallelism = 6 } ,(id) =>
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile((fileAsByteArray,id, "www.xyz.ca"));
...
});
and I used ForEach and also it takes approx. > 25 minutes.
foreach (int id in Ids)
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile(fileAsByteArray,id, "www.xyz.ca");
...
}
any suggested way to speedup the process please?
FYI I'm not writing anything on the disk, all is done in memory as Byte[] and then I'm writing the values back to the Db.
and also all the time spent - mentioned in the question is only the time spent for Parallel.ForEach / ForEach statements.
Db calls is not an issue for me at all, I'm making only two calls to the Db , one when I load list of recipients from it and another call when writing values back to the Db
public static byte[] GeneratePdfFromPdfFile(byte[] file, int id, string landingPage)
{
try
{
using (var ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new iTextSharp.text.Document();
//Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
PdfContentByte cb = writer.DirectContent;
// doc.NewPage();
//var srHtml = new StringReader(source);
////parse html code to xml
//iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
PdfReader reader = new PdfReader(file);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
doc.NewPage();
//Insert to Destination on the first page
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// Add a new page to the pdf file
doc.NewPage();
// set pdf open action to open the link embedded in the file.
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + GetCampaignRecipientCode(id) + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
writer.SetOpenAction(act);
doc.Close();
return ms.ToArray();
}
}
catch { return null; }
}
Recipient Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CampaignLauncherLibrary
{
public class CampaignRecipientLib
{
private int _id;
private int _crid;
private string _crcode;
private int _cmpId;
private string _cmpStatus;
private string _email;
private string _firstName;
private string _lastName;
private string _language;
private string _cmpDefaultlanguage;
private bool _isdoubleBarrle;
private DateTime? _scheduled;
private string _offset;
private string _emailTo;
private string _emailFrom;
private string _emailBody;
private string _emailSubject;
private byte[] _emailAttachment;
private string _emailReplyTo;
private string _attachmentName;
private bool _readytobesent;
private bool _pickupready;
private TimeSpan _Toffset;
private int? _cmprIDnextRecipient;
private string _CampaignGroupCode;
private bool _Reschedule;
private List<int> _Campaigns;
private List<int> _SentCampaigns;
private bool _restrictToWorkHours;
private TimeSpan? _whStart;
private TimeSpan? _whEnd;
private string _emailName;
public CampaignRecipientLib()
{
}
public CampaignRecipientLib(CampaignRecipientLib _recipient)
{
ID = _recipient.ID;
CampaignId = _recipient.CampaignId;
CampaignStatus = _recipient.CampaignStatus;
CMPRID = _recipient.CMPRID;
CMPRCode = Guid.NewGuid().ToString("N");
Email = _recipient.Email;
FirstName = _recipient.FirstName;
LastName = _recipient.LastName;
Language = _recipient.Language;
DefaultLanguage = _recipient.DefaultLanguage;
IsdoubleBarrle = _recipient.IsdoubleBarrle;
Scheduled = _recipient.Scheduled;
Offset = _recipient.Offset;
EmailTo = _recipient.EmailTo;
EmailFrom = _recipient.EmailFrom;
EmailBody = _recipient.EmailBody;
EmailSubject = _recipient.EmailSubject;
EmailAttachment = _recipient.EmailAttachment;
EmailReplyTo = _recipient.EmailReplyTo;
AttachmentName = _recipient.AttachmentName;
ReadyTobeSent = _recipient.ReadyTobeSent;
PickupReady = _recipient.PickupReady;
IDnextRecipient = _recipient.IDnextRecipient;
CampaignGroupCode = _recipient.CampaignGroupCode;
Reschedule = _recipient.Reschedule;
Campaigns = _recipient.Campaigns;
SentCampaigns = _recipient.SentCampaigns;
EmailName = _recipient.EmailName;
Toffset = _recipient.Toffset;
}
public void AssingRandomCampaign()
{
int result = 0;
List<int> cmp = _Campaigns;
List<int> sentcmp = _SentCampaigns;
if (cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList().Count > 0)
{
cmp = cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList();
result = cmp.Shuffle().Take(1).ToList()[0];
}
else
{
int N = 0;
if (sentcmp.Count == 2) N = 1;
else if (sentcmp.Count == 3) N = 2;
else N = sentcmp.Count % 2 == 0 ? 2 : 3;
List<int> lastN = sentcmp.Skip(Math.Max(0, sentcmp.Count) - N).ToList();
cmp = cmp.Where(predicate: x => !lastN.Contains(x)).ToList();
sentcmp = sentcmp.Where(predicate: x => cmp.Contains(x)).ToList();
List<int> grpOccurrences = sentcmp.GroupBy(i => i).OrderByDescending(item => item.Count()).SelectMany(i => i).Distinct().ToList();
result = grpOccurrences.Shuffle().PickRandom(1).ToList()[0];
}
if (result > 0)
{
_SentCampaigns.Add(result);
CampaignId = result;
}
}
public bool reAdjustScheduleDate()
{
try
{
Scheduled = Utilities.FixDate(Scheduled.Value, RestrictToWorkHours, Offset, WhStart, WhEnd);
}
catch (Exception ex)
{
return false;
}
return true;
}
public TimeSpan Toffset
{
get { return _Toffset; }
set { _Toffset = value; }
}
public string EmailName
{
get { return _emailName; }
set { _emailName = value; }
}
public int? IDnextRecipient
{
get { return _cmprIDnextRecipient; }
set { _cmprIDnextRecipient = value; }
}
public string CampaignGroupCode
{
get { return _CampaignGroupCode; }
set { _CampaignGroupCode = value; }
}
public bool RestrictToWorkHours
{
get { return _restrictToWorkHours; }
set { _restrictToWorkHours = value; }
}
public TimeSpan? WhStart
{
get { return _whStart; }
set { _whStart = value; }
}
public TimeSpan? WhEnd
{
get { return _whEnd; }
set { _whEnd = value; }
}
public bool Reschedule
{
get { return _Reschedule; }
set { _Reschedule = value; }
}
public List<int> Campaigns
{
get { return _Campaigns; }
set { _Campaigns = value; }
}
public List<int> SentCampaigns
{
get { return _SentCampaigns; }
set { _SentCampaigns = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public int CMPRID
{
get { return _crid; }
set { _crid = value; }
}
public string CMPRCode
{
get { return _crcode; }
set { _crcode = value; }
}
public int CampaignId
{
get { return _cmpId; }
set { _cmpId = value; }
}
public string CampaignStatus
{
get { return _cmpStatus; }
set { _cmpStatus = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public string DefaultLanguage
{
get { return _cmpDefaultlanguage; }
set { _cmpDefaultlanguage = value; }
}
public bool IsdoubleBarrle
{
get { return _isdoubleBarrle; }
set { _isdoubleBarrle = value; }
}
public DateTime? Scheduled
{
get { return _scheduled; }
set { _scheduled = value; }
}
public string EmailTo
{
get { return _emailTo; }
set { _emailTo = value; }
}
public string Offset
{
get { return _offset; }
set { _offset = value; }
}
public string EmailFrom
{
get { return _emailFrom; }
set { _emailFrom = value; }
}
public string EmailBody
{
get { return _emailBody; }
set { _emailBody = value; }
}
public string EmailSubject
{
get { return _emailSubject; }
set { _emailSubject = value; }
}
public byte[] EmailAttachment
{
get { return _emailAttachment; }
set { _emailAttachment = value; }
}
public string EmailReplyTo
{
get { return _emailReplyTo; }
set { _emailReplyTo = value; }
}
public string AttachmentName
{
get { return _attachmentName; }
set { _attachmentName = value; }
}
public bool ReadyTobeSent
{
get { return _readytobesent; }
set { _readytobesent = value; }
}
public bool PickupReady
{
get { return _pickupready; }
set { _pickupready = value; }
}
}
}

Xamarin View Not Refreshing

I am having some problems with my Xamarin XAML page and its viewmodel.
I have written the code with a bunch of methods which are executed via commands from the XAML.
Functionally its all working as desired. However, the view is not refreshing when the methods have finished executing. So despite inserting things and removing things from my observable collections (via an API call update), and having a notifypropertychanged event, the page doesn't reload.
Any ideas?
ViewModel (Some properties omitted to fit the character limit for a post)
namespace TechsportiseApp.ViewModels
{
public class ResultsProcessViewModel : INotifyPropertyChanged
{
public ICommand AddTimingCommand { get; set; }
public ICommand AddScanCommand { get; set; }
public ICommand DeleteTimingCommand { get; set; }
public ICommand DeleteScanCommand { get; set; }
public ICommand PublishCommand { get; set; }
public ICommand LoadResultsCommand { get; set; }
public ICommand MissingFinisherCommand { get; set; }
public ICommand MissingTimingCommand { get; set; }
public int RaceId { get; set; }
public DateTime RaceDate { get; set; }
//public ResultsViewModel(Race race)
public ResultsProcessViewModel(Race race)
{
AddTimingCommand = new Command(AddTiming);
AddScanCommand = new Command(AddScan);
DeleteTimingCommand = new Command<int>(DeleteTiming);
DeleteScanCommand = new Command<int>(DeleteScan);
PublishCommand = new Command<string>(Publish);
LoadResultsCommand = new Command<int>(LoadResults);
MissingFinisherCommand = new Command(MissingFinisher);
MissingTimingCommand = new Command(MissingTiming);
Invalid = false;
AddTimingVisibility = false;
AddScanVisibility = false;
AddVisibility = true;
PublishProvisionalVisibility = false;
PublishFinalVisibility = false;
IsBusy = false;
RaceId = race.Id;
RaceDate = race.RaceDate;
RaceStartTime = Convert.ToDateTime(race.RaceStartTime);
Scans = ScansAPI.GetScans(RaceId);
Timings = TimingsAPI.GetTimings(RaceId);
Entries = EntriesAPI.GetEntries(RaceId);
LoadResults(RaceId);
}
ObservableCollection<Result> _results;
public ObservableCollection<Result> Results
{
get
{
return _results;
}
set
{
if (_results != value)
{
_results = value;
OnPropertyChanged("Results");
}
}
}
ObservableCollection<Scan> _scans;
public ObservableCollection<Scan> Scans
{
get
{
return _scans;
}
set
{
if (_scans != value)
{
_scans = value;
OnPropertyChanged("Scans");
}
}
}
ObservableCollection<Timing> _timings;
public ObservableCollection<Timing> Timings
{
get
{
return _timings;
}
set
{
if (_timings != value)
{
_timings = value;
OnPropertyChanged("Timings");
}
}
}
ObservableCollection<RaceEntry> _entries;
public ObservableCollection<RaceEntry> Entries
{
get
{
return _entries;
}
set
{
if (_entries != value)
{
_entries = value;
OnPropertyChanged("Entries");
}
}
}
ObservableCollection<Race> _races;
public ObservableCollection<Race> Races
{
get
{
try
{
var racelist = RacesAPI.GetRaces();
var sortedracelist = new ObservableCollection<Race>(racelist.OrderBy(c => c.Name));
var racecount = racelist.Count();
if (racecount == 0)
{
RaceCountZero = true;
}
else
{
RaceCountZero = false;
}
return racelist;
}
catch
{
Invalid = true;
ValidationError = "Error getting Race List. No internet connection available.";
}
return _races;
}
set
{
if (_races != value)
{
_races = value;
OnPropertyChanged("Races");
}
}
}
string _aboveBelow;
public string AboveBelow
{
get { return _aboveBelow; }
set
{
if (_aboveBelow == value)
return;
_aboveBelow = value;
OnPropertyChanged("AboveBelow");
}
}
string _aboveBelowPosition;
public string AboveBelowPosition
{
get { return _aboveBelowPosition; }
set
{
if (_aboveBelowPosition == value)
return;
_aboveBelowPosition = value;
OnPropertyChanged("AboveBelowPosition");
}
}
string _addHH;
public string AddHH
{
get { return _addHH; }
set
{
if (_addHH == value)
return;
_addHH = value;
OnPropertyChanged("AddHH");
}
}
string _addMM;
public string AddMM
{
get { return _addMM; }
set
{
if (_addMM == value)
return;
_addMM = value;
OnPropertyChanged("AddMM");
}
}
string _addSS;
public string AddSS
{
get { return _addSS; }
set
{
if (_addSS == value)
return;
_addSS = value;
OnPropertyChanged("AddSS");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
void AddTiming()
{
AddScanVisibility = false;
AddTimingVisibility = !AddTimingVisibility;
}
void AddScan()
{
AddScanVisibility = !AddScanVisibility;
AddTimingVisibility = false;
}
void MissingFinisher()
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
var scancount = Scans.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a scan whilst you are offline");
else if (string.IsNullOrEmpty(MissingBib))
throw new Exception("You must enter a bib number");
else if (string.IsNullOrEmpty(AboveBelow))
throw new Exception("You must choose if you are adding the bib above or below");
else if (string.IsNullOrEmpty(AboveBelowPosition))
throw new Exception("You must enter the position you are inserting " + AboveBelow);
else if (Convert.ToInt32(AboveBelowPosition) > scancount)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
else if (Convert.ToInt32(AboveBelowPosition) < 1)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
//We are good to go
else
{
var InsertedSequence = new int();
var abovebelow = Scans.SingleOrDefault(i => i.Position == Convert.ToInt32(AboveBelowPosition));
var abposition = Convert.ToInt32(AboveBelowPosition);
if (AboveBelow == "Above")
{
InsertedSequence = abovebelow.Sequence + 5;
}
else if (AboveBelow == "Below")
{
InsertedSequence = abovebelow.Sequence - 5;
}
else
{
return;
}
//Need to add resequencing and reallocation of position numbers
var scan = new ScanPost
{
RaceId = RaceId,
BibNumber = MissingBib,
Sequence = InsertedSequence,
Position = abposition,
Reorder = true,
Status = 0
};
var createscan = ScansAPI.CreateScan(scan);
if (createscan.Code != "Created")
throw new Exception("Error creating scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void MissingTiming()
{
Task.Run(() =>
{
try
{
var timingcount = Timings.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a timing whilst you are offline");
//We are good to go
else
{
if (AddHH == "") { AddHH = "0"; }
if (AddMM == "") { AddMM = "0"; }
if (AddSS == "") { AddSS = "0"; }
var ManualEndTime = RaceStartTime.AddHours(Convert.ToDouble(AddHH))
.AddMinutes(Convert.ToDouble(AddMM))
.AddSeconds(Convert.ToDouble(AddSS));
var timing = new TimingPost
{
RaceId = RaceId,
StartTime = RaceStartTime,
EndTime = ManualEndTime,
Reorder = true,
Position = 0,
Status = 0
};
var createtiming = TimingsAPI.CreateTiming(timing);
if (createtiming.Code != "Created")
throw new Exception("Error creating timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Results"));
}
});
}
void DeleteTiming(int timingid)
{
//Do stuff when deleting a timing. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a timing whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(timingid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Timings");
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Timings"));
}
});
}
void DeleteScan(int scanid)
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a scan whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(scanid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void Publish(string status)
{
Task.Run(() =>
{
try
{
var publish = new Publish();
publish.RaceId = RaceId;
publish.ResultStatus = status;
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot publish results whilst you are offline");
//We are good to go
else
{
var publishrace = RacesAPI.PublishRace(publish);
if (publishrace.Code != "NoContent")
throw new Exception("Error publishing race");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void LoadResults(int raceid)
{
var results = new ObservableCollection<Result>();
//Start with the timings
foreach (Timing timing in Timings)
{
var result = new Result();
//Basic details
result.RaceId = RaceId;
result.RaceDate = RaceDate;
result.Status = "Processing";
//Timing Data
result.TimingId = timing.Id;
result.TimingPosition = timing.Position;
result.TimingStatus = timing.Status;
result.StartTime = timing.StartTime;
result.EndTime = timing.EndTime;
var elapsed = result.EndTime - result.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis;
if (elapsed.Milliseconds.ToString().Length > 2)
{
elapsedmillis = elapsed.Milliseconds.ToString().Substring(0, 2);
}
else
{
elapsedmillis = elapsed.Milliseconds.ToString();
}
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if((elapsedhours == "00"))
{
result.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
result.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(result);
}
//Add in the scans
foreach (Result result1 in results)
{
var scan = Scans.FirstOrDefault(p => p.Position == result1.TimingPosition);
if (scan != null)
{
result1.ScanId = scan.Id;
result1.ScanPosition = scan.Position;
result1.ScanStatus = scan.Status;
result1.ScanBibNumber = scan.BibNumber;
}
else
{
result1.ScanId = 0;
result1.ScanPosition = 0;
result1.ScanStatus = 99;
result1.ScanBibNumber = "UNKNOWN";
}
}
//Add any scans which there are no times for (Higher than count)
var timingscount = Timings.Count();
var notimescans = new ObservableCollection<Scan>();
foreach (Scan scan in Scans)
{
if (scan.Position > timingscount)
{
var newresult = new Result();
newresult.RaceId = RaceId;
newresult.RaceDate = RaceDate;
newresult.Status = "Processing";
newresult.ScanId = scan.Id;
newresult.ScanPosition = scan.Position;
newresult.ScanStatus = scan.Status;
newresult.ScanBibNumber = scan.BibNumber;
newresult.TimingId = 0;
newresult.TimingPosition = 99999;
newresult.TimingStatus = 99;
newresult.StartTime = RaceStartTime;
newresult.EndTime = RaceStartTime;
var elapsed = newresult.EndTime - newresult.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis = elapsed.Milliseconds.ToString();
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if ((elapsedhours == "00"))
{
newresult.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
newresult.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(newresult);
}
}
//Then add in the entries
foreach (Result result2 in results)
{
var entry = Entries.FirstOrDefault(p => p.BibNumber == result2.ScanBibNumber);
if (entry != null)
{
result2.EntryId = entry.Id;
result2.FirstName = entry.FirstName;
result2.LastName = entry.LastName;
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = entry.Gender;
result2.DateOfBirth = entry.DateOfBirth;
result2.Club = entry.Club;
result2.Team = entry.Team;
result2.EntryBibNumber = entry.BibNumber;
}
else
{
result2.EntryId = 0;
result2.FirstName = "Unknown";
result2.LastName = "ATHLETE";
result2.Gender = "Unknown";
result2.DateOfBirth = DateTime.Now;
result2.Club = "";
result2.Team = "";
result2.EntryBibNumber = "Unknown";
}
}
var sortedresults = new ObservableCollection<Result>(results.OrderBy(c => c.TimingPosition));
Results = sortedresults;
OnPropertyChanged("Results");
}
}
}

Bind Long List Selector to result of POST method

I'm trying to POST data to server and get the response to bind it to a Long List Selector. This is the code :
public class TestData
{
private string _LikeNum, _CommentNum, _HyperLinkTitle, _HyperLinkNavigationLink, _BrandImage, _PostImage, _PostDate, _PostTitle, _PostDescription, _PostID;
public string LikeNum { get { return _LikeNum; } set { _LikeNum = value; } }
public string CommentNum { get { return _CommentNum; } set { _CommentNum = value; } }
public string HyperLinkTitle { get { return _HyperLinkTitle; } set { _HyperLinkTitle = value; } }
public string HyperLinkNavigationLink { get { return _HyperLinkNavigationLink; } set { _HyperLinkNavigationLink = value; } }
public string BrandImage { get { return _BrandImage; } set { _BrandImage = value; } }
public string PostImage { get { return _PostImage; } set { _PostImage = value; } }
public string PostDate { get { return _PostDate; } set { _PostDate = value; } }
public string PostTitle { get { return _PostTitle; } set { _PostTitle = value; } }
public string PostDescription { get { return _PostDescription; } set { _PostDescription = value; } }
public string PostID { get { return _PostID; } set { _PostID = value; } }
public TestData(string LNum, string CNum, string HLTitle, string HLNaviagtionLink, string BImage, string PImage, string PDate, string PTitle, string PDescription, string PID)
{
this.LikeNum = LNum;
this.CommentNum = CNum;
this.HyperLinkTitle = HLTitle;
this.HyperLinkNavigationLink = HLNaviagtionLink;
this.BrandImage = BImage;
this.PostImage = PImage;
this.PostDate = PDate;
this.PostTitle = PTitle;
this.PostDescription = PDescription;
this.PostID = PID;
}
}
#region Lists of data
List<string> LstBrandID = new List<string>();
List<string> LstBrandName = new List<string>();
List<string> LstBrandLongitude = new List<string>();
List<string> LstBrandLatitude = new List<string>();
List<string> LstPostID = new List<string>();
List<string> LstPostTitle = new List<string>();
List<string> LstPostDescription = new List<string>();
List<string> LstPostDate = new List<string>();
List<string> LstLikeNum = new List<string>();
List<string> LstCommentNum = new List<string>();
List<string> LstUserLike = new List<string>();
List<string> LstCatName = new List<string>();
List<string> LstUserFollow = new List<string>();
#endregion
ObservableCollection<TestData> DataList = new ObservableCollection<TestData>();
string id;
public Home()
{
InitializeComponent();
id = PhoneApplicationService.Current.State["id"].ToString();
try
{
GetPosts(id);
myLLS.ItemsSource = DataList;
for (int i = 1; i <= 10; i++)
{
DataList.Add(new TestData(LstLikeNum[i], LstCommentNum[i], LstBrandName[i], "SomePage.xaml", "SomeLink.com/data/" + LstBrandID[i], "SomeLink.com/data/" + LstPostID[i], LstPostDate[i], LstPostTitle[i], LstPostDescription[i], LstPostID[i]));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
#region getting data
void GetPosts(string UserID)
{
WebClient webclient = new WebClient();
Uri uristring = new Uri("SomeLink.com");
webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
string postJsonData = string.Empty;
postJsonData += "userId=" + UserID;
webclient.UploadStringAsync(uristring, "POST", postJsonData);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
}
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
string response = e.Result.ToString();
JArray a = JArray.Parse(response);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = p.Value.ToString();
if (name == "brandId")
{
LstBrandID.Add(value);
}
else if (name == "brandName")
{
LstBrandName.Add(value);
}
else if (name == "brandLongitude")
{
LstBrandLongitude.Add(value);
}
else if (name == "brandLatitude")
{
LstBrandLatitude.Add(value);
}
else if (name == "postId")
{
LstPostID.Add(value);
}
else if (name == "postTitle")
{
LstPostTitle.Add(value);
}
else if (name == "postDescription")
{
LstPostDescription.Add(value);
}
else if (name == "postDate")
{
LstPostDate.Add(value);
}
else if (name == "likeNum")
{
LstLikeNum.Add(value);
}
else if (name == "commentNum")
{
LstCommentNum.Add(value);
}
else if (name == "userLike")
{
LstUserLike.Add(value);
}
else if (name == "catName")
{
LstCatName.Add(value);
}
else if (name == "userFollow")
{
LstUserFollow.Add(value);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
When I run the application I get Out Of Range Exception
Getting data isn't the problem. The problem is the time it takes to get data from server to bind it to the Long List Selector. So, how can I delay the binding tell I get the data from the server and fill the Lists with them ?
In your Home():
myLLS.ItemsSource = DataList;
is good. You are telling your LLS to watch this data source and update itself whenever a new item is inserted.
for (int i = 1; i <= 10; i++)
{
DataList.Add(new TestData(LstLikeNum[i], LstCommentNum[i], LstBrandName ...);
}
is not good. You are trying to populate your data source before the data arrived. This is the operation that belongs in your request's callback. You're getting an out of range exception because LstLikeNum has 0 items, and you're trying to get items 0 -> 9.
Instead, do this:
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) {
...
int i = 0;
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
...
}
var testData = new TestData(LstLikeNum[i], LstCommentNum[i], ...);
DataList.Add(testData);
i++;
}
}
Note that you don't need to bind (myLLS.ItemsSource = DataList) in the callback. That's something you only do once -- the callback is only adding items to the source.

Binding to New Member Display; BuildComboList

I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}

Categories