public void UpdateNetworkStatus() {
            try
            {
                ActivityController++;
                _state = DataAccessLayer.NetworkState.Unknown;

                // Retrieve the connectivity manager service
                var connectivityManager = (ConnectivityManager)
                    Application.Context.GetSystemService (
                        Context.ConnectivityService);

                // Check if the network is connected or connecting.
                // This means that it will be available, 
                // or become available in a few seconds.
                var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;

                Android.Content.Res.Resources res = _activity.Resources;
                NotificationManager notificationManager = (NotificationManager) _activity.GetSystemService (
                    Android.Content.Context.NotificationService);

                Android.Net.Uri uri = null;


                if (activeNetworkInfo == null)
                {

                    // Send the two notification: 
                    // 1. There is no connection.
                    // 2. The user is offline

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    Notification.Builder builder = new Notification.Builder (_activity)
                        .SetSmallIcon (Resource.Drawable.ic_network_disconnected)
                        .SetAutoCancel (false)
                        .SetSound (uri)
                        //.SetVibrate (new long[] { 1000, 1000, 1000, 1000, 1000 })
                        .SetLights (54, 3000, 5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.NetworkDisconnected))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  +  _activity.Resources.GetString(Resource.String.Disconnected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Disconnected));
                    Notification notification = builder.Build();
                    notificationManager.Notify (1, notification);

                    builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_action_offline)
                        .SetAutoCancel (false)
                        .SetSound (Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification))
                        .SetLights (54,3000,5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.UserOffline))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + "Offline")
                        .SetTicker (_activity.Resources.GetString(Resource.String.UserOffline));
                    notification = builder.Build();
                    notificationManager = (NotificationManager) _activity.GetSystemService (
                        Android.Content.Context.NotificationService);
                    notificationManager.Notify (2, notification);


                    /*AlertDialog a = new  AlertDialog.Builder (this)
                            .SetTitle ("NETWORK")
                            .SetMessage ("No Network")
                            .SetPositiveButton (Android.Resource.String.Ok, delegate (object o, DialogClickEventArgs e) {})
                            .Create();
                        a.Show ();*/
                    _state =  DataAccessLayer.NetworkState.Disconnected;
                    return;
                }

                if (activeNetworkInfo.IsConnectedOrConnecting) {

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    Notification.Builder builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_network_connected)
                        .SetAutoCancel (false)
                        .SetSound (uri)

                        //.SetVibrate (new long[] { 10, 0 })
                        .SetLights (54,3000,5)
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + _activity.Resources.GetString(Resource.String.Connected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Connected));



                    //.SetContentIntent (GetDialogPendingIntent ("Connected."));

                    // According to the status of the user, adjust the text of the notification
                    if (MainActivity.User.NetworkStatus == DataAccessLayer.NetworkState.Disconnected)
                        builder.SetContentText( _activity.Resources.GetString(Resource.String.NetworkConnected));
                    else
                        builder.SetContentText( _activity.Resources.GetString(Resource.String.NetworkConnected));

                    Notification notification = builder.Build();

                    notificationManager.Notify (1, notification);

                    // Now that we know it's connected, determine if we're on WiFi or something else.
                    _state = activeNetworkInfo.Type == ConnectivityType.Wifi ?
                        DataAccessLayer.NetworkState.ConnectedWifi : DataAccessLayer.NetworkState.ConnectedData;

                    // First check if there is any unsync data in the SQLite database
                    offlineTasks =  BusinessLayer.Task.HasNewOfflineTasks();

                    // If there is and the user is online then ask for synchronizing the data
                    if (offlineTasks != 0 &&MainActivity.User.NetworkStatus  != DataAccessLayer.NetworkState.Disconnected)
                    {
                        // Ask the user if he wants to upload the unsynchronized data
                        var alertdialog = new AlertDialog.Builder(this._activity);
                        alertdialog.SetIconAttribute(Android.Resource.Attribute.AlertDialogIcon);
                        alertdialog.SetTitle(Resource.String.OfflineData);
                        alertdialog.SetPositiveButton(Resource.String.Yes, OfflineDataYesClicked);
                        alertdialog.SetNegativeButton(Resource.String.No, OfflineDataNoClicked);

                        // Set the right Message
                        if (offlineTasks == 1)
                            alertdialog.SetMessage(string.Format(_activity.GetString(Resource.String.AskUpload), offlineTasks));
                        else
                            alertdialog.SetMessage(string.Format(_activity.GetString(Resource.String.AskUploads), offlineTasks));
                        alertdialog.Show();
                    }


                } 
                else 
                {

                    if (ActivityController > 1)
                        uri = Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification);

                    // Send the two notification: 
                    // 1. There is no connection.
                    // 2. The user is offline

                    Notification.Builder builder = new Notification.Builder (_activity)

                        .SetSmallIcon (UI.Resource.Drawable.ic_network_disconnected)
                        .SetAutoCancel (false)
                        .SetSound (uri)
                        //.SetVibrate (new long[] { 1000, 1000, 1000, 1000, 1000 })
                        .SetLights (54, 3000, 5)
                        .SetContentText (_activity.Resources.GetString(Resource.String.NetworkDisconnected))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + _activity.Resources.GetString(Resource.String.Disconnected))
                        .SetContentIntent (GetDialogPendingIntent ())
                        .SetTicker (_activity.Resources.GetString(Resource.String.Disconnected));
                    //.SetContentIntent (GetDialogPendingIntent ("Disconnected"));

                    Notification notification = builder.Build();

                    notificationManager.Notify (1, notification);


                    builder = new Notification.Builder (_activity)
                        .SetSmallIcon (UI.Resource.Drawable.ic_action_offline)
                        .SetAutoCancel (false)
                        .SetSound (Android.Media.RingtoneManager.GetDefaultUri ( Android.Media.RingtoneType.Notification))
                        .SetLights (54,3000,5)
                        .SetContentText ( _activity.Resources.GetString(Resource.String.UserOffline))
                        .SetContentTitle (_activity.Resources.GetString(Resource.String.AppName)  + " - "  + "Offline")
                        .SetTicker (_activity.Resources.GetString(Resource.String.UserOffline));
                    notification = builder.Build();
                    notificationManager = (NotificationManager) _activity.GetSystemService (
                        Android.Content.Context.NotificationService);
                    notificationManager.Notify (2, notification);


                    /*AlertDialog a = new  AlertDialog.Builder (this)
                            .SetTitle ("NETWORK")
                            .SetMessage ("Disconnected")
                            .SetPositiveButton (Android.Resource.String.Ok, delegate (object o, DialogClickEventArgs e) {})
                            .Create();*/

                    _state = DataAccessLayer.NetworkState.Disconnected;
                }
            }
            catch(Exception ex)
            {
                DataAccessLayer.ExceptionWriter.WriteLogFile(ex);
            }


        }
        /// <summary>
        /// Purpose : Validate -> Authenticate -> Save Url -> if successfull -> Run the main control
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        private async void Login (object sender , EventArgs e)
        {
            try
            {


                // Run the progressbar
                hud = new MTMBProgressHUD (this.View){DimBackground = true, LabelText = LocalString.GetString("Authenticating")};
                this.View.AddSubview (hud);
                hud.Show(true);

                // First dismiss the keyboard
                TfUsername.ResignFirstResponder();
                TfPassword.ResignFirstResponder();
                TfServerIP.ResignFirstResponder();
                TfMandant.ResignFirstResponder();

                // First Validate the controls
                if (Validate() == false)
                    return ;

                // First get the URL and set it to the main URL
                DataAccessLayer.Utilities.ServerIP = TfServerIP.Text;
                BusinessLayer.User.SetUrl(TfServerIP.Text);

                // Check the Network status
                networkStatus = GetNetworkStatus();

                // Then authenticate the user by the values of the controls
                if (await Authenticate(TfUsername.Text, TfPassword.Text, TfMandant.Text,networkStatus,  SwitchOffline.On ) == false)
                    return ;
                
                // if authenticated and the user online, save the user in the offline database
                // the offline user is only saved in the offline database anyway
                if (SwitchOffline.On == false)
                    Application._user.SaveOnlineUserData();

                // Now check if this device has a license to use the app
                if (await this.ValidateLicenseAsync() == false)
                    return ;

                if (_vcSettings != null)
                {
                    _loggedSuccessfully = true;
                    DismissViewController(true,null);
                    return ;
                }

                if (tabController == null)
                    tabController = Storyboard.InstantiateViewController<MainTabController>();

                Theme.TransitionController(tabController);

            }
            catch (Exception ex)
            {
                DataAccessLayer.ExceptionWriter.WriteLine(ex.Message, ex.StackTrace);
            }
            finally
            {
                // finallize the progressbar
                hud.RemoveFromSuperview();
                hud = null;


            }

        }
        async private void  onlineElement_ValueChanged( object sender , EventArgs e)
        {

            if (onlineElement.Value == false)
            {
                MessageBox.ShowMessage(this.View, LocalString.GetString("UserOffline"));
                Application._user.NetworkStatus = DataAccessLayer.NetworkState.Disconnected;
            }
            else
            {

                if (Application._networkstate == DataAccessLayer.NetworkState.Disconnected)
                {
                    onlineElement.Value = false;
                    return;
                }

                // First save the current setting -> We need them if the connection to the new server fails -> then we have to reset to these settings
                CurrentURL = DataAccessLayer.Utilities.ServerIP;
                CurrentNetworkState = Application._networkstate;

                // Just run the Login ViewController if the user has never logged online before
                if (string.IsNullOrEmpty(Application._user.IdSession))
                {
                    Application._user.NetworkStatus = Application._networkstate;
                    DataAccessLayer.Utilities.ServerIP = urlElement.Value.ToString();

                    // Create a VCSelectAnsprechpartnern dialog
                    loginController = Storyboard.InstantiateViewController<LoginController>();
                    loginController.VCSettings = this;
                    loginController.ModalPresentationStyle = UIModalPresentationStyle.FormSheet;

                    PresentViewController(loginController, true, null);

                    return;
                    // After it has finished the LoginController calls UpdateLoggedValues

                }
                else
                {
                    if (await TestConnection() == true)
                    {
                        // connection available and the user is online
                        Application._user.NetworkStatus = Application._networkstate;
                        MessageBox.ShowMessage(this.View, LocalString.GetString("UserOnline"));

                    }
                    else
                    {
                        // No connection
                        onlineElement.Value = false;
                        Application._user.NetworkStatus = DataAccessLayer.NetworkState.Disconnected;

                        MessageBox.ShowErrorMessage(this.View, LocalString.GetString("ConnectionFailedTitle"));

                    }
                }

                if (Application._user.NetworkStatus != DataAccessLayer.NetworkState.Disconnected)
                    offlineTasks = BusinessLayer.Task.HasNewOfflineTasks();

                // Ask to upload any unsync data if the user is online 
                if (offlineTasks != 0 && Application._user.NetworkStatus != DataAccessLayer.NetworkState.Disconnected)
                {
                    OfflineDataSection.RemoveRange(1,3);
                    string UploadLabel = "";
                    if (offlineTasks != 0)
                        UploadLabel = "  (" + LocalString.GetString("UnsynchronizedData_") + " " + offlineTasks.ToString() + ")";
                    uploadDataElement = new ImageStringElement(LocalString.GetString("UploadData") + UploadLabel,UIImage.FromFile("Images/ic_action_upload.png"));
                    uploadDataElement.Tapped += delegate()
                        {
                            UploadData();
                        };

                    OfflineDataSection.Add(uploadDataElement);
                    OfflineDataSection.Add(clearofflineDataElement);

                    UploadData();
                }
            }

        }
Exemplo n.º 4
0
		protected override void OnCreate(Bundle savedInstanceState)
		{
			// Set the main flag for the activity, so that the blank Launcher knows this activity is running
			isRunning = true;

            progress_handler = new ProgressHandler (this);

			// Create the broadcast receiver and bind the event handler
			// so that the app gets updates of the network connectivity status
			_networkmonitor = new NetworkStatusMonitor (this);
			if (_broadcastReceiver == null)
			{
				// Set the ActivityController to 0 -> That has the effect that the sound won't be raised
				// This is just the first time when the activity starts, after that this counter increments
				// And doesn't prevent the sound
				NetworkStatusMonitor.ActivityController = 0;
				_broadcastReceiver = new NetworkStatusBroadcastReceiver ();
				_broadcastReceiver.ConnectionStatusChanged += _networkmonitor.OnNetworkStatusChanged;

				// Register the broadcast receiver
				Application.Context.RegisterReceiver (_broadcastReceiver, 
					new IntentFilter (ConnectivityManager.ConnectivityAction));

			}

			// Keep the ActivityController to 0 because we want to call the UpdateNetworkStatus on our own
			// And the sound shouldn't be raised
			UI.MainActivity._networkstate = _networkmonitor.GetNetworkStatus();


			base.OnCreate(savedInstanceState);

			// The SQLite Utility will be initialized
			// -> Open Connection -> Create Database -> Create Security and Object tables
			//DataAccessLayer.SQLiteUtilities.Initialize ();

			// Set the classname which is by default Kunden
			_className = "Kunden";

			// Set the layout
			SetContentView(Resource.Layout.ActivityMain);

            // First run the UtilityClasses
            BusinessLayer.UtilityClasses.FillUtilityClasses(BaseContext.Resources.Configuration.Locale.Language.ToUpper(), _user);

			// Run our lovely fragment which is by default the FrgGeneral
            fragment = new PersonGeneralFragment(Resource.Layout.FrgPersonGeneral,this,null);
			FragmentManager
				.BeginTransaction()
				.Replace(Resource.Id.frameContent, fragment)
				.Commit();

			// Initialize the controls
			_list = FindViewById<ListView>(Resource.Id.left_pane);
			_btnSearch = FindViewById<ImageButton> (Resource.Id.btnSearch);
			_btnNew = FindViewById<ImageButton> (Resource.Id.btnNew);
			_btnEdit = FindViewById<ImageButton> (Resource.Id.btnEdit);
			_btnSave = FindViewById<ImageButton> (Resource.Id.btnSave);
			_btnDelete = FindViewById<ImageButton> (Resource.Id.btnDelete);
			_leftLayout = FindViewById<LinearLayout> (Resource.Id.leftLayout);
			_btnOffline = FindViewById<ImageButton> (Resource.Id.btnOffline);
			_btnUebersicht = FindViewById<Button> (Resource.Id.btnUebersicht);
			_btnCharts = FindViewById<Button> (Resource.Id.btnCharts);
            _btnTasks = FindViewById<Button> (Resource.Id.btnTasks);
            _btnAngebot = FindViewById<Button> (Resource.Id.btnAngebot);
            _btnAuftrag = FindViewById<Button> (Resource.Id.btnAuftrag);
            _tvTelefon = FindViewById<TextView>(Resource.Id.tvTelefon);
            _ImageViewRecord = FindViewById<ImageView>(Resource.Id.ImageViewRecord);


			_btnAnsprechpartner = FindViewById<Button> (Resource.Id.btnAnsprechpartner);
			_btnMap = FindViewById<Button> (Resource.Id.btnMap);
			_edSearch = FindViewById<EditText> (Resource.Id.edSearch);

			// Set the Buttons
			// Disable the New - Edit - Save - Delete Button
			_btnNew.Enabled 		= false;
			_btnEdit.Enabled 		= false;
			_btnSave.Enabled 		= false;
			_btnDelete.Enabled 		= false;

			_btnOffline.Enabled = false;


			// Set the eventhandlers of the controls:
			// Buttons + listview
			_list.ItemClick += (sender, args) =>
			{
				ListItemClickAsync (args);
			};

            // Eventhandler for the Search button on the keyboard
            _edSearch.EditorAction += (object sender, TextView.EditorActionEventArgs e) => 
                {
                    if (e.ActionId == Android.Views.InputMethods.ImeAction.Search)
                    {
                        BtnSearchAsync();
                    }

                };

			_btnSearch.Click += (sender, e) => 
			{
				BtnSearchAsync ();
			};

			_btnNew.Click += (sender, e) => 
			{
				BtnNewClick ();
			};

			_btnEdit.Click += (sender, e) => 
			{
				BtnEditClick ();
			};

			// BtnSave Event must be handled here 
			_btnSave.Click += (sender, e) => 
			{
				BtnSaveClickAsync ();
			};

			_btnDelete.Click += (sender, e) => 
			{
				BtnDeleteClick ();
			};

			_btnUebersicht.Click += (sender, e) => 
			{
				BtnUebersichtClick ();
			};

			_btnMap.Click += (sender, e) => 
			{
				BtnMapClickAsync ();
			};

			
			_btnAnsprechpartner.Click += (sender, e) => 
			{
				BtnAnsprechpartnerClickAsync();
			};

			_btnTasks.Click += (sender, e) => {
				BtnTasksClickAsync ();
			};

            _btnAngebot.Click += (sender, e) => {

                BtnAngebotClickAsync();
            };

            _btnAuftrag.Click += (sender, e) => {

                BtnAuftragClickAsync();
            };

			_btnCharts.Click += (sender, e) => {
				BtnChartsClick();
			};

			_btnOffline.Click += (sender, e) => {

                BtnOfflineClickAsync();

			};

            // set the main tabbar according to the permissions
            this.setMainTabbar();

            // Hide the keyboard except the user clickes on it
            Console.WriteLine("Window.SetSoftInputMode (SoftInput.StateAlwaysHidden); Hide keyboard");
            Window.SetSoftInputMode (SoftInput.StateAlwaysHidden);

            // Set the MainColor 
            FindViewById<TableLayout>(Resource.Id.AM_ColoredTableLayout).SetBackgroundResource(DataAccessLayer.Utilities.MainColor);

		}