Xamarin C# Android Call Logs - c#

Im having trouble with this call logs of the device.
The code is not returning the logs at all, It's giving false data.
Code:
public void ReadCalls()
{
try {
Android.Content.Context myContext = Android.App.Application.Context;
string myDateToCheck = myServiceRef.myTimeToCheck("CallLog");
if (myDateToCheck==null || myDateToCheck=="")
{myDateToCheck = "0";}
ICursor cursor = myContext.ContentResolver.Query( Android.Net.Uri.Parse ("content://call_log/calls"), null, "Date > ?", new string[]{myDateToCheck }, "Date ASC");
if (cursor.MoveToFirst ()) {
while (!cursor.IsAfterLast ) {
if (cursor.GetLong (cursor.GetColumnIndex (CallLog.Calls.Date)) > long.Parse (myDateToCheck)) {
string Number = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Number));
string Name = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.CachedName));
if (Name == null || Name == "") {
Name = "Unknown";
}
string Date = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Date));
string Duration = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Duration));
string Type = cursor.GetString (cursor.GetColumnIndex (CallLog.Calls.Type));
if (Number == "0") {
Number = "Unknown";
} else if (Number == "-1") {
Number = "Unknown";
}
long num = long.Parse (Date);
Java.Text.SimpleDateFormat simpleDateFormat = new Java.Text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = new DateTime (1970, 1, 1).AddMilliseconds ((double)num);
dateTime = dateTime.AddMilliseconds (simpleDateFormat.TimeZone.GetOffset (num));
if (Type == "1") {
Type = "Outgoing";
} else if (Type == "2") {
Type = "Incoming";
} else if (Type == "3") {
Type = "Missed Call";
}
// now need to write it to a database
MyCallLog myLine = new MyCallLog {
TheNumber = Number ,
TheName = Name ,
TheTime = dateTime.ToString() ,
TheDirection = Type ,
TheDuration = Duration
};
string output = Newtonsoft.Json.JsonConvert.SerializeObject (myLine );
myServiceRef.myDatabaseConnection (output);
} else {
break;
}
cursor.MoveToNext ();
}
}
}catch{
}
}
The number is always "-1".
The name is always blank,
and its always an outgoing call.
It gives a datestamp but not accurate.

//static class to convert milisecond to datetime
static class ConvertToDate
{
static readonly DateTime UnixEpochStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc); //Coverting date in to universal
public static DateTime ToDateTimeFromEpoch(this long epochTime)
{
DateTime result = UnixEpochStart.AddMilliseconds(epochTime);
return result;
}
}
Above code might help you. I am also new to Xamarin and above code gives me the appropriate date time. Please let me know if you have any queries.

public class ContactsAdapter : BaseAdapter
{
Activity activity;
List<Contact> contactList;
public ContactsAdapter(Activity activity)
{
this.activity = activity;
FillContacts();
}
void FillContacts()
{
var uri = calllog.ContentUri;
//var uri = ContactsContract.Contacts.ContentUri;
string[] projection = {
calllog.Number,
calllog.Date,
calllog.Duration,
calllog.Type,
calllog.CachedName,
calllog.CachedPhotoId
};
// CursorLoader introduced in Honeycomb (3.0, API11)
var loader = new CursorLoader(activity, uri, projection, null, null, null);
var cursor = (ICursor)loader.LoadInBackground();
contactList = new List<Contact>();
if (cursor.MoveToFirst())
{
do
{
contactList.Add(new Contact
{
Number = cursor.GetString(cursor.GetColumnIndex(projection[0])),
Date = cursor.GetLong(cursor.GetColumnIndex(projection[1])),
Duration = cursor.GetString(cursor.GetColumnIndex(projection[2])),
Type = cursor.GetString(cursor.GetColumnIndex(projection[3])),
Name = cursor.GetString(cursor.GetColumnIndex(projection[4])),
PhotoId = cursor.GetString(cursor.GetColumnIndex(projection[5]))
});
} while (cursor.MoveToNext());
}
}
public override int Count
{
get { return contactList.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return 0;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var view = convertView ?? activity.LayoutInflater.Inflate(Resource.Layout.CallLogItems, parent, false);
var callNum = view.FindViewById<TextView>(Resource.Id.NumTxtVw);
var callType = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
var calldate = view.FindViewById<TextView>(Resource.Id.CallTime);
var name = view.FindViewById<TextView>(Resource.Id.CallerNameTxtVw);
var contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
callNum.Text = contactList[position].Number;
calldate.Text = ConvertToDate.ToDateTimeFromEpoch(contactList[position].Date).ToString();// ToDateTimeFromEpoch(contactList[position].Date).ToString();
if (string.IsNullOrWhiteSpace(contactList[position].Name))
{
name.Text = "Unkown";
}
else
{
name.Text = contactList[position].Name;
}
if (contactList[position].PhotoId == null)
{
contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
contactImg.SetImageResource(Resource.Drawable.contactimg);
}
else
{
contactImg = view.FindViewById<ImageView>(Resource.Id.ContactImgVw);
contactImg.SetImageResource(Resource.Drawable.contactimg);
}
if (contactList[position].Type == "1")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.incoming);
}
else
if (contactList[position].Type == "2")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.outgoing);
}
else
if (contactList[position].Type == "3")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.misssedcall);
}
else
if (contactList[position].Type == "4")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.voicemail);
}
else
if (contactList[position].Type == "5")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.reject);
}
else
if (contactList[position].Type == "6")
{
var contactImage = view.FindViewById<ImageView>(Resource.Id.TypeIndicatImgVw);
contactImage.SetImageResource(Resource.Drawable.blocked);
}
return view;
}
}

Related

How to set second label on InfoWindow xamarin map

I want to set second label in info window on xamarin map. I use this example.
So exactly I want to set one variable who come from date base on info window like a second label:
public MapPage()
{
InitializeComponent();
DatabaseConnection();
CustomPin pin1 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.59043006333251, 24.766286971618303),
Name = "Xamarin",
Label = "р. Бяла",
Address = "гр. Смолян",
};
CustomPin pin2 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.56817473054596, 24.758451447799708),
Label = "р. Черна",
Name = "Xamarin",
Address = "гр. Смолян",
};
CustomPin pin3 = new CustomPin
{
Type = PinType.Place,
Position = new Position(41.48398466282902, 24.847715935872973),
Label = "р. Елховска",
Name = "Xamarin",
Address = "гр. Рудозем",
};
customMap.CustomPins = new List<CustomPin> {
pin1,
pin2,
pin3,
};
customMap.Pins.Add(pin1);
customMap.Pins.Add(pin2);
customMap.Pins.Add(pin3);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(41.567797926753485, 25.389703182725665), Distance.FromKilometers(70)));
}
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var codeNum = myReader.GetInt32(4);
var level = myReader.GetInt32(3);
await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
I want var codeNum = myReader.GetInt32(4); to be on the pin info window.
In my android project in directory resource/layout I have two axml files for the info window:
XamarinMapInfoWindow.axml
and
MapInfoWindow.axml
Inside in both files I create a new TextView for the second label:
<TextView
android:id="#id/InfoWindowSubtitle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowSubtitle2"
android:textColor="#android:color/black" />
On my CustomMapRenderer.cs file in android project I have method GetInfoContents in which I do not know how to submit the new label.
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}
return view;
}
return null;
}
So
` if (infoSubtitle2 != null)
{
infoSubtitle2.Text = marker.Snippet;
}`
is not the correct code. Before this method in the same page I have CreateMarker method who add a new lines on the marker and here I also don't understand how to submit the new line:
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
return marker;
}
Finally I create a new object in the Pin class for Alert Level who will come from data base.
namespace CustomRenderer
{
public class CustomPin : Pin
{
public string Name { get; set; }
public string Url { get; set; }
public int CodeNum { get; set; }
public int AlertLevel { get; set; }
}
}
My main question is how to put var level = myReader.GetInt32(3); like a second Label on InfoWindow ?
You could get the CustomPin with the GetCustomPin method in the custom renderer like the sample in your above link.
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
and in your public Android.Views.View GetInfoContents(Marker marker) method:
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
CustomPin pin = GetCustomPin(marker);
int CodeNum = pin.CodeNum; //get the pin,then get the codenum and alertlevel
string AlertLevel = pin.AlertLevel;
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
var infoSubtitle3 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle3);// create the third TextView in your xml
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = CodeNum +"";
}
if (infoSubtitle3 != null)
{
infoSubtitle3.Text = AlertLevel;
}
return view;
}
return null;
}
Update :
public partial class YouPage: ContentPage
{
public YouPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
... //you get the data from MySql,if you have several data,you need a loop
var codeNum = xxx;
var level = xxx;
CustomPin pin = new CustomPin();
pin.CodeNum = codeNum;
pin.AlertLevel = level ;
yourcustomMap.Pins.Add(pin);
}

netOffice Outlook AppointmentItem filter by EntryID from a shared folder

I have a list of emails each corresponding to a shared calendar.
In the AppointmentFound function given an AppointmentItem EntryID I would like to search if the item exists in the shared calendar.
The error I get when I run AppointmentFound() is System.Runtime.InteropServices.COMException. ErrorCode -2147467259
Searching for this error code I came across another article developed in the second function (commented) AppointmentFound, but without success.
Running out of memory looping through mail items
What is the best way to search for an AppointmentItem for EntryID with the netOffice API?
public class TestCalendar {
private Outlook oOutlook;
public AppointmentItem AppointmentItem { get; set; }
private List<string> Owner = new List<string>();
private DateTime dtFrom;
private DateTime dtTo;
public TestCalendar() {
Inizialize();
CheckIfExists();
}
private void Inizialize() {
oOutlook = new Outlook();
dtFrom = new DateTime(DateTime.Now.Year - 1, 01, 01);
dtTo = new DateTime(DateTime.Now.Year, 12, 31);
}
public void CheckIfExists() {
string entryID;
int i;
bool bFound;
Owner = GetCalendarOwner();
if(!Owner.Any() && Owner.Count < 1) {
return;
}
entryID = "00000000BEF58CC55AC7EC42B5AA253C222DE56707000F9B165872833F4BBFD216F68D0E5C5480000000010D00000F9B035872833F4BBFD896F68D0E5C550000014BBE4A0000";
foreach(string email in Owner) {
oOutlook.ProcessSharedFolder(email, dtFrom, dtTo);
bFound = oOutlook.AppointmentFound(entryID);
if(!bFound)
i = SqlFactory.DeleteAppointment(entryID);
}
}
private List<string> GetCalendarOwner() {
List<string> delegator = new List<string>();
try {
delegator.Add("test01#mycompany.com");
delegator.Add("test02#mycompany.com");
delegator.Add("test03#mycompany.com");
delegator.Add("test04#mycompany.com");
}
catch(System.Exception ex) {
throw new System.Exception(Commons.Scope, ex.InnerException);
}
return delegator;
}
}
public class TestOutlook {
public Application oApp;
private Recipient TeamMember { get; set; }
public MAPIFolder SharedFolder { get; set; }
private _NameSpace ns { get; set; }
private _Items calendarAppointments { get; set; }
private string restrictCriteria, storeID;
public _Items ProcessSharedFolder(string email, DateTime from, DateTime to) {
try {
TeamMember = oApp.Session.CreateRecipient(email);
TeamMember.Resolve();
if(!TeamMember.Resolved) return null;
SharedFolder = oApp.Session.GetSharedDefaultFolder(TeamMember, OlDefaultFolders.olFolderCalendar);
storeID = SharedFolder.StoreID;
ns = oApp.Session;
if(SharedFolder.DefaultMessageClass != "IPM.Appointment" || TeamMember.DisplayType != 0) {
throw new System.InvalidOperationException("DefaultMessageClass != IPM.Appointment");
}
else {
calendarAppointments = new _Items();
restrictCriteria = "[Start]<=\"" + to.ToString("g") + "\"" + " AND [End]>=\"" + from.ToString("g") + "\"";
calendarAppointments = SharedFolder.Items.Restrict(restrictCriteria);
if(calendarAppointments == null || !calendarAppointments.Any()) return null;
return calendarAppointments;
}
}
catch(System.Exception) {
throw;
}
}
public bool AppointmentFound(string entryID) {
bool bRes = false;
try {
//restrictCriteria = "[EntryId]=\"" + entryID("g") + "\"";
//calendarAppointments = SharedFolder.Items.Restrict(restrictCriteria);
AppointmentItem itemFound = (AppointmentItem)ns.GetItemFromID(entryID);
if(itemFound == null) bRes = false;
else bRes = true;
}
catch(NetOffice.NetOfficeException ex) {
}
return bRes;
}
//public bool AppointmentFound(string entryID) {
// try {
// //AppointmentItem item = (AppointmentItem)ns.GetItemFromID(entryID, storeID);
// _Items calItems = SharedFolder.Items;
// COMObject calItem = null;
// do {
// if(null == calItem)
// calItem = (COMObject)calItems.GetFirst();
// if(null == calItem)
// break;
// // do what you want here
// calItem.Dispose();
// calItem = (COMObject)calItems.GetNext();
// } while(null != calItem);
// if(calItem == null) bRes = false;
// else bRes = true;
// }
// catch(NetOffice.NetOfficeException ex) {
// }
// return bRes;
//}
}
My solution with LINQ.
public bool AppointmentFound(string entryID) {
try {
var query = from AppointmentItem ai in calendarAppointments
where ai.EntryID == entryID
select ai;
bRes = query.Any();
}
catch(NetOffice.NetOfficeException ex) {
}
return bRes;
}

Report Viewer export button load the data again

I have a report viewer in reportviewer.aspx. After I generated the report, I chose Excel format and click Export. I found that in backend, when I press the export button, it goes to load the data again and it make export take 20 minutes or more. I am doubting whether the export is just dumping the already generated report content or will load the functions and do the calculation once again. How can I avoid the export to do the calculation again but just dumping the already generated report?
Here is my code behind the reportviewer.aspx.
public partial class ReportViewer : CustomPage
{
private string _reportSourceFolder = ConfigurationManager.AppSettings["ReportSourceFolder"];
protected void Page_Load(object sender, EventArgs e)
{
try
{
EW_REPORTS, true); // added by HC on 2014-10-21, for permission checking
string reportFileName = Request.QueryString["ReportFileName"];
if (string.IsNullOrEmpty(reportFileName))
{
}
else
{
int? yearInt = null;
string year = Request.QueryString["Year"];
if (string.IsNullOrEmpty(year))
{
yearInt = DateTime.Now.Year;
}
else
{
try
{
yearInt = Convert.ToInt32(year);
}
catch { }
}
string reportFullPath = Path.Combine(_reportSourceFolder, reportFileName);
Telerik.Reporting.UriReportSource uriReportSource = new Telerik.Reporting.UriReportSource();
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("lang", WebUtil.GetLanguage()));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("companyID", WebUtil.GetCompanyID()));
if (yearInt != null)
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("year", yearInt));
}
if (
!"AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//"Report1.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//|| "ESGSummaryReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
)
{
int? fromYear = Common.Util.TryToConvertToInt32(Request.QueryString["fromYear"]);
int? fromMonth = Common.Util.TryToConvertToInt32(Request.QueryString["fromMonth"]);
int? toYear = Common.Util.TryToConvertToInt32(Request.QueryString["toYear"]);
int? toMonth = Common.Util.TryToConvertToInt32(Request.QueryString["toMonth"]);
string indicatorIDs = Request.QueryString["indicatorIDs"];
string locationIDs = Request.QueryString["locationIDs"];
if (fromYear == null || fromMonth == null || toYear== null || toMonth == null)
{
try
{
DateTime? fiscalYearStartDate = Util.GetCorporateFiscalYearStartDate();
if (fiscalYearStartDate != null)
{
DateTime now = DateTime.Now;
DateTime startDate = new DateTime(now.Year, fiscalYearStartDate.Value.Month, 1);
if (now < startDate)
{
startDate = startDate.AddYears(-1);
}
DateTime endDate = startDate.AddYears(1).AddMilliseconds(-1d);
if (fromYear == null)
{
fromYear = startDate.Year;
}
if (fromMonth == null)
{
fromMonth = startDate.Month;
}
if (toYear == null)
{
toYear = endDate.Year;
}
if (toMonth == null)
{
toMonth = endDate.Month;
}
}
}
catch { }
}
// prevent incorrect numbers
List<int> indicatorIDsList = new List<int>(1024);
string[] indicatorIDsArr = new string[] { };
if (indicatorIDs != null)
{
indicatorIDsArr = indicatorIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach(string indicatorID in indicatorIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(indicatorID);
if (temp != null && !indicatorIDsList.Contains(temp.Value))
{
indicatorIDsList.Add(temp.Value);
}
}
if (indicatorIDsList.Count > 0)
{
indicatorIDs = string.Join(",", indicatorIDsList);
}
else
{
indicatorIDs = "0";
}
List<int> locationIDsList = new List<int>(1024);
string[] locationIDsArr = new string[] { };
if (locationIDs != null)
{
locationIDsArr = locationIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach (string locationID in locationIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(locationID);
if (temp != null && !locationIDsList.Contains(temp.Value))
{
locationIDsList.Add(temp.Value);
}
}
if (locationIDsList.Count > 0)
{
locationIDs = string.Join(",", locationIDsList);
}
else
{
locationIDs = "0";
}
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromYear", fromYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toYear", toYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromMonth", fromMonth));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toMonth", toMonth));
//uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("indicatorIDs", indicatorIDs));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("locationIDs", locationIDs));
}
if ("AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase))
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateFrom", DateTime.Now.AddDays(-1d)));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateTo", DateTime.Now));
}
uriReportSource.Uri = reportFullPath;
if (IsPrintPreviewMode())
{
uiReportViewer.ViewMode = Telerik.ReportViewer.WebForms.ViewMode.PrintPreview;
}
uiReportViewer.ReportSource = uriReportSource;
} // end if
}
catch (Exception ex)
{
uiPanel.Alert(Convert.ToString(HttpContext.GetGlobalResourceObject("Resource", "Message_Error_Occurs")));
Logger.Log(string.Format("Error occurs in the '{0}.{1}' method.{2}{3}"
, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString()
, System.Reflection.MethodBase.GetCurrentMethod().Name
, Environment.NewLine
, ex.ToString()));
}
} // end method
private bool IsPrintPreviewMode()
{
bool val = false;
string temp = Request.QueryString["IsPrintPreviewMode"];
if (!string.IsNullOrEmpty(temp))
{
try
{
val = Convert.ToBoolean(temp);
}
catch { }
}
return val;
}
protected void uiBack_Click(object sender, EventArgs e)
{
string reportFileName = Request.QueryString["ReportFileName"];
Response.Redirect(string.Format("~/ReportCriteria.aspx?ReportFileName={0}", reportFileName), false);
Context.ApplicationInstance.CompleteRequest();
}
}

ViewModel Method Not Reloading View

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");
}

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");
}
}
}

Categories