EventHandler<DateSetEventArgs> callBack, DatePickerDialog - xamarin

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.-

Related

Binding CalendarView DateChange event with MvvmCross

I have a CalendarView that looks like this:
<CalendarView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="#+id/createReservationCalendarView" />
Here is how I handle the DateChange event without MvvmCross:
protected override void OnCreate(Bundle savedInstanceState)
{
... Code ...
calendar.DateChange += (s, args) =>
{
var year = args.Year;
var month = args.Month + 1;
var dayOfMont = args.DayOfMonth;
var date = new DateTime(year, month, dayOfMont);
var myReservations = new Intent(this, typeof(CreateReservationTimeslotScreen));
myReservations.PutExtra("selectedDate", date.Ticks);
StartActivity(myReservations);
};
}
Now that I have switched to MvvmCross, I would like to have my ViewModel start the new activity instead.
Im not sure how to do this, since the ViewModel should be OS and UI agnostic.
The "args" argument is of type CalendarView.DateChangeEventArgs, which is Android specific, so I cant use that in the ViewModel. It derives from System.EventArgs, so maybe I could use that instead. I am thinking that there must be a simpler way.
A thought that I had was if it is possible to update a property on the ViewModel from the activity, and then execute the switch to the new Activity from there? I'm not sure how this could be accomplished since activites dont have references to their ViewModels.
Any suggestions?
Thanks.
MvvmCross does give you access to your ViewModel from your View. The relationship between your View (e.g. Activity/fragment in Android) and your ViewModel, and their ability to share data (models) in both directions is a core characteristic a Mvvm framework.
In order to setup an Activity to be used with MvvmCross you need to make sure to inherit from MvxActivity or MvxAppCompatActivity (If using Android Support Library). Following which you need to link your Activity to its corresponding ViewModel using one of the possible conventions (See link, for basic sample of each registration offered by the MvxViewModelViewTypeFinder). A simple example would be to use the concrete type based registration using the type parameter overload.
public class FirstActivity : MvxAppCompatActivity<FirstViewModel>
Now that you have access to your ViewModel from your View you can create a command that can be used to execute the navigation:
CalendarViewModel (ViewModel linked to the current Activity in question)
Create a command that requires a DateTime parameter, which in turn will pass the value when navigation (see MvvmCross Navigation docs for alternative navigation and parameter passing conventions).
public class CalendarViewModel : MvxViewModel
{
IMvxCommand _goToMyReservationCommand;
public IMvxCommand GoToMyReservationCommand =>
_goToMyReservationCommand ??
(_goToMyReservationCommand = new MvxCommand<DateTime>(NavigateToMyReservation));
void NavigateToMyReservation(DateTime reservationDate)
{
ShowViewModel<MyReservationViewModel>(
new GoToMyReservationParameter
{
ReservationTicks = reservationDate.Ticks
});
}
}
Navigation Parameter Class
Holds the values and type information used for navigation.
public class GoToMyReservationParameter
{
public long ReservationTicks { get; set; }
}
MyReservationViewModel
The ViewModel that will receive the value passed.
public class MyReservationViewModel : MvxViewModel
{
public void Init(GoToMyReservationParameter parameters)
{
var reservationTicks = parameters.ReservationTicks;
// Do what you need with the parameters
}
}
View
Execute the command on the ViewModel and pass through the DateTime object.
public class CalendarActivity : MvxAppCompatActivity<CalendarViewModel>
{
protected override void OnCreate(Bundle bundle)
{
... Code...
calendar.DateChange += (s, args) =>
{
var year = args.Year;
var month = args.Month + 1;
var dayOfMont = args.DayOfMonth;
var date = new DateTime(year, month, dayOfMont);
ViewModel.GoToMyReservationCommand.Execute(date);
};
}
}

windows phone 7 how to pass Array value from one scree to another screen

///first I have crated Popular class for storing values
public class Popular
{
public string trk_mnetid,trk_title , art_mnetid, art_name, image_url;
}
/// create popularplaylist class
public partial class PopularPlaylist : PhoneApplicationPage
{
Popular popobj = new Popular();
List<Popular> pop = new List<Popular>();
/* call json parsing it and show only "titles" in List form when i m click on perticular title i need to show details in next screen which i paser and store in popular popularplaylist class.
i use navigationservice call new screen
*/
NavigationService.Navigate(new Uri("/Popular_Module/PopularPlaylist.xaml", System.UriKind.Relative));
}
// plz tell me how to get list data in next screen
Use querystring.
Passing Value: In MainPage.xaml.cs add the following
The easiest way to pass a parameter is just to use a string, something like:
private void btnNavigate_Click(object sender, RoutedEventArgs e)
{
string url=String.Format("/Page1.xaml?parameter={0}",popular);
NavigationService.Navigate(new Uri(url, UriKind.Relative));
}
Getting Value: In Page.xaml.cs add the following
Note: It is important to override the OnNavigatedTo and after that you can use the NavigationContext to get the passed parameter.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
List<string> parameterValue = NavigationContext.QueryString["parameter"];
}
Another popular syntax to get the value of the parameter is:
List<string> parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("parameter", out parameter))
{
//do something with the parameter
}

Prism Shell buttons shared by modules

I am using Prism 2, trying to add four navigation buttons (First Record, Last Record, Previous Record, Next Record) in shell to be used by modules. I also want these buttons to be disable if active View/ViewModel does not provide these functions.
I tried using events but didn't know how to achieve my second goal regarding disabling buttons. It seems I need to check current active View/ViewModel to see if they subscribed the click event during View switch. But I think publisher should be unaware of subscriber...
Somehow I tried my own way. I create an IDocNavigation interface which has four method corresponding to my four buttons. At runtime I check modules' ViewModel if they implemented that interface or not, and change the ICommand on fly. Below is my code. I include one LastRecordCommand only:
public ShellViewModel(Views.Shell shell)
{
this.Shell = shell;
shell.DataContext = this;
shell.MainDocking.ActivePaneChanged += (s, e) =>
{
if (e.NewPane.Content is UserControl &&
((UserControl)e.NewPane.Content).DataContext is IDocumentNavigate)
{
IDocumentNavigate vm = ((UserControl)e.NewPane.Content).DataContext as IDocumentNavigate;
LastRecordCommand = new RelayCommand(x => vm.GotoLastRecord(), x => true);
}
else
{
LastRecordCommand = new RelayCommand(x => { }, x => false);
}
};
//...
I feel these are quite ugly. Creating an empty RelayCommand is also stupid. How can I improve ? or how can I achieve disabling command if event is more suitable in my case ?
You can make use of CompositeCommand in prism.
Define a globally available CompositeCommand
public static readonly CompositeCommand FirstRecord= new CompositeCommand(true);
Then in your your module view models
class Module1
{
public DelegateCommand Module1Firstrecord{ get; set; }
Module1()
{
Module1Firstrecord = new DelegateCommand(this.FirstRecord, CanExecute);
}
private void FirstRecord()
{
//do whatever you want
}
private bool CanExecute()
{
return true;
}
private void Module1_IsActiveChanged(object sender, EventArgs e)
{
//Find if your window is acive
// if it is active Module1Firstrecord.IsActive = true
//else false.
}
}
With IActiveAware you can handle the active window scenario easily. According to whether your active module have a handler for the command on not the buttons will enable/disable.

Accessing User in Entity partial class via OnContextCreated()?

All of my tables have common audit fields: modifiedBy,modifiedDateTime, etc.
I would like to have these automatically set, and can set most of them with the following code:
partial class myEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(Entities_SavingChanges);
}
private void Entities_SavingChanges(object sender, EventArgs e)
{
IEnumerable<ObjectStateEntry> objectStateEntries =
from ose
in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)
where ose.Entity != null
select ose;
var auditDate = DateTime.Now;
var auditUser = System.Web.HttpContext.Current.User.Identity.Name;//I wish
foreach (ObjectStateEntry entry in objectStateEntries)
{
ReadOnlyCollection<FieldMetadata> fieldsMetaData = entry.CurrentValues.DataRecordInfo.FieldMetadata;
FieldMetadata modifiedField = fieldsMetaData.Where(f => f.FieldType.Name == "ModifiedBy").FirstOrDefault();
if (modifiedField.FieldType != null)
{
string fieldTypeName = modifiedField.FieldType.TypeUsage.EdmType.Name;
if (fieldTypeName == PrimitiveTypeKind.String.ToString())
{
entry.CurrentValues.SetString(modifiedField.Ordinal, auditUser);
}
}
}
}
}
The problem is that there doesn't appear to be any way to get access to the current user. The app is intranet only, using Windows auth.
Is there a way to either pass in a parameter, or get access to the HttpContext (which doesn't seem like it would be a good idea, but I'm stuck)? Is there a way to populate the EventArgs with information?
Check out the section where the poster has overridden the SaveChanges method (6th code box down on the page). This way you can pass in the UserID and perform your audit and not have to use an event handler.

How do I handle the event SessionSecurityTokenReceived in Global.asax?

I'm trying to set up sliding sessions in WIF and need to handle SessionSecurityTokenReceived.
I'm sure I'm doing something dumb here... but VS2010 keeps on telling me that There is no applicable variable or member in the spot illustrated below. Can anyone point me in the right direction? I've searched high and low for actual samples of how to define the handling of this event, but I can't find a single one.
Global.asax
protected void Application_Start()
{
FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived
+= SessionAuthenticationModule_SessionSecurityTokenReceived;
// ^^^ There is no applicable variable or member
}
void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
DateTime now = DateTime.UtcNow;
DateTime validFrom = e.SessionToken.ValidFrom;
DateTime validTo = e.SessionToken.ValidTo;
if ((now < validTo) &&
(now > validFrom.AddMinutes((validTo.Minute - validFrom.Minute) / 2))
)
{
SessionAuthenticationModule sam = sender as SessionAuthenticationModule;
e.SessionToken = sam.CreateSessionSecurityToken(
e.SessionToken.ClaimsPrincipal,
e.SessionToken.Context,
now,
now.AddMinutes(2),
e.SessionToken.IsPersistent);
e.ReissueCookie = true;
}
else
{
//todo: WSFederationHelper.Instance.PassiveSignOutWhenExpired(e.SessionToken, this.Request.Url);
// this code from: http://stackoverflow.com/questions/5821351/how-to-set-sliding-expiration-in-my-mvc-app-that-uses-sts-wif-for-authenticati
var sessionAuthenticationModule = (SessionAuthenticationModule)sender;
sessionAuthenticationModule.DeleteSessionTokenCookie();
e.Cancel = true;
}
}
I don't think you need the event subscription. Remove the subcription on start and just use
SessionAuthenticationModule_SessionSecurityTokenReceived
ASP.Net will wire that for you. (The module has to be named "SessionAuthenticationModule" and it is by default).
If you are working on sliding sessions, this blog post by Vittorio is pretty good: http://blogs.msdn.com/b/vbertocci/archive/2010/06/16/warning-sliding-sessions-are-closer-than-they-appear.aspx
Instead of defining it in Global.asax, create a new class that inherits SessionAuthenticationModule:
public class CustomAuthenticationModule : SessionAuthenticationModule
{
public CustomAuthenticationModule()
{
this.SessionSecurityTokenReceived += new EventHandler<SessionSecurityTokenReceivedEventArgs>(CustomAuthenticationModule_SessionSecurityTokenReceived);
}
void CustomAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
// Your code
}
}
Then in your web.config, substitute the default SessionAuthentication module with your new module:
<modules>
<add name="SessionAuthenticationModule" type="CustomAuthenticationModule" preCondition="managedHandler"/>
</modules>

Resources