We have one problem where it happen randomly on certain devices which is the OnLocationChanged event cannot be triggered.
LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 30000, 100, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 30000, 100, this);
We also try set a timer, if after a minute, the event didn't trigger, we will try get the last known location, but it still returning null.
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, this);
if (CurrentLocation == null)//network provider
{
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, this);
}
if (CurrentLocation == null)//passive provider
{
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, 0, 0, this);
}
May I know what wrong with my code ?
Edited (Complete Code) :
public class LocationService : Service, ILocationListener
{
public IBinder Binder { get; private set; }
public MainActivity MainAC { get { return m_ac; } set { m_ac = value; } }
public Android.Locations.Location CurrentLocation { get; set; }
public Android.Locations.LocationManager LocationManager { get; set; }
public DateTime LastUpdateTime { get; set; }
public bool IsMockLocation { get; set; }
public string CurrentAddress { get; set; }
public string CurrentCity { get; set; }
private int iUpdateLocationInterval = 30000;// 30sec
private int iUpdateLocationDistance = 100;// 100meter
private int iUpdateLocationInterval_LastKnown = 0;// 0sec
private int iUpdateLocationDistance_LastKnown = 0;// 0meter
private System.Timers.Timer timerBackground = null;
private MainActivity m_ac;
private Lib.GoogleMaps google = new Lib.GoogleMaps();
private bool bUpdateLocationIntervalUnknown = false;
public LocationService()
{
}
#region Override Function
public override void OnCreate()
{
base.OnCreate();
}
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
StartCommandResult result = base.OnStartCommand(intent, flags, startId);
return result;
}
public override void OnDestroy()
{
Binder = null;
if (LocationManager != null)
{
LocationManager.RemoveUpdates(this);
}
base.OnDestroy();
}
public override IBinder OnBind(Intent intent)
{
// Return the communication channel to the service.
this.Binder = new LocalLocationBinder(this);
return this.Binder;
}
#endregion
private void StartBackgroundTimer()
{
timerBackground = new System.Timers.Timer();
timerBackground.Elapsed -= TimerBackground_Elapsed;
timerBackground.Elapsed += TimerBackground_Elapsed;
timerBackground.Interval = 10000;
timerBackground.AutoReset = false;
timerBackground.Enabled = true;
}
private void TimerBackground_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timerBackground.Enabled = false;
try
{
if (CurrentLocation == null)// OnLocationChanged didnt trigger, so get from last known location
{
GetLastKnownLocation();
}
}
catch { }
}
public void GetLastKnownLocation()
{
m_ac.RunOnUiThread(() =>
{
bUpdateLocationIntervalUnknown = true;
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.GpsProvider);
LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
if (CurrentLocation == null)//network provider
{
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
}
if (CurrentLocation == null)//passive provider
{
CurrentLocation = LocationManager.GetLastKnownLocation(LocationManager.PassiveProvider);
LocationManager.RequestLocationUpdates(LocationManager.PassiveProvider, iUpdateLocationInterval_LastKnown, iUpdateLocationDistance_LastKnown, this);
}
if (CurrentLocation != null)
{
UpdateCurrentLocationInterval();
ResolveGPSCoordinates(CurrentLocation);
}
else
{
m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
}
});
}
// Location GPS
public void InitializeLocationManager()
{
try
{
m_ac.RunOnUiThread(() =>
{
try
{
if (LocationManager != null) return;
LocationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
IList<string> acceptableLocationProviders = LocationManager.GetProviders(criteriaForLocationService, true);
if (!LocationManager.IsProviderEnabled(LocationManager.GpsProvider))
{
m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
return;
}
if (acceptableLocationProviders.Any())
{
StartBackgroundTimer();
LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
}
else
{
m_ac.ShowMessageToast(Function.GetLanguage(this, Resource.String.lblGPSLocationIsNotEnabled));
}
}
catch(Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
});
}
catch (Exception ex) { m_ac.ShowMessageToast("ERROR:" + ex.Message); }
}
private void UpdateCurrentLocationInterval()
{
try
{
if (LocationManager != null)
{
bUpdateLocationIntervalUnknown = false ;
LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, iUpdateLocationInterval, iUpdateLocationDistance, this);
}
}
catch { }
}
public void OnLocationChanged(Location location)
{
LastUpdateTime = DateTime.Now;
IsMockLocation = true;
CurrentLocation = location;
CurrentAddress = string.Empty;
CurrentCity = string.Empty;
if (bUpdateLocationIntervalUnknown)
{
UpdateCurrentLocationInterval();
}
if (location.IsFromMockProvider)
{
CurrentLocation = null;
m_ac.UpdateLocationName(CurrentCity);
}
else
{
IsMockLocation = false;
ResolveGPSCoordinates(location);
}
}
private void ResolveGPSCoordinates(Location location)
{
ResolveGPSCoordinatesAwait(location);
}
private async void ResolveGPSCoordinatesAwait(Location location)
{
int iResult = await google.ResolveLatLng(location.Latitude, location.Longitude);
if (iResult == 0)
{
CurrentAddress = google.AddressName;
CurrentCity = google.CityName;
if(CurrentCity == string.Empty)
m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceGetFailure));
else
m_ac.UpdateLocationName(CurrentCity);
}
else if (iResult == -2)
{
m_ac.UpdateLocationName(Function.GetLanguage(m_ac, Resource.String.lblLocationServiceExceedAPIQuota));
}
else
{
if (string.IsNullOrEmpty(google.APIErrorMessage))
{
m_ac.UpdateLocationName("ERROR:" + location.Latitude + "," + location.Longitude );
}
else
{
m_ac.UpdateLocationName(google.APIErrorMessage);
}
}
}
public void OnProviderDisabled(string provider)
{
if (provider.Equals(LocationManager.GpsProvider, StringComparison.InvariantCultureIgnoreCase))
{
LastUpdateTime = DateTime.Now;
IsMockLocation = false;
CurrentLocation = null;
CurrentAddress = string.Empty;
CurrentCity = Function.GetLanguage(m_ac, Resource.String.lblLocationServiceDisable);
m_ac.UpdateLocationName(CurrentCity);
}
}
public void OnProviderEnabled(string provider)
{
UpdateCurrentLocationInterval();
}
public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
{
}
}
public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
MainActivity m_ac = null;
public LocationServiceConnection(MainActivity activity)
{
m_ac = activity;
IsConnected = false;
Binder = null;
}
public bool IsConnected { get; private set; }
public LocalLocationBinder Binder { get; private set; }
public void OnServiceConnected(ComponentName name, IBinder service)
{
Binder = service as LocalLocationBinder;
IsConnected = this.Binder != null;
Binder.Service.MainAC = m_ac;
Binder?.Service.InitializeLocationManager();
}
public void OnServiceDisconnected(ComponentName name)
{
IsConnected = false;
Binder.Service.MainAC = null;
Binder = null;
}
public void GetLastKnownLocation()
{
Binder?.Service.GetLastKnownLocation();
}
}
#region LocalBinder
public class LocalLocationBinder : Binder
{
public LocalLocationBinder(LocationService service)
{
this.Service = service;
}
public LocationService Service { get; private set; }
}
#endregion
Well I would suggest you check if the location services are provided and by that I mean are they turned on if not doing that would solve the issue also what you can do is if these services are not available or you can say are currently declined you can simply use this to check if it's available or not and in that way apply your own code to it which could determine if you continue forward to the maps page or not.
public class LocationEnabled : Fragment
{
public GoogleApiClient googleApiClient;
// static int REQUEST_LOCATION = 199;
public const int MIN_TIME_BW_UPDATES = 1000 * 3;
public const int REQUEST_CHECK_SETTINGS = 9000;
AppCompatActivity _activity;
public LocationEnabled(AppCompatActivity activity)
{
_activity = activity;
}
private bool hasGPSDevice(Context context)
{
LocationManager mgr = (LocationManager)context.GetSystemService(Context.LocationService);
if (mgr == null)
return false;
IList<string> providers = mgr.AllProviders;
if (providers == null)
return false;
return providers.Contains(LocationManager.GpsProvider);
}
private async void enableLoc()
{
if (googleApiClient == null)
{
googleApiClient = new GoogleApiClient.Builder(_activity)
.AddApi(LocationServices.API)
.AddConnectionCallbacks(new CallBackHelper(googleApiClient))
.AddOnConnectionFailedListener(new ConnectionFailedCallBack(_activity)).Build();
googleApiClient.Connect();
LocationRequest locationRequest = LocationRequest.Create();
locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
locationRequest.SetInterval(MIN_TIME_BW_UPDATES);
locationRequest.SetFastestInterval(MIN_TIME_BW_UPDATES/2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.AddLocationRequest(locationRequest);
builder.SetAlwaysShow(true);
LocationSettingsResult locationSettingsResult =
await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, builder.Build());
switch (locationSettingsResult.Status.StatusCode)
{
case LocationSettingsStatusCodes.Success:
Toast.MakeText(_activity, "SUCCESS", ToastLength.Short).Show();
break;
case LocationSettingsStatusCodes.ResolutionRequired:
try
{
locationSettingsResult.Status.StartResolutionForResult(_activity, REQUEST_CHECK_SETTINGS);
}
catch (Exception e)
{
Toast.MakeText(_activity, "CANCEL: " + e.Message, ToastLength.Short).Show();
}
break;
default:
googleApiClient.Disconnect();
break;
}
}
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
LocationManager manager = (LocationManager)_activity.GetSystemService(Context.LocationService);
if (manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
{
Intent intent = new Intent(_activity, typeof(GoogleMapsActivity));
StartActivity(intent);
}
if (!hasGPSDevice(_activity))
{
Toast.MakeText(_activity, "Gps not Supported", ToastLength.Long).Show();
}
if (!manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
{
enableLoc();
}
else
{
}
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return base.OnCreateView(inflater, container, savedInstanceState);
}
}
public class ConnectionFailedCallBack : Java.Lang.Object, GoogleApiClient.IOnConnectionFailedListener
{
Context _context;
public ConnectionFailedCallBack(Context context)
{
_context = context;
}
public void OnConnectionFailed(ConnectionResult result)
{
Toast.MakeText(_context, "Location connection failed.", ToastLength.Short).Show();
}
}
public class CallBackHelper : Java.Lang.Object, GoogleApiClient.IConnectionCallbacks
{
GoogleApiClient googleApiClient;
public CallBackHelper(GoogleApiClient googleApiClient)
{
this.googleApiClient = googleApiClient;
}
public void OnConnected(Bundle connectionHint)
{
}
public void OnConnectionSuspended(int cause)
{
googleApiClient.Connect();
}
}
And get the result on your fragment host activity using this :
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == LocationEnabled.REQUEST_CHECK_SETTINGS)
{
switch (resultCode)
{
case Result.Canceled:
//negative result
break;
case Result.Ok:
//positive result
break;
case Result.FirstUser:
default:
break;
}
}
}
Goodluck!
Related
RelativeLayout :
How Can we write Layout.RaiseChild(View) Method in XAML?
( or )
How can we write in ViewModel?
namespace MatchesProject.ViewModels
{
public class MatchesViewModel : BindableObject
{
private int _lastItemAppearedIdx = 0;
private bool IsLastDirectionWasUp = false;
private bool stackMatchTypesIsVisible { get; set; }
public bool StackMatchTypesIsVisible
{
get => stackMatchTypesIsVisible;
set
{
if (value == stackMatchTypesIsVisible)
return;
stackMatchTypesIsVisible = value;
OnPropertyChanged();
}
}
public ObservableCollection<MatchProfile> MatchesList { get; set; }
public ICommand ItemDisappearingCommand
{
get;
private set;
}
private void ItemDisappearing(object obj)
{
try
{
MatchProfile profile = obj as MatchProfile;
if (MatchesList != null && MatchesList.Contains(profile))
{
if (MatchesList.Contains(profile))
{
var currentIdx = MatchesList.IndexOf(profile);
if (currentIdx > _lastItemAppearedIdx)
{
StackMatchTypesIsVisible = false;
IsLastDirectionWasUp = true;
}
else if (IsLastDirectionWasUp)
{
IsLastDirectionWasUp = false;
StackMatchTypesIsVisible = true;
MessagingCenter.Send(this, "RaiseChild", "");
}
_lastItemAppearedIdx = currentIdx;
}
}
}
catch (Exception) { }
}
public MatchesViewModel()
{
ItemDisappearingCommand = new Command(ItemDisappearing);
MatchesList = new ObservableCollection<MatchProfile>();
BindingContext = MatchesList;
}
}
}
//MatchesPage.xaml.cs
public partial class MatchesPage : ContentPage
{
public MatchesPage()
{
InitializeComponent();
MessagingCenter.Subscribe<MatchesPageViewModel>(this, "RaiseChild", (page) => { relativeCompletePage.RaiseChild(stackMatchTypes); });
}
}
I am using RelativeLayout and inside this more than 2 stack layouts with one Listview. While Scrolling listview, Some cases I need to bring front the StackLayout. That's why I have used MessageCenter. I need to know, Is there have any other better option to fix?
In my project , i want to create a MvxRecyclerView to show all the products which user purchased on particular dates.So i have a main MvxRecyclerView layout and a Adapter class which extends MvxRecyclerAdapter .Inside this MvxRecyclerAdapter , iam creating a layouts which contains MvxRecyclerView which populates all the items based on date.
When i tried to create the adapter, Mvvmcross is not showing the child adapter data since OnCreateViewHolder of the child adapter is throwing error.
Please check My parent Adapter class below:
public class MyRecyler1Adapter: MvxRecyclerAdapter
{
private Activity _activity;
public static int MEETING_TYPE = 0;
public static int DOCUMENTS_TYPE = 1;
public NewResponse _response;
Meeting1Adapter adapter;
Documents1Adapter docadapter;
public List<MeetingDetails> meetingDetailList { get; set; }
public List<DocumentDetails> docDetailsList { get; set; }
public bool btnDocStatus = false;
public NewViewModel viewModel;
public MyRecyler1Adapter(IMvxAndroidBindingContext bindingContext, Activity context, NewResponse response,NewViewModel model)
: base(bindingContext)
{
this._activity = context;
this._response = response;
this.viewModel = model;
}
public override int ItemCount
{
get { return 2; }
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (position == 0 && _response.Meetings != null)
{
var meeting = holder as MeetingsTypeViewHolder;
meeting.txtMeg.Text = "Meeting";_response.Meetings.Meetings[position].MeetingTitle+position);
adapter = new Meeting1Adapter(BindingContext, _activity, _response.Meetings);
meeting.recycle.SetAdapter(adapter);
meetingDetailList = _response.Meetings.Meetings;
}
else if (position == 1 && _response.Documents != null)
{
var documents = holder as DocumentsTypeViewHolder;
documents.txtMsg.Text = "Documents";
docadapter = new Documents1Adapter((IMvxAndroidBindingContext)BindingContext,_activity, _response.Documents);
documents.recycle.SetAdapter(docadapter);
docDetailsList = _response.Documents.Documents;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
switch (viewType)
{
case 0:
if (_response.Meetings != null)
{
var itemBindingContext = new MvxAndroidBindingContext(parent.Context, this.BindingContext.LayoutInflaterHolder);
var id = Resource.Layout.layout1;
itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false);
return new MeetingsTypeViewHolder(itemView, itemBindingContext);
}
case 1:
if (_response.Documents != null)
{
var itemBindingContext = new MvxAndroidBindingContext(parent.Context, this.BindingContext.LayoutInflaterHolder);
var id1 = Resource.Layout.layout2;
itemView = LayoutInflater.From(parent.Context).Inflate(id1, parent, false);
return new DocumentsTypeViewHolder(itemView, itemBindingContext);
}
}
return null;
}
public class MeetingsTypeViewHolder : MvxRecyclerViewHolder
{
public TextView txtMeg { get; private set; }
public MvxRecyclerView recycle { get; set; }
public Button btnShowMore { get; set; }
public MeetingsTypeViewHolder(View itemView, IMvxAndroidBindingContext context) : base(itemView, context)
{
txtMeg = itemView.FindViewById<TextView>(Resource.Id.textView1);
recycle = itemView.FindViewById<MvxRecyclerView>(Resource.Id.rec1);
btnShowMore = itemView.FindViewById<Button>(Resource.Id.btnShowMore);
}
}
public class DocumentsTypeViewHolder : MvxRecyclerViewHolder
{
public TextView txtMsg { get; private set; }
public RecyclerView recycle { get; set; }
public Button btnShowMore { get; set; }
public DocumentsTypeViewHolder(View itemView, IMvxAndroidBindingContext context) : base(itemView, context)
{
txtMsg = itemView.FindViewById<TextView>(Resource.Id.textView1);
recycle = itemView.FindViewById<RecyclerView>(Resource.Id.rec1);
btnShowMore = itemView.FindViewById<Button>(Resource.Id.btnShowMore);
}
}
public override int GetItemViewType(int position)
{
switch (position)
{
case 0:
return MEETING_TYPE;
case 1:
return DOCUMENTS_TYPE;
default:
return -1;
}
}
}
Child adapter sample:
public class Meeting1Adapter: MvxRecyclerAdapter
{
private Activity activity;
public MeetingsMain meetingMain { get; set; }
public Meeting1Adapter(IMvxAndroidBindingContext bindingContext, Activity activity, MeetingsMain meetingsMain)
: base(bindingContext)
{
this.activity = activity;
this.meetingMain = meetingsMain;
}
public void RefreshItems(Object response)
{
if (response is List<ContactDetails>)
meetingMain.Meetings = (List<MeetingDetails>)response;
NotifyDataSetChanged();
}
public override int ItemCount
{
get { return meetingMain.Meetings.Count; }
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var meeting = holder as MeetingsAdapterValueTypeViewHolder;
meeting.txtMeg.Text = meetingMain.Meetings[position].MeetingTitle;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
try
{
var itemBindingContext = new MvxAndroidBindingContext(parent.Context, this.BindingContext.LayoutInflaterHolder);
var id = Resource.Layout.item_layout;
View itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false);
return new MeetingsAdapterValueTypeViewHolder(itemView, itemBindingContext);
}catch(Exception e)
{
Console.WriteLine("Exception in response ## " + e.Message);
}
return null;
}
public class MeetingsAdapterValueTypeViewHolder : MvxRecyclerViewHolder
{
// public ImageView Image { get; private set; }
public TextView txtMeg { get; private set; }
public MeetingsAdapterValueTypeViewHolder(View itemView, IMvxAndroidBindingContext ctxt) : base(itemView,ctxt)
{
txtMeg = itemView.FindViewById<TextView>(Resource.Id.textView);
}
}
}
}
Problem : In the child adapter ,OnCreateViewHolder () method is not calling.
Thanks in advance.
After 2 days in searching the solution ,finally i got the result.
The main thing we should check while loading MvxRecyclerview is
1: MvxRecyclerView.LayoutManager.
2:In Child Adapter,Since we are using MvxRecyclerView,we should use IMvxAndroidBindingContext
and the associated adapter changes like
a:Adapter should extend MvxRecyclerAdapter
b: use MvxRecyclerViewHolder
------------------------------------------Edit Your Adapter in the below mentioned way----
Code change made in MyRecyler1Adapter:
MvxRecyclerView.LayoutManager layoutManager;//Dont use RecyclerView.LayoutManager
Inside the OnBindViewHolder()
layoutManager = new LinearLayoutManager(_activity, LinearLayoutManager.Vertical, false);
meeting.recycle.SetLayoutManager(layoutManager);
Inside Child Adapter:
public class Meeting1Adapter: MvxRecyclerAdapter
{
private Activity activity;
public IMvxAndroidBindingContext bindingCtxt;
protected IMvxAndroidBindingContext BindingContext => bindingCtxt;
public MeetingsMain meetingMain { get; set; }
public Meeting1Adapter(IMvxAndroidBindingContext bindingContext, Activity activity, MeetingsMain meetingsMain)
{
this.bindingCtxt = bindingContext;
this.activity = activity;
this.meetingMain = meetingsMain;
}
----
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
try
{
var itemBindingContext = new MvxAndroidBindingContext(parent.Context, this.BindingContext.LayoutInflaterHolder);
var id = Resource.Layout.item_layout;
View itemView = LayoutInflater.From(parent.Context).Inflate(id, parent, false);
return new MeetingsAdapterValueTypeViewHolder(itemView, itemBindingContext);
// return new MeetingsAdapterValueTypeViewHolder(itemView);
}
catch (Exception e)
{
Console.WriteLine("Exception in response ## " + e.Message);
}
return null;
}
----
}
I recently started getting an error in my App.xaml after installing Blend 4, all my ViewModels now show an error of "Object Reference Not Set To An Instance Of An Object". I uninstalled Blend 4 and the errors went away for a few hours and are now back.
I've checked out every commit I've made till the beginning of the project now and the problem still persists, I am completely baffled. What is going on here? This is causing my windows to throw errors in design mode about being unable to locate resources.
Edit:An Update: Every few times I build the application it changes, this time it changed after changing the binding on a button on a UserControl. Before it was UserListViewModel and SettingViewModel. Now it's SettingsViewModel and MainScreenViewModel.
App.xaml :
<Application x:Class="HelpScoutMetrics.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:HelpScoutMetrics.ViewModel">
<Application.Resources>
<ResourceDictionary>
<vm:MainScreenViewModel x:Key="MainScreenViewModel" />
<vm:SettingsViewModel x:Key="SettingsViewModel" />
<vm:UserListViewModel x:Key="UserListViewModel" />
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatButton.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
ViewModels:
public class MainScreenViewModel : ViewModelBase
{
public MainScreenViewModel()
{
QuickStatistics = new QuickStats();
QuickStatistics.UserQuickStats = new ObservableCollection<UserQuickStat>();
QuickStatistics.UserQuickStats.Add(new UserQuickStat() { Name = "Test", TotalConversations = 93, TotalReplies = 57 });
ApplicationData.MainViewModel = this; // Temp for debug of issues
}
public static Logger logger = LogManager.GetLogger("MainScreenViewModel");
public MainWindow Window { get; set; }
private UserReport m_UserOverall;
public UserReport UserOverall
{
get { return m_UserOverall; }
set { m_UserOverall = value; RaisePropertyChanged("UserOverall"); }
}
private QuickStats m_QuickStatistics;
public QuickStats QuickStatistics
{
get { return m_QuickStatistics; }
set { m_QuickStatistics = value; RaisePropertyChanged("QuickStatistics"); }
}
private DateTime m_SelectedDate;
public DateTime SelectedDate
{
get { return m_SelectedDate; }
set { m_SelectedDate = value; RaisePropertyChanged("SelectedDate"); }
}
private ObservableCollection<DateTime> m_SelectedDates;
public ObservableCollection<DateTime> SelectedDates
{
get { return m_SelectedDates; }
set { m_SelectedDates = value; RaisePropertyChanged("SelectedDates"); }
}
private bool m_EnableLoadQuickStatsButton;
public bool EnableLoadQuickStatsButton
{
get { return m_EnableLoadQuickStatsButton; }
set { m_EnableLoadQuickStatsButton = value; RaisePropertyChanged("EnableLoadQuickStatsButton"); }
}
private bool m_EnableLoadQuickStatsButtonTest = false;
public bool EnableLoadQuickStatsButtonTest
{
get { return m_EnableLoadQuickStatsButtonTest; }
set { m_EnableLoadQuickStatsButtonTest = value; RaisePropertyChanged("EnableLoadQuickStatsButtonTest"); }
}
public void NewUser()
{
QuickStatistics.UserQuickStats.Add(new UserQuickStat() { Name = "Test2", TotalConversations = 953, TotalReplies = 577 });
}
public void OpenSettings()
{
if(Window.SettingsFlyout.IsOpen)
{
Window.SettingsFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Settings Flyout");
}
else
{
SettingsViewModel viewModel = Window.SettingsFlyout.DataContext as SettingsViewModel;
viewModel.MainWindow = Window;
viewModel.LoadSettings();
Window.SettingsFlyout.IsOpen = true;
logger.Log(LogLevel.Info, "Opened Settings Flyout");
}
}
public void OpenUsersList()
{
if(Window.UserListFlyout.IsOpen)
{
Window.UserListFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Users List Flyout");
}
else
{
UserListViewModel viewModel = Window.UserListFlyout.DataContext as UserListViewModel;
UserListView userListView = Window.UserListFlyoutView;
viewModel.UserListView = userListView;
viewModel.MainWindow = Window;
viewModel.SetupFreshViewModel();
Window.UserListFlyout.IsOpen = true;
logger.Log(LogLevel.Info, "Opened Users List Flyout");
}
}
public void OpenLogWindow()
{
int count = ApplicationData.MainLogEntries.LogEvents.Count;
NLogViewerView window = new NLogViewerView();
window.Show();
logger.Log(LogLevel.Info, "Opened Log Window");
EnableLoadQuickStatsButtonTest = true;
}
public void RefreshView()// Temp for debug of issues
{
foreach (string name in MiscMethods.GetPropertyNames(this))
{
RaisePropertyChanged(name);
}
}
}
public class SettingsViewModel : ViewModelBase
{
public SettingsViewModel()
{
SettingsWindowLogic.LoadSettings(this);
}
private static Logger logger = LogManager.GetLogger("SettingsViewModel");
public MainWindow MainWindow { get; set; }
private string m_APIKey;
public string APIKey
{
get { return m_APIKey; }
set
{
m_APIKey = value; TriedToValidateKey = false;
KeyValidationButtonText = "Verify Key";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 213, 213, 213));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
RaisePropertyChanged("APIKey");
}
}
private bool m_SaveAPIKey = true;
public bool SaveAPIKey
{
get { return m_SaveAPIKey; }
set { m_SaveAPIKey = value; RaisePropertyChanged("SaveAPIKey"); }
}
/*====================================================================
* Key Validation & Button
* ==================================================================*/
private bool m_ValidKey;
public bool ValidKey
{
get { return m_ValidKey; }
set
{
m_ValidKey = value;
if(value)
{
KeyValidationButtonText = "Valid!";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 18, 145, 47));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = true;
}
else
{
KeyValidationButtonText = "Invalid";
VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 153, 18, 18));
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
}
RaisePropertyChanged("ValidKey");
}
}
//Will be true when the eky is in process of verification
private bool m_CurrentlyVerifyingKey;
public bool CurrentlyVerifyingKey
{
get { return m_CurrentlyVerifyingKey; }
set
{
if (value)
{
KeyValidationButtonText = "Verifying...";
}
m_CurrentlyVerifyingKey = value;
RaisePropertyChanged("CurrentlyVerifyingKey");
}
}
private bool m_TriedToValidateKey;
public bool TriedToValidateKey
{
get { return m_TriedToValidateKey; }
set { m_TriedToValidateKey = value; RaisePropertyChanged("TriedToValidateKey"); }
}
private string m_KeyValidationButtonText = "Verify Key";
public string KeyValidationButtonText
{
get { return m_KeyValidationButtonText; }
set { m_KeyValidationButtonText = value; RaisePropertyChanged("KeyValidationButtonText"); }
}
private Brush m_VerifyButtonBackground = new SolidColorBrush(Color.FromArgb(255, 213, 213, 213));
public Brush VerifyButtonBackground
{
get { return m_VerifyButtonBackground; }
set { m_VerifyButtonBackground = value; RaisePropertyChanged("VerifyButtonBackground"); }
}
public async void VerifyAPIKey()
{
//Task<Paged<Mailbox>> testPull = new Task<Paged<Mailbox>>(() => client.ListMailboxes());
Task<bool> results = new Task<bool>(() => SettingsWindowLogic.VerifyAPIKey(APIKey));
CurrentlyVerifyingKey = true;
results.Start();
CurrentlyVerifyingKey = false;
if (await results)
{
ValidKey = true;
}
else
{
ValidKey = false;
}
TriedToValidateKey = true;
}
public void SaveSettings()
{
SettingsWindowLogic.SaveSettings(this);
logger.Log(LogLevel.Debug, "Saved Settings");
CloseFlyout();
}
public void LoadSettings()
{
SettingsWindowLogic.LoadSettings(this);
}
public void ResetSettings()
{
APIKey = string.Empty;
SaveAPIKey = false;
ApplicationData.ApplicationSettings.ValidAPIKeyExists = false;
logger.Log(LogLevel.Debug, "Reset Settings");
}
public void CloseFlyout()
{
MainWindow.SettingsFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Settings Flyout");
}
}
public class UserListViewModel : ViewModelBase
{
public UserListViewModel()
{
// LoadUserList();
}
public static Logger logger = LogManager.GetLogger("UserListViewModel");
public MainWindow MainWindow { get; set; }
public UserListView UserListView { get; set; }
private UserList m_UserList;
public UserList UsersList
{
get { return m_UserList; }
set { m_UserList = value; RaisePropertyChanged("UsersList"); }
}
private List<string> m_TestItems;
public List<string> TestItems
{
get { return m_TestItems; }
set { m_TestItems = value; RaisePropertyChanged("TestItems"); }
}
private string m_NewUserName;
public string NewUserName
{
get { return m_NewUserName; }
set { m_NewUserName = value; RaisePropertyChanged("NewUserName"); }
}
private string m_HelpScoutUserListStatus = "Attempting To Load HelpScout Users...";
public string HelpScoutUserListStatus
{
get { return m_HelpScoutUserListStatus; }
set { m_HelpScoutUserListStatus = value; RaisePropertyChanged("HelpScoutUserListStatus"); }
}
private Brush m_HelpScoutUserListStatusColor = new SolidColorBrush(Color.FromArgb(255, 187, 95, 32));
public Brush HelpScoutUserListStatusColor
{
get { return m_HelpScoutUserListStatusColor; }
set { m_HelpScoutUserListStatusColor = value; RaisePropertyChanged("HelpScoutUserListStatusColor"); }
}
private bool m_HelpScoutUserListLoaded;
public bool HelpScoutUserListLoaded
{
get { return m_HelpScoutUserListLoaded; }
set
{
if(value)
{
HelpScoutUserListStatus = UserListWindowLogic.HelpScutUseListStringStatus[0];
HelpScoutUserListStatusColor = UserListWindowLogic.HelpScoutUserListStatusColors[0];
ReverifyUserList();
}
else
{
HelpScoutUserListStatus = UserListWindowLogic.HelpScutUseListStringStatus[1];
HelpScoutUserListStatusColor = UserListWindowLogic.HelpScoutUserListStatusColors[1];
}
m_HelpScoutUserListLoaded = value;
RaisePropertyChanged("HelpScoutUserListLoaded");
}
}
private List<User> m_HelpScoutUsersList;
public List<User> HelpScoutUsersList
{
get { return m_HelpScoutUsersList; }
set { m_HelpScoutUsersList = value; RaisePropertyChanged("HelpScoutUsersList"); }
}
private List<string> m_HelpScoutUsersListStrings = new List<string>();
public List<string> HelpScoutUsersListStrings
{
get { return m_HelpScoutUsersListStrings; }
set { m_HelpScoutUsersListStrings = value; RaisePropertyChanged("HelpScoutUsersListStrings"); }
}
public async void RetrieveHelpScoutUserList()
{
Task<List<User>> task = new Task<List<User>>(() => UserListWindowLogic.RetrieveHelpScoutUserList());
task.Start();
List<User> usersList = await task;
if(usersList != null)
{
HelpScoutUsersList = usersList;
foreach(User userObject in usersList)
{
HelpScoutUsersListStrings.Add(userObject.Name);
}
HelpScoutUserListLoaded = true;
}
else
{
HelpScoutUserListLoaded = false;
}
}
private User MatchUserID(string name)
{
return UserListWindowLogic.FindUserByName(name, HelpScoutUsersList);
}
public void RemoveUser()
{
User user = UserListView.NamesDataGrid.SelectedItem as User;
UsersList.Users.Remove(user);
logger.Log(LogLevel.Debug, "Removed User: " + user.Name);
}
public void AddUser()
{
if (!string.IsNullOrEmpty(NewUserName) && HelpScoutUserListLoaded)
{
User user = MatchUserID(NewUserName);
if(user != null)
{
UsersList.Users.Add(user);
logger.Log(LogLevel.Debug, "Added New Valid User: " + user.Name);
}
else
{
UsersList.Users.Add(new User() { Name = NewUserName });
logger.Log(LogLevel.Debug, "Added New User: " + NewUserName);
}
}
else
{
UsersList.Users.Add(new User() { Name = NewUserName });
logger.Log(LogLevel.Debug, "Added New User: " + NewUserName);
}
ClearNewUserNameTextBox();
}
//Clears the new user textbox
public void ClearNewUserNameTextBox()
{
NewUserName = string.Empty;
}
public void SetupFreshViewModel()
{
m_HelpScoutUserListLoaded = false;
HelpScoutUserListStatusColor = new SolidColorBrush(Color.FromArgb(255, 187, 95, 32));
HelpScoutUserListStatus = "Attempting To Load HelpScout Users...";
LoadUserList();
RetrieveHelpScoutUserList();
}
public void SaveUserList()
{
UserListWindowLogic.SaveUserList(this);
logger.Log(LogLevel.Debug, "Saved Users List");
CloseFlyout();
}
public void ReverifyUserList()
{
UserListWindowLogic.CheckUserListValidity(HelpScoutUsersList);
LoadUserList();
}
public void LoadUserList()
{
UserList userList;
if(ApplicationData.Users != null)
{
userList = XMLSerialize<UserList>.CopyData(ApplicationData.Users);
}
else
{
userList = UserListWindowLogic.CreateNewUserList();
}
UsersList = userList;
}
public void ResetUserList()
{
UsersList = new UserList();
logger.Log(LogLevel.Debug, "Reset Users List");
}
public void CloseFlyout()
{
MainWindow.UserListFlyout.IsOpen = false;
logger.Log(LogLevel.Info, "Closed Users List Flyout");
}
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool IsInDesignMode
{
get
{
var prop = DesignerProperties.IsInDesignModeProperty;
return (bool)DependencyPropertyDescriptor
.FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
}
}
You need to make sure that the constructor of your view model can be initialized in design time, if you're using some dependencies in the constructor that cannot be initialized in design time, you need to put it inside the condition block: if(!IsInDesignMode)
I am working on WPF MVVM Application.
I have a view (Employee) shown inside Main Region
this view (Employee) contain scoped regions within it where I show/display Employee details views. Its working fine till this place New, display update and delete
But I am facing strange problem with New Operation
If I create view for first time and click on new , Object got initialized my Data Object CurrentEmployee.
But If I load some previous data its been shown properly and then I click on New, my Data Object CurrentEmployee took too much time and finaly crash. the problem so far traced is in OnPropertyChange
Thanks any sort of help/suggestion is highly appriciated
whole code of view model
[Export(typeof(ITB_EMPLOYEEViewModel))]
public class TB_EMPLOYEEViewModel : ViewModelBase, ITB_EMPLOYEEViewModel
{
private TB_EMPLOYEE _currentTB_EMPLOYEE;
IRegionManager RefRegionManager;
IEventAggregator _eventAggregator;
[ImportingConstructor]
public TB_EMPLOYEEViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
: base(regionManager, eventAggregator)
{
RefRegionManager = regionManager;
HeaderInfo = "TB_EMPLOYEE";
_eventAggregator = eventAggregator;
OpenImageDialog = new DelegateCommand(OpenDialog, CanOpenDialog);
//CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
//empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
//UnLoadChild();
//LoadChild();
New();
}
private void LoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
var empHistory = ServiceLocator.Current.GetInstance<uTB_EMPLOYEE_HISTORYView>();
if (region.GetView("EmployeeHistory") == null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Add(empHistory, "EmployeeHistory");
}
if (CurrentTB_EMPLOYEE != null && CurrentTB_EMPLOYEE.ID!=0)
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel(CurrentTB_EMPLOYEE.ID);
}
else
{
empHistoryVM = new TB_EMPLOYEE_HISTORYViewModel();
}
empHistory.ViewModel = empHistoryVM;
region.Activate(region.GetView("EmployeeHistory"));
}
}
private void UnLoadChild()
{
IRegionManager regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
if (regionManager.Regions.ContainsRegionWithName(RegionNames.EmployeeDetail))
{
IRegion region = regionManager.Regions[RegionNames.EmployeeDetail];
if (region.GetView("EmployeeHistory") != null)// .Views.OfType<uTB_EMPLOYEE_HISTORYView>().SingleOrDefault() == null)
{
region.Remove(region.GetView("EmployeeHistory"));
}
}
}
#region DetailUserControls ViewModels
private TB_EMPLOYEE_HISTORYViewModel empHistoryVM;
#endregion DetailUserControls ViewModels
#region Commands
public DelegateCommand OpenImageDialog { get; set; }
private bool CanOpenDialog() { return true; }
public void OpenDialog()
{
using (OpenFileDialog objOpenFile = new OpenFileDialog())
{
if (objOpenFile.ShowDialog() == DialogResult.OK)
{
_currentTB_EMPLOYEE.PHOTO = Utility.ConvertImageToByte(objOpenFile.FileName);
CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO);
}
}
}
public override void ShowSelectedRow()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uTB_EMPLOYEEView>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uTB_EMPLOYEEView));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uTB_EMPLOYEEView");
UnLoadChild();
LoadChild();
}
public override void RegisterCommands()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
GlobalCommands.ShowAllCommand.RegisterCommand(ShowAllCommand);
GlobalCommands.SaveCommand.RegisterCommand(SaveCommand);
GlobalCommands.NewCommand.RegisterCommand(NewCommand);
GlobalCommands.DeleteCommand.RegisterCommand(DeleteCommand);
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
GlobalCommands.CloseCommand.RegisterCommand(CloseCommand);
GlobalCommands.SearchCommand.RegisterCommand(SearchCommand);
GlobalCommands.PrintCommand.RegisterCommand(PrintCommand);
GlobalCommands.ExportToExcelCommand.RegisterCommand(ExportToExcelCommand);
GlobalCommands.ExportToWordCommand.RegisterCommand(ExportToWordCommand);
GlobalCommands.ExportToPDFCommand.RegisterCommand(ExportToPDFCommand);
}
}
}
public override bool CanShowAll()
{
return IsActive;
}
public override void ShowAll()
{
HeaderInfo = "TB_EMPLOYEE List";
if (RefRegionManager.Regions[RegionNames.MainRegion].Views.OfType<uListTB_EMPLOYEE>().SingleOrDefault() == null)
{
RefRegionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(uListTB_EMPLOYEE));
}
RefRegionManager.RequestNavigate(RegionNames.MainRegion, "uListTB_EMPLOYEE");
UpdateListFromDB();
}
public override void UpdateListFromDB()
{
using (DBMain objDBMain = new DBMain())
{
TB_EMPLOYEEList = objDBMain.EntTB_EMPLOYEE.ToList<TB_EMPLOYEE>();
}
}
public override void New()
{
this.CurrentTB_EMPLOYEE = new TB_EMPLOYEE();
UnLoadChild();
LoadChild();
}
public override void Close()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault().ToString() == "WPFApp.View.uTB_EMPLOYEEView")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault());
UnLoadChild();
}
}
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault().ToString() == "WPFApp.ListView.uListTB_EMPLOYEE")
{
RefRegionManager.Regions[RegionNames.MainRegion].Remove(RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault());
}
}
}
public override void Delete()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
ConfirmationDialog confirmationMessage = new ConfirmationDialog("Do You want to Delete this Record of [TB_EMPLOYEE]", "Confirmation Dialog Box");
confirmationMessage.AllowsTransparency = true;
DoubleAnimation animFadeIn = new DoubleAnimation();
animFadeIn.From = 0;
animFadeIn.To = 1;
animFadeIn.Duration = new Duration(TimeSpan.FromSeconds(1));
confirmationMessage.BeginAnimation(Window.OpacityProperty, animFadeIn);
confirmationMessage.ShowDialog();
if (confirmationMessage.DialogValue)
{
if (CurrentTB_EMPLOYEE.ID != 0)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = EntityState.Deleted;
objDBMain.SaveChanges();
OnPropertyChanged("CurrentTB_EMPLOYEE");
CurrentTB_EMPLOYEE = null;
}
}
else
{
CurrentTB_EMPLOYEE = null;
}
UpdateListFromDB();
}
}
}
}
public override bool CanSave()
{
return IsActive;
}
public override void Save()
{
if (RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uTB_EMPLOYEEView>().FirstOrDefault() != null ||
RefRegionManager.Regions[RegionNames.MainRegion].ActiveViews.OfType<uListTB_EMPLOYEE>().FirstOrDefault() != null)
{
if (CurrentTB_EMPLOYEE != null)
{
using (DBMain objDBMain = new DBMain())
{
objDBMain.Entry<TB_EMPLOYEE>(CurrentTB_EMPLOYEE).State = CurrentTB_EMPLOYEE.ID == 0 ? EntityState.Added : EntityState.Modified;
foreach (TB_EMPLOYEE_HISTORY obj in empHistoryVM.TB_EMPLOYEE_HISTORYList)
{
objDBMain.Entry<TB_EMPLOYEE_HISTORY>(obj).State = EntityState.Added;
CurrentTB_EMPLOYEE.TB_EMPLOYEE_HISTORYList.Add(obj);
objDBMain.SaveChanges();
}
}
UpdateListFromDB();
}
}
}
#endregion Commands
#region Properties
private ImageSource _CurrentEmployeeImage;
public ImageSource CurrentEmployeeImage { get { return _CurrentEmployeeImage; } private set { _CurrentEmployeeImage = value; OnPropertyChanged("CurrentEmployeeImage"); } }//OnPropertyChanged("CurrentTB_EMPLOYEE");
public string CurrentEmployeeImagePath { get; set; }
private List<TB_EMPLOYEE> _TB_EMPLOYEEList;
public List<TB_EMPLOYEE> TB_EMPLOYEEList
{
get { return _TB_EMPLOYEEList; }
set
{
_TB_EMPLOYEEList = value;
RaisePropertyChanged();
}
}
public TB_EMPLOYEE CurrentTB_EMPLOYEE
{
get { return _currentTB_EMPLOYEE; }
set
{
_currentTB_EMPLOYEE = value;
if (_currentTB_EMPLOYEE != null && _currentTB_EMPLOYEE.PHOTO != null)
{ CurrentEmployeeImage = Utility.ConvertByteToImage(_currentTB_EMPLOYEE.PHOTO); }
//OnPropertyChanged("CurrentTB_EMPLOYEE");
RaisePropertyChanged();
}
}
private IList<TB_SETUP_RELIGION> _listRELIGION;
public IList<TB_SETUP_RELIGION> listRELIGION
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listRELIGION = objDBMain.EntTB_SETUP_RELIGION.ToList();
}
return _listRELIGION;
}
}
private IList<string> _listTitles;
public IList<string> listTitles
{
get
{
if (_listTitles == null)
{
_listTitles = new List<string>();
_listTitles.Add("Mr");
_listTitles.Add("Miss");
_listTitles.Add("Mrs");
//_listTitles.Add("Mr");
}
return _listTitles;
}
}
private IList<TB_SETUP_GENDER> _listGENDER;
public IList<TB_SETUP_GENDER> listGENDER
{
get
{
using (DBMain objDBMain = new DBMain())
{
_listGENDER = objDBMain.EntTB_SETUP_GENDER.ToList();
}
return _listGENDER;
}
}
#endregion Properties
#region FormNavigation
private bool isActive;
public override bool IsActive
{
get
{
return this.isActive;
}
set
{
isActive = value;
OnIsActiveChanged();
}
}
protected virtual void OnIsActiveChanged()
{
if (IsActive)
{
_eventAggregator.GetEvent<SubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"Subscribtion to Events" } });
}
else
{
_eventAggregator.GetEvent<UnSubscribeToEvents>().Publish(new Dictionary<string, string>() { { "View", "TB_EMPLOYEE" }, { "FileName", #"UnSubscribtion to Events" } });
}
UnRegisterCommands();
RegisterCommands();
}
public override bool IsNavigationTarget(NavigationContext navigationContext)
{
this.isActive = true;
return this.isActive;
}
public override void OnNavigatedFrom(NavigationContext navigationContext)
{
UnRegisterCommands();
this.isActive = false;
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
HeaderInfo = "TB_EMPLOYEE";
this.isActive = true;
RegisterCommands();
}
#endregion FormNavigation
}
Finally solve the problem. I was using single Object CurrentTB_EMPLOYEE as current data for my form and ActiveData Item of another List view. this view model handle both form and list views. I just remove CurrentTB_EMPLOYEE from ActiveData Item to my list view and bind them through another object.. when CurrentTB_EMPLOYEE become responsible only for form its start working properly. Thanks every one for your precious time.
Im haveing some xml that have this structure
<Person Id="*****" Name="*****">
<AccessControlEntries>
<AccessControlEntry Id="*****" Name="****"/>
</AccessControlEntries>
<AccessControls />
<IdentityGroups>
<IdentityGroup Id="****" Name="*****" />
</IdentityGroups></Person>
and i also have this entities
[DataContract(IsReference = true)]
public abstract class EntityBase
{
protected bool serializing;
[DataMember(Order = 1)]
[XmlAttribute()]
public string Id { get; set; }
[DataMember(Order = 2)]
[XmlAttribute()]
public string Name { get; set; }
[OnDeserializing()]
public void OnDeserializing(StreamingContext context)
{
this.Initialize();
}
[OnSerializing()]
public void OnSerializing(StreamingContext context)
{
this.serializing = true;
}
[OnSerialized()]
public void OnSerialized(StreamingContext context)
{
this.serializing = false;
}
public abstract void Initialize();
public string ToXml()
{
var settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
var sb = new System.Text.StringBuilder();
using (var writer = System.Xml.XmlWriter.Create(sb, settings))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
}
return sb.ToString();
}
}
[DataContract()]
public abstract class Identity : EntityBase
{
private EntitySet<AccessControlEntry> accessControlEntries;
private EntitySet<IdentityGroup> identityGroups;
public Identity()
{
Initialize();
}
[DataMember(Order = 3, EmitDefaultValue = false)]
[Association(Name = "AccessControlEntries")]
public EntitySet<AccessControlEntry> AccessControlEntries
{
get
{
if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false)))
{
return null;
}
return accessControlEntries;
}
set
{
accessControlEntries.Assign(value);
}
}
[DataMember(Order = 4, EmitDefaultValue = false)]
[Association(Name = "IdentityGroups")]
public EntitySet<IdentityGroup> IdentityGroups
{
get
{
if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false)))
{
return null;
}
return identityGroups;
}
set
{
identityGroups.Assign(value);
}
}
private void attach_accessControlEntry(AccessControlEntry entity)
{
entity.Identities.Add(this);
}
private void dettach_accessControlEntry(AccessControlEntry entity)
{
entity.Identities.Remove(this);
}
private void attach_IdentityGroup(IdentityGroup entity)
{
entity.MemberIdentites.Add(this);
}
private void dettach_IdentityGroup(IdentityGroup entity)
{
entity.MemberIdentites.Add(this);
}
public override void Initialize()
{
this.accessControlEntries = new EntitySet<AccessControlEntry>(
new Action<AccessControlEntry>(this.attach_accessControlEntry),
new Action<AccessControlEntry>(this.dettach_accessControlEntry));
this.identityGroups = new EntitySet<IdentityGroup>(
new Action<IdentityGroup>(this.attach_IdentityGroup),
new Action<IdentityGroup>(this.dettach_IdentityGroup));
}
}
[XmlType(TypeName = "AccessControlEntry")]
public class AccessControlEntry : EntityBase, INotifyPropertyChanged
{
private EntitySet<Service> services;
private EntitySet<Identity> identities;
private EntitySet<Permission> permissions;
public AccessControlEntry()
{
services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service));
identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity));
permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission));
}
[DataMember(Order = 3, EmitDefaultValue = false)]
public EntitySet<Permission> Permissions
{
get {
if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false)))
{
return null;
}
return permissions;
}
set
{
permissions.Assign(value);
}
}
[DataMember(Order = 4, EmitDefaultValue = false)]
public EntitySet<Identity> Identities
{
get
{
if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false)))
{
return null;
}
return identities;
}
set
{
identities.Assign(identities);
}
}
[DataMember(Order = 5, EmitDefaultValue = false)]
public EntitySet<Service> Services
{
get
{
if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false)))
{
return null;
}
return services;
}
set
{
services.Assign(value);
}
}
private void attach_Permission(Permission entity)
{
entity.AccessControlEntires.Add(this);
}
private void dettach_Permission(Permission entity)
{
entity.AccessControlEntires.Remove(this);
}
private void attach_Identity(Identity entity)
{
entity.AccessControlEntries.Add(this);
}
private void dettach_Identity(Identity entity)
{
entity.AccessControlEntries.Remove(this);
}
private void attach_Service(Service entity)
{
entity.AccessControlEntries.Add(this);
}
private void dettach_Service(Service entity)
{
entity.AccessControlEntries.Remove(this);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
#endregion
public override void Initialize()
{
throw new NotImplementedException();
}
}
[DataContract()]
[XmlType(TypeName = "Person")]
public class Person : Identity
{
private EntityRef<Login> login;
[DataMember(Order = 3)]
[XmlAttribute()]
public string Nombre { get; set; }
[DataMember(Order = 4)]
[XmlAttribute()]
public string Apellidos { get; set; }
[DataMember(Order = 5)]
public Login Login {
get
{
return login.Entity;
}
set
{
var previousValue = this.login.Entity;
if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false)))
{
if ((previousValue != null))
{
this.login.Entity = null;
previousValue.Person = null;
}
this.login.Entity = value;
if ((value != null))
value.Person = this;
}
}
}
public override void Initialize()
{
base.Initialize();
}
}
[DataContract()]
[XmlType(TypeName = "Login")]
public class Login : EntityBase
{
private EntityRef<Person> person;
[DataMember(Order = 3)]
public string UserID { get; set; }
[DataMember(Order = 4)]
public string Contrasena { get; set; }
[DataMember(Order = 5)]
public Domain Dominio
{
get;
set;
}
public Person Person
{
get
{
return person.Entity;
}
set
{
var previousValue = this.person.Entity;
if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false)))
{
if ((previousValue != null))
{
this.person.Entity = null;
previousValue.Login = null;
}
this.person.Entity = value;
if ((value != null))
value.Login = this;
}
}
}
public override void Initialize()
{
throw new NotImplementedException();
}
}
[DataContract()]
[XmlType(TypeName = "IdentityGroup")]
public class IdentityGroup : Identity
{
private EntitySet<Identity> memberIdentities;
public IdentityGroup()
{
Initialize();
}
public override void Initialize()
{
this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity));
}
[DataMember(Order = 3, EmitDefaultValue = false)]
[Association(Name = "MemberIdentities")]
public EntitySet<Identity> MemberIdentites
{
get
{
if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false)))
{
return null;
}
return memberIdentities;
}
set
{
memberIdentities.Assign(value);
}
}
private void attach_Identity(Identity entity)
{
entity.IdentityGroups.Add(this);
}
private void dettach_Identity(Identity entity)
{
entity.IdentityGroups.Remove(this);
}
}
[DataContract()]
[XmlType(TypeName = "Group")]
public class Group : Identity
{
public override void Initialize()
{
throw new NotImplementedException();
}
}
but the ToXml() response something like this
<Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person>
but what i want is something like this
<Person Id="****" Name="***" Nombre="****">
<AccessControlEntries/>
<IdentityGroups/>
</Person>
Try using the following Serialize method:
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(writer, this, ns);