I am developing a Windows Phone prayer time application, and I want to calculate the prayer time when mobile changes date automatically or by user hand ...
I've looked a lot to find the date changed event for Windows Phone,
but I don't know how to handle this event
I dont fully understand what you are trying to ask still this could help you. Save your date in a variable dt globally and call the checkfunction() where ever you need to check the date. The checkfunction will keep invoking the startfunction() which in turn will keep calling the checkfunction() at a interval of 100 milliseconds.
private bool DateChanged(DateTime date)
{
if (DateTime.Compare(DateTime.Today, date) == 0)
return true;
else
return false;
}
public void startfunction()
{
System.Threading.ThreadPool.QueueUserWorkItem(obj =>
{
System.Threading.Thread.Sleep(100);
Dispatcher.BeginInvoke(() =>
{
checkfunction();
});
});
}
public void checkfunction()
{
if (DateChanged(dt))
{
//execute code
}
else
{
startfunction();
}
}
Related
I'm writing an Android renderer for a Xamarin Forms custom crontrol(CustomDatePicker). I found sample code which does the job. However there are a few lines of code that I do not understand. I'm referring to the first constructor parameter of DatePickerDialog which is a callback function. Could someone please explain the what this actually does and also if I really need all commands, for example
view.Date = e.Date ?
I'm already setting the date when "Done" button is clicked?? (this code exists).
[assembly: ExportRenderer(typeof(Common.Infrastructure.Controls.CustomDatePicker), typeof(CustomDatePickerRenderer))]
namespace Employer.Droid
{
public class CustomDatePickerRenderer : ViewRenderer<CustomDatePicker, EditText>
{
public CustomDatePickerRenderer(Context context) : base(context)
{
}
///more logic
void CreateDatePickerDialog(int year, int month, int day)
{
CustomDatePicker view = Element;
_dialog = new DatePickerDialog(Context, **(o, e) =>
{
view.Date = e.Date;
((IElementController)view).SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
Control.ClearFocus();
_dialog = null;**
}, year, month, day);
_dialog.SetButton("Done", (sender, e) =>
{
SetDate(_dialog.DatePicker.DateTime);
});
_dialog.DatePicker.MinDate = (long)(DateTime.Now.Date - new DateTime(1970, 1, 1)).TotalMilliseconds;
}
The EventHandler<DateSetEventArgs> callBack is the method that will be executed when a new date is set DatePicker.
In your case, you will use this method to send the value from your CustomRenderer to your CustomDatePicker in your Shared project.
I see you are also setting the value when the user clicks on the "Done" button so if you don't want to pass in an action value to the EventHandler<DateSetEventArgs> callBack, you can send an empty one, something like:
_dialog = new DatePickerDialog(Context, (o, e) => { }, year, month, day);
Just make sure that on the SetDate method you are doing all the required steps so the Date picked is correctly set into the Element.
Hope this helps.-
I'm trying to get a notification event in .NET core/Standard (as I need to do plan future actions). I'm porting a piece of existing .NET4.5x code to .NET core 2.2 or .NETStandard2.
Originally I was using:
SystemEvents.TimeChanged += SystemEvents_TimeChanged; //my handler
But in .NETCore or .NETStandard, this is not implemented.
What is the most elegant way to overcome that?
OK, so finally I did it that way (pseudo code):
public TimeSpan CheckInterval { get; private set; } = TimeSpan.FromMinutes(1);
public TimeSpan MaxAllowedDeviation { get; private set; } = TimeSpan.FromSeconds(1);
private async Task CheckTimeUpdate()
{
while (cancelToken.IsCancellationRequested == false)
{
DateTimeOffset beforeTimer = DateTimeOffset.Now;
await Task.Delay(CheckInterval, cancelToken);
DateTimeOffset afterTimer = DateTimeOffset.Now;
if ((afterTimer.UtcDateTime - beforeTimer.UtcDateTime).Duration() > MaxAllowedDeviation + CheckInterval)
{
//raises the event
TimeChanged?.Invoke();
}
}
}
But this only works for manual time change, not for daylight saving nor time zone updates!!
I am trying to show 10,000 contacts on listview in xamarin forms using realm. But whenever user traverse to contact listing screen
it gets freezed and loads after a while.
Moreover , i have provided an option to search from list as well and that too gets stuck as search if performing on UI thread.
Following is the code to load data from realm
public override async Task Initialize(Object data )
{
private Realm _realmInstance = getRealm();
if (contactList != null)
{
contactList.Clear();
}
contactList = _realmInstance.All<Contact>().OrderByDescending(d => d.contactId).ToList();
// here the binding happens with realm data
contacts = new ObservableCollectionFast<Contact>(contactList);
}
public ObservableCollectionFast<Contact> contacts
{
get { return items; }
set
{
items = value;
OnPropertyChanged("contacts");
}
}
as it was taking time in loading i thought to fetch realm data in background and bind it on UI thread as follows
but that is throwing error
realm accessed from incorrect thread
await Task.Run(() => {
contactList = _realmInstance.All<Contact>().OrderByDescending(d => d.contactId).ToList();
});
if (contactList.Count() > 0)
{
ContactListView = true;
AddContactMsg = false;
}
else
{
AddContactMsg = true;
}
Device.BeginInvokeOnMainThread(() =>
{
contacts = new ObservableCollectionFast<Contact>(contactList);
});
i wanted to try limiting the results by using TAKE function of LINQ but unfortunately its not supported by realm yet. not sure how i can smoothly load records from realm to listview.
EDIT
as per the SushiHangover i have changed things from IList to IQueryable
public IQueryable<Contact> contacts
{
get { return items; }
set
{
items = value;
OnPropertyChanged("contacts");
}
}
public override async Task Initialize(Object data )
{
_realmInstance = getRealm();
contacts = dbContactList= _realmInstance.All<Contact>();
}
so far search is working pretty smoothly but IQueryable change leads to another issue. on repeatedly performing following steps results in app crash
tap on list item
detail page gets open then press back
scroll down to few records
perform step 1 and repeat
this results into stackoverflow error
04-19 06:05:13.980 F/art ( 3943): art/runtime/runtime.cc:289]
Pending exception java.lang.StackOverflowError thrown by 'void
md5b60ffeb829f638581ab2bb9b1a7f4f3f.CellAdapter.n_onItemClick(android.widget.AdapterView,
android.view.View, int, long):-2' 04-19 06:05:13.980 F/art (
3943): art/runtime/runtime.cc:289] java.lang.StackOverflowError: stack
size 8MB
Link to entire log file
code to fire item click command is
public ICommand OnContactSelectCommand => new Command<Contact>(OnContactSelect);
following code will open ups a detail page
private async void OnContactSelect(Contact contact)
{
if (contact != null)
{
await NavigationService.NavigateToAsync<ContactDetailViewModel>(contact.mContactId);
}
}
Note:
when i replace IQueryable with List i do not face any error
somehow my issue is related to realm github thread where user is getting exception on listView.SelectedItem = null while using IQueryable
here is my code of list view item tap
private static void ListViewOnItemTapped(object sender, ItemTappedEventArgs e)
{
var listView = sender as ListView;
if (listView != null && listView.IsEnabled && !listView.IsRefreshing)
{
// have commented this line because it was crashing the app
//listView.SelectedItem = null;
var command = GetItemTappedCommand(listView);
if (command != null && command.CanExecute(e.Item))
{
command.Execute(e.Item);
}
}
}
How do I tell ReactiveUI to update bindings?
Normally, I would do something like this:
string _instructorNameInput;
public string InstructorNameInput
{
get { return _instructorNameInput; }
set
{
this.RaiseAndSetIfChanged(ref _instructorNameInput, value);
Submit.RaiseCanExecuteChanged();
}
}
However, the following isn't supported:
Submit.RaiseCanExecuteChanged();
As a result, how can I force bindings to update based on the CanExecute predicate that my command relies on?
Updated:
public partial class FormViewModel : ReactiveObject
{
public FormViewModel()
{
Submit = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanSubmit));
Submit.Subscribe(x => OnSubmit());
}
bool _canExecute;
public bool CanSubmit
{
get { return !GetUnsatisfied().Any(); }
set { this.RaiseAndSetIfChanged(ref _canExecute, value); } // Need to update view based on command.CanExecute state change
}
void OnSubmit()
{
var rosterInfo = new RosterInfo(new Course(CourseInput.Name),
new Instructor(InstructorNameInput, InstructorIdInput));
var repository = GetRepository();
repository.AddCourseInfo(rosterInfo);
Publish(REQUEST_NAVIGATION_TO_SUBMITION_CONFIRMATION, rosterInfo);
}
ObservableCollection<RequiredField> GetUnsatisfied()
{
RequiredFields.Clear();
RequiredFields = Review();
return RequiredFields;
}
}
Multiple issues:
Have a read at the fundamentals on ReactiveObject, in particular how "Read-Write Properties" are written.
In your case, this.WhenAnyValue(x => x.CanSubmit) will trigger a refresh on the command whenever the property CanSubmit changes, but this one never does, because you never call the setter (and the getter has an incorrect impl).
Currently, your method GetUnsatisfied() has "polling" semantics, which mean you need something to trigger this method to update your command. This isn't reactive at all, you should instead bind/listen to updates.
If there's no way for you to make your Review() logic reactive, then you may do something like:
var canExec = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
.Select(_ => !GetUnsatisfied().Any());
Submit = ReactiveCommand.Create(canExec);
Submit.Subscribe(x => OnSubmit());
Basically, having a timer to do your polling.
(But I strongly suggest going further down the reactive way)
I have just started learning to write mobile apps using Xamarin and MvvmCross. I have found it quite easy to pick up the basics due to the great support including the N+1 days of MvvmCross videos on YouTube (Huge thanks to Stuart Lodge).
However I am struggling with valudation data. I'm hoping someone on Stackoverflow can point me in the direction of some useful blogs or tutorials on performing validation using MvvmCross. I want to be able validate the data entered and then update the view indicating the issue.
I need something from first principles as I don't know what I don't know (If that makes sense). I need some best practice to follow.
Data validation can be displayed in the UI in different ways.
For example, you can show a message box or show a label.
Suppose you want to have a label with red text somewhere in the UI to show the error.
I assume you have a 'Save' button or similar in your UI.
You can bind the button to a SaveCommand in the view-model.
In the implementation of the SaveCommand, you can check if all the data is valid and set an Error string property.
You can have a label's text bound to the Error property. Moreover, you could also bind the label's visibility to the condition (Error != null).
public class SettingsViewModel : MvxViewModel
{
string firstName;
public string FirstName
{
get { return this.firstName; }
set
{
if(this.firstName != value)
{
this.firstName = value;
this.RaisePropertyChanged(()=> this.FirstName);
this.Error = null; // reset error
}
}
}
public string Error { get; private set; }
public ICommand SaveCommand { get { return new MvxCommand(this.Save); } }
void Save()
{
// reset error
this.Error = null;
if(string.IsNullOrEmpty(this.FirstName))
{
this.Error = "First name is empty";
}
if(string.IsNullOrEmtpy(this.Error))
{
// no error, save settings...
}
else
{
this.RaisePropertyChanged(()=> this.Error);
}
}
}