/**
     * Sets the callback to be invoked when a {@link Preference} in the
     * hierarchy rooted at this {@link PreferenceManager} is clicked.
     * 
     * @param listener The callback to be invoked.
     */
		public	static void SetOnPreferenceTreeClickListener (PreferenceManager manager, IOnPreferenceTreeClickListener listener)
		{
			//FIXME How Should this Happen??? I dont need it so i leave it..
//			try {                
//				
//				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
//				Field onPreferenceTreeClickListener = cl.GetDeclaredField ("mOnPreferenceTreeClickListener");
//				onPreferenceTreeClickListener.Accessible = true;
//				if (listener != null) {
//					
//					Java.Lang.Object proxy = Proxy.NewProxyInstance (manager.Class.ClassLoader, new Class[] { Class.FromType (typeof(PreferenceManagerCompat).GetInterface ("IOnPreferenceTreeClickListener"))  }, new MyInvocationHandler (listener));
//					onPreferenceTreeClickListener.Set (manager, proxy);
//				} else {
//					onPreferenceTreeClickListener.Set (manager, null);
//				}
//			} catch (System.Exception e) {
//				Console.WriteLine (TAG + " Couldn't set PreferenceManager.mOnPreferenceTreeClickListener by reflection " + e.Message);
//			}
		}
 public FloatListPreference(Context context, IAttributeSet attrs) : base(context, attrs)
 {
     _sharedPreferences       = PreferenceManager.GetDefaultSharedPreferences(context);
     _sharedPreferencesEditor = _sharedPreferences.Edit();
 }
Example #3
0
        public void LoadDatabase(IOConnectionInfo ioConnectionInfo, MemoryStream memoryStream, CompositeKey compositeKey,
                                 ProgressDialogStatusLogger statusLogger, IDatabaseFormat databaseFormat)
        {
            var prefs        = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
            var createBackup = prefs.GetBoolean(Application.Context.GetString(Resource.String.CreateBackups_key), true) &&
                               !(new LocalFileStorage(this).IsLocalBackup(ioConnectionInfo));

            MemoryStream backupCopy = new MemoryStream();

            if (createBackup)
            {
                memoryStream.CopyTo(backupCopy);
                backupCopy.Seek(0, SeekOrigin.Begin);
                //reset stream if we need to reuse it later:
                memoryStream.Seek(0, SeekOrigin.Begin);
            }


            _db.LoadData(this, ioConnectionInfo, memoryStream, compositeKey, statusLogger, databaseFormat);

            if (createBackup)
            {
                statusLogger.UpdateMessage(Application.Context.GetString(Resource.String.UpdatingBackup));
                Java.IO.File internalDirectory = IoUtil.GetInternalDirectory(Application.Context);
                string       baseDisplayName   = App.Kp2a.GetFileStorage(ioConnectionInfo).GetDisplayName(ioConnectionInfo);
                string       targetPath        = baseDisplayName;
                var          charsToRemove     = "|\\?*<\":>+[]/'";
                foreach (char c in charsToRemove)
                {
                    targetPath = targetPath.Replace(c.ToString(), string.Empty);
                }
                if (targetPath == "")
                {
                    targetPath = "local_backup";
                }

                var targetIoc = IOConnectionInfo.FromPath(new Java.IO.File(internalDirectory, targetPath).CanonicalPath);

                using (var transaction = new LocalFileStorage(App.Kp2a).OpenWriteTransaction(targetIoc, false))
                {
                    var file = transaction.OpenFile();
                    backupCopy.CopyTo(file);
                    transaction.CommitWrite();
                }
                Java.Lang.Object baseIocDisplayName = baseDisplayName;

                string keyfile = App.Kp2a.FileDbHelper.GetKeyFileForFile(ioConnectionInfo.Path);
                App.Kp2a.StoreOpenedFileAsRecent(targetIoc, keyfile, Application.Context.
                                                 GetString(Resource.String.LocalBackupOf, new Java.Lang.Object[] { baseIocDisplayName }));

                prefs.Edit()
                .PutBoolean(IoUtil.GetIocPrefKey(ioConnectionInfo, "has_local_backup"), true)
                .PutBoolean(IoUtil.GetIocPrefKey(targetIoc, "is_local_backup"), true)
                .Commit();
            }
            else
            {
                prefs.Edit()
                .PutBoolean(IoUtil.GetIocPrefKey(ioConnectionInfo, "has_local_backup"), false)             //there might be an older local backup, but we won't "advertise" this anymore
                .Commit();
            }

            UpdateOngoingNotification();
        }
Example #4
0
 public static int getQEMinLines(Context context)
 {
     return(validPositiveIntegerOrNumber(PreferenceManager.GetDefaultSharedPreferences(context)
                                         .GetString(OPT_QEDIT_MIN_LINES, OPT_QEDIT_MIN_LINES_DEF), 1));
 }
Example #5
0
 public static int getDefaultView(Context context)
 {
     return(new Integer(PreferenceManager.GetDefaultSharedPreferences(context)
                        .GetString("DefaultView", "1")).IntValue());
 }
Example #6
0
 public static string getSuLocation(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetString(OPT_SULOCATION, OPT_SULOCATION_DEF));
 }
        private void LoadConfiguration()
        {
            //Load configurations based on User configs.
            using (ConfigurationManager configurationManager = new ConfigurationManager(PreferenceManager.GetDefaultSharedPreferences(Application.Context)))
            {
                switch (configurationManager.RetrieveAValue(ConfigurationParameters.ChangeWallpaper, "0"))
                {
                case "0":

                    WallpaperPublisher.ChangeWallpaper(new WallpaperChangedEventArgs {
                        Wallpaper = null
                    });
                    break;

                case "1":
                    using (var wallpaper = (BitmapDrawable)WallpaperManager.GetInstance(Application.Context).Drawable)
                    {
                        int       savedblurlevel    = configurationManager.RetrieveAValue(ConfigurationParameters.BlurLevel, 1);
                        int       savedOpacitylevel = configurationManager.RetrieveAValue(ConfigurationParameters.OpacityLevel, 255);
                        BlurImage blurImage         = new BlurImage(Application.Context);
                        blurImage.Load(wallpaper.Bitmap).Intensity(savedblurlevel).Async(true);
                        var blurredwallpaper = new BitmapDrawable(Resources, blurImage.GetImageBlur());
                        WallpaperPublisher.ChangeWallpaper(new WallpaperChangedEventArgs {
                            Wallpaper = blurredwallpaper, OpacityLevel = (short)savedOpacitylevel
                        });
                        blurImage = null;
                    }

                    break;

                case "2":
                    //using (Bitmap bm = BitmapFactory.DecodeFile(configurationManager.RetrieveAValue(ConfigurationParameters.imagePath, "")))
                    //{
                    //    using (var backgroundFactory = new BackgroundFactory())
                    //    {
                    //        using (BackgroundFactory blurImage = new BackgroundFactory())
                    //        {
                    //            var drawable = blurImage.Difuminar(bm, sa);
                    //            RunOnUiThread(() =>
                    //            Window.DecorView.Background = drawable);
                    //            drawable.Dispose();
                    //        }
                    //    }
                    //}
                    break;

                default:
                    Window.DecorView.SetBackgroundColor(Color.Black);
                    break;
                }
                if (configurationManager.RetrieveAValue(ConfigurationParameters.MusicWidgetEnabled) == true)
                {
                    CheckIfMusicIsPlaying(); //This method is the main entry for the music widget and the floating notification.
                }
                int interval = int.Parse(configurationManager.RetrieveAValue(ConfigurationParameters.TurnOffScreenDelayTime, "5000"));
                watchDog.Interval = interval;
                if (configurationManager.RetrieveAValue(ConfigurationParameters.TurnOnUserMovement) == true)
                {
                    StartAwakeService();
                }
            }
        }
		/**
     * Called by the {@link PreferenceManager} to dispatch the activity destroy
     * event.
     */
		public	static void DispatchActivityDestroy (PreferenceManager manager)
		{
			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("dispatchActivityDestroy");
				m.Accessible = true;
				m.Invoke (manager);
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.dispatchActivityDestroy by reflection " + e.Message);
			}
		}
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            OnImagePicked += (sender, image) =>
            {
                if (image == null)
                {
                    return;
                }

                AppPreference appPreference = new AppPreference();
                CvInvoke.UseOpenCL = appPreference.UseOpenCL;
                String oclDeviceName = appPreference.OpenClDeviceName;
                if (!String.IsNullOrEmpty(oclDeviceName))
                {
                    CvInvoke.OclSetDefaultDevice(oclDeviceName);
                }


                ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                String             appVersion = PackageManager.GetPackageInfo(PackageName, Android.Content.PM.PackageInfoFlags.Activities).VersionName;
                if (!preference.Contains("cascade-data-version") || !preference.GetString("cascade-data-version", null).Equals(appVersion) ||
                    !(preference.Contains("cascade-eye-data-path") || preference.Contains("cascade-face-data-path")))
                {
                    AndroidFileAsset.OverwriteMethod overwriteMethod = AndroidFileAsset.OverwriteMethod.AlwaysOverwrite;

                    FileInfo eyeFile  = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_eye.xml", "cascade", overwriteMethod);
                    FileInfo faceFile = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_frontalface_default.xml", "cascade", overwriteMethod);

                    //save tesseract data path
                    ISharedPreferencesEditor editor = preference.Edit();
                    editor.PutString("cascade-data-version", appVersion);
                    editor.PutString("cascade-eye-data-path", eyeFile.FullName);
                    editor.PutString("cascade-face-data-path", faceFile.FullName);
                    editor.Commit();
                }

                string           eyeXml  = preference.GetString("cascade-eye-data-path", null);
                string           faceXml = preference.GetString("cascade-face-data-path", null);
                long             time;
                List <Rectangle> faces = new List <Rectangle>();
                List <Rectangle> eyes  = new List <Rectangle>();


                DetectFace.Detect(image.Mat, faceXml, eyeXml, faces, eyes, false, out time);

                String computeDevice = CvInvoke.UseOpenCL ? "OpenCL: " + OclDevice.Default.Name : "CPU";
                SetMessage(String.Format("Detected with {1} in {0} milliseconds.", time, computeDevice));

                foreach (Rectangle rect in faces)
                {
                    image.Draw(rect, new Bgr(System.Drawing.Color.Red), 2);
                }
                foreach (Rectangle rect in eyes)
                {
                    image.Draw(rect, new Bgr(System.Drawing.Color.Blue), 2);
                }

                SetImageBitmap(image.ToBitmap());
                image.Dispose();

                if (CvInvoke.UseOpenCL)
                {
                    CvInvoke.OclFinish();
                }
            };

            OnButtonClick += (sender, args) =>
            {
                PickImage("lena.jpg");
            };
        }
Example #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.deleteInterest);
            data = new List <GetUserSkills_Result>();
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);

            email = prefs.GetString("email", "empty");

            if (email.Equals("empty"))
            {
                StartActivity(typeof(MainActivity));
                this.Finish();
            }

            try
            {
                Task <string> task = getUserInterest();
                var           x    = JsonConvert.DeserializeObject <GetUserSkills_Result[]>(task.Result);
                foreach (GetUserSkills_Result a in x)
                {
                    data.Add(a);
                }
                skillNames = new List <string>();
                foreach (var item in data)
                {
                    skillNames.Add(item.name);
                }
            }
            catch (Exception e)
            {
                Toast.MakeText(this, "Error! Some Wrong Happen", ToastLength.Short).Show();
            }


            Spinner spinner = FindViewById <Spinner>(Resource.Id.skillspinner);

            spinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected);
            var adapter = new ArrayAdapter <string>(this,
                                                    Android.Resource.Layout.SimpleSpinnerItem, skillNames);

            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;

            Button button = FindViewById <Button>(Resource.Id.AddSkill);

            if (skillNames.Count == 0)
            {
                button.Enabled = false;
            }



            button.Click += delegate {
                spinner.ItemSelected += new EventHandler <AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected);

                Task <string> task = DeleteInterest(email, SelectedSkill);
                var           x    = JsonConvert.DeserializeObject(task.Result);
                skillNames.Remove(SelectedSkill);

                data.Remove(new GetUserSkills_Result {
                    rating = SelectedId, name = SelectedSkill
                });
                Toast.MakeText(this, "Interest Deleted Sucessfully", ToastLength.Short).Show();

                adapter = new ArrayAdapter <string>(this,
                                                    Android.Resource.Layout.SimpleSpinnerItem, skillNames);

                adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                spinner.Adapter = adapter;
            };


            // Create your application here
        }
        private static bool IsKioskModeActive(Context context)
        {
            var sp = PreferenceManager.GetDefaultSharedPreferences(context);

            return(sp.GetBoolean(PrefKioskMode, false));
        }
Example #12
0
 public PasswordStorageManager(Context context)
 {
     _preferences = PreferenceManager.GetDefaultSharedPreferences(context);
 }
Example #13
0
        private void RequestQuestionList()
        {
            var loading = Acr.UserDialogs.UserDialogs.Instance.Loading("Loading Answers...");

            string hwid = Android.OS.Build.Serial;

            var SharedSettings = new Dictionary <String, String>();
            var prefs          = PreferenceManager.GetDefaultSharedPreferences(Android.App.Application.Context);
            ISharedPreferencesEditor editor = prefs.Edit();
            String gcmID = prefs.GetString("GCMID", "");

            try
            {
                var client     = new RestClient(Shared.SERVERURL);
                var request    = new RestRequest("resource/{id}", Method.POST);
                var parameters = new Dictionary <string, string>();

                parameters.Add(Shared.ParamType.REQUEST_CODE, Shared.RequestCode.GET_QUESTION_LIST.ToString());
                //parameters.Add(Shared.ParamType.WAVIO_ID, micId);
                parameters.Add(Shared.ParamType.GCM_ID, gcmID);
                parameters.Add(Shared.ParamType.HWID, hwid);
                string requestJson = JsonConvert.SerializeObject(parameters);
                request.AddParameter(Shared.ParamType.REQUEST, requestJson);

                Console.WriteLine("Waiting for response");


                client.ExecuteAsync(request, response => {
                    ServerResponse serverResponse = JsonConvert.DeserializeObject <ServerResponse>(response.Content);

                    if (serverResponse == null)
                    {
                        Acr.UserDialogs.UserDialogs.Instance.ShowError("Network error!");
                        return;
                    }

                    if (serverResponse.error == Shared.ServerResponsecode.OK)
                    {
                        questions = JsonConvert.DeserializeObject <List <Question> >(serverResponse.data);
                        adapter.SetItems(questions);

                        parent.RunOnUiThread(() =>
                        {
                            adapter.NotifyDataSetChanged();
                        });

                        loading.Hide();
                    }

                    else if (serverResponse.error == Shared.ServerResponsecode.DATABASE_ERROR)
                    {
                        Acr.UserDialogs.UserDialogs.Instance.ShowError("Server error!");
                    }
                    else
                    {
                        if (serverResponse.request != Shared.RequestCode.GET_QUESTION_LIST)
                        {
                            Acr.UserDialogs.UserDialogs.Instance.ShowError("Request type mismatch!");
                            return;
                        }
                        Acr.UserDialogs.UserDialogs.Instance.ShowError("Unknown error!");
                    }
                    Acr.UserDialogs.UserDialogs.Instance.HideLoading();
                    return;
                });
            }
            catch (WebException ex)
            {
                string _exception = ex.ToString();
                Acr.UserDialogs.UserDialogs.Instance.ShowError("Network error!");
                Console.WriteLine("--->" + _exception);
            }
        }
Example #14
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);


            prefs       = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
            db          = new DbHelper();
            geo         = new Geolocation();
            restService = new ServiceHelper();
            ic          = new InternetConnection();
            login_data  = new List <LoginModel>();

            version = Android.App.Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Android.App.Application.Context.ApplicationContext.PackageName, 0).VersionName;
            DrawerLayout          drawer = FindViewById <DrawerLayout>(Resource.Id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);

            drawer.AddDrawerListener(toggle);
            toggle.SyncState();

            NavigationView navigationView = FindViewById <NavigationView>(Resource.Id.nav_view);

            navigationView.SetNavigationItemSelectedListener(this);
            List <LoginModel> loginModel = db.getDetail();

            if (loginModel.Count <= 1)
            {
                IMenu nav_Menu = navigationView.Menu;
                nav_Menu.FindItem(Resource.Id.switchuser).SetVisible(false);
            }

            location = geo.GetGeoLocation(this);
            SupportFragmentManager.BeginTransaction().Replace(Resource.Id.container, new MainFrag(), "MainFrag").Commit();

            ManualSyncData();

            View   header   = navigationView.GetHeaderView(0);
            string userName = prefs.GetString("UserName", "");
            string number   = prefs.GetString("MobileNumber", "");
            string propic   = prefs.GetString("NPPhoto", "");
            string org      = prefs.GetString("Organization", "");
            string desig    = prefs.GetString("Designation", "");

            identity = prefs.GetString("LoginIdentity", "");

            TextView  name1   = (TextView)header.FindViewById(Resource.Id.user);
            TextView  mobile1 = (TextView)header.FindViewById(Resource.Id.number);
            ImageView image   = (ImageView)header.FindViewById(Resource.Id.propic);
            TextView  desig1  = (TextView)header.FindViewById(Resource.Id.desig);
            TextView  org1    = (TextView)header.FindViewById(Resource.Id.org);

            name1.Text   = userName;
            mobile1.Text = number;
            desig1.Text  = desig;
            org1.Text    = org;

            if (propic != "" && propic != null)
            {
                Glide.With(this).Load(propic).Into(image);
            }
        }
		/**
     * Inflates a preference hierarchy from the preference hierarchies of
     * {@link Activity Activities} that match the given {@link Intent}. An
     * {@link Activity} defines its preference hierarchy with meta-data using
     * the {@link #METADATA_KEY_PREFERENCES} key.
     * <p>
     * If a preference hierarchy is given, the new preference hierarchies will
     * be merged in.
     * 
     * @param queryIntent The intent to match activities.
     * @param rootPreferences Optional existing hierarchy to merge the new
     *            hierarchies into.
     * @return The root hierarchy (if one was not provided, the new hierarchy's
     *         root).
     */
		public	static PreferenceScreen InflateFromIntent (PreferenceManager manager, Intent intent, PreferenceScreen screen)
		{

			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("inflateFromIntent", Class.FromType (typeof(Intent)), Class.FromType (typeof(PreferenceScreen)));
				m.Accessible = true;
				PreferenceScreen prefScreen = (PreferenceScreen)m.Invoke (manager, intent, screen);
				return prefScreen;
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.inflateFromIntent by reflection " + e.Message);
			}
			return null;
		}
		/**
     * Returns the root of the preference hierarchy managed by this class.
     *  
     * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.
     */
		public	static PreferenceScreen GetPreferenceScreen (PreferenceManager manager)
		{
			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("getPreferenceScreen");
				m.Accessible = true;
				return (PreferenceScreen)m.Invoke (manager);
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.getPreferenceScreen by reflection " + e.Message);
			}
			return null;
		}
Example #17
0
        private static string GetLog(List <string> changeLog, string warning, Context ctx)
        {
            StringBuilder sb = new StringBuilder(HtmlStart);

            if (!string.IsNullOrEmpty(warning))
            {
                sb.Append(warning);
            }
            bool inList  = false;
            bool isFirst = true;

            foreach (string versionLog in changeLog)
            {
                string versionLog2 = versionLog;
                bool   title       = true;
                if (isFirst)
                {
                    bool showDonateOption    = true;
                    ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(ctx);
                    if (prefs.GetBoolean(ctx.GetString(Resource.String.NoDonationReminder_key), false))
                    {
                        showDonateOption = false;
                    }

                    long usageCount = prefs.GetLong(ctx.GetString(Resource.String.UsageCount_key), 0);

                    if (usageCount <= 5)
                    {
                        showDonateOption = false;
                    }

                    if (showDonateOption)
                    {
                        if (versionLog2.EndsWith("\n") == false)
                        {
                            versionLog2 += "\n";
                        }
                        string donateUrl = ctx.GetString(Resource.String.donate_url,
                                                         new Java.Lang.Object[] { ctx.Resources.Configuration.Locale.Language,
                                                                                  ctx.PackageName });

                        versionLog2 += " * <a href=\"" + donateUrl
                                       + "\">" +
                                       ctx.GetString(Resource.String.ChangeLog_keptDonate)
                                       + "<a/>";
                    }
                    isFirst = false;
                }
                foreach (string line in versionLog2.Split('\n'))
                {
                    string w = line.Trim();
                    if (title)
                    {
                        if (inList)
                        {
                            sb.Append("</ul></div>\n");
                            inList = false;
                        }
                        w = w.Replace("<b>", "");
                        w = w.Replace("</b>", "");
                        w = w.Replace("\\n", "");
                        sb.Append("<div class='title'>"
                                  + w.Trim() + "</div>\n");
                        title = false;
                    }
                    else
                    {
                        w = w.Replace("\\n", "<br />");
                        if ((w.StartsWith("*") || (w.StartsWith("•"))))
                        {
                            if (!inList)
                            {
                                sb.Append("<div class='list'><ul>\n");
                                inList = true;
                            }
                            sb.Append("<li>");
                            sb.Append(w.Substring(1).Trim());
                            sb.Append("</li>\n");
                        }
                        else
                        {
                            if (inList)
                            {
                                sb.Append("</ul></div>\n");
                                inList = false;
                            }
                            sb.Append(w);
                        }
                    }
                }
            }
            sb.Append(HtmlEnd);
            return(sb.ToString());
        }
		/**
     * Sets the owning preference fragment
     */
		public	static void SetFragment (PreferenceManager manager, SupportPreferenceFragment fragment)
		{
			// stub
		}
        public void settingsDialog()
        {
            Android.Support.V7.App.AlertDialog.Builder builder;
            Android.Support.V7.App.AlertDialog         dlg;

            appSetting = AppInstanceManager.Instance.getAppSetting();

            LayoutInflater inflater = (LayoutInflater)GetSystemService(Context.LayoutInflaterService);
            View           layout   = inflater.Inflate(Resource.Layout.setting_option, null);

            EditText ipAddressEditText = layout
                                         .FindViewById(Resource.Id.selectprotocol_ipAddr) as EditText;
            EditText tcpPortEditText = (EditText)layout
                                       .FindViewById(Resource.Id.selectprotocol_tcpPort);

            string ipAddress = appSetting.getIPAddress();
            string tcpPort   = appSetting.getTcpPort();


            builder = new Android.Support.V7.App.AlertDialog.Builder(this);

            ipAddressEditText.Text = ipAddress;
            tcpPortEditText.Text   = tcpPort;

            string   htmlString = "<b><u>SharpHmi Settings</u></b>";
            TextView title      = new TextView(this);

            title.Gravity  = GravityFlags.Center;
            title.Text     = Html.FromHtml(htmlString).ToString();
            title.TextSize = 25;

            builder.SetCustomTitle(title);
            builder.SetPositiveButton("OK", (senderAlert, args) => {
                if (ipAddressEditText.Length() != 0)
                {
                    appSetting.setIPAddress(ipAddressEditText.Text.ToString());
                }

                if (tcpPortEditText.Length() != 0)
                {
                    appSetting.setTcpPort(tcpPortEditText.Text.ToString());
                }

                string tmpIpAddress     = appSetting.getIPAddress();
                string tmpTcpPortNumber = appSetting.getTcpPort();

                ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

                prefs.Edit().PutString(Const.PREFS_KEY_TRANSPORT_IP, appSetting.getIPAddress())
                .PutInt(Const.PREFS_KEY_TRANSPORT_PORT, int.Parse(appSetting.getTcpPort())).Commit();

                if ((ipAddress != tmpIpAddress) || (tcpPort != tmpTcpPortNumber))
                {
                    new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                    {
                        AppInstanceManager.Instance.setupConnection(appSetting.getIPAddress(), int.Parse(appSetting.getTcpPort()));
                    })).Start();
                }

                builder.Dispose();
            });

            builder.SetNegativeButton("Cancel", (senderAlert, args) => {
                builder.Dispose();
            });

            builder.SetCancelable(true);
            builder.SetView(layout);
            dlg = builder.Create();
            dlg.Show();
        }
Example #20
0
 public static bool getMainVertical(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_VERTICAL, OPT_VERTICAL_DEF));
 }
Example #21
0
        private void ShowAuthDialog()
        {
            // Create transaction to show our add item dialog on this activity
            var transaction    = FragmentManager.BeginTransaction();
            var dialogFragment = new AuthDialog(ApplicationId, ApiKey, DatabaseUrl, Email, Password);

            // Do staff with email/password, when we press authenticate on the dialog
            dialogFragment.Dismissed += (s, e) =>
            {
                // Hide auth button
                authButton.Visibility = ViewStates.Gone;
                // Show loading again
                loading.Visibility = ViewStates.Visible;

                // Set Firebase variables
                ApplicationId = e.ApplicationId;
                ApiKey        = e.ApiKey;
                DatabaseUrl   = e.DatabaseUrl;

                // Save Firebase variables on local preferences
                ISharedPreferences       prefs  = PreferenceManager.GetDefaultSharedPreferences(this);
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("ApplicationId", ApplicationId);
                editor.PutString("ApiKey", ApiKey);
                editor.PutString("DatabaseUrl", DatabaseUrl);
                editor.PutString("Email", Email);
                editor.Apply();

                if (app == null)
                {
                    // Needs to initialize Firebase app first
                    InitFirebase();
                    return;
                }

                OnCompleteAuthListener OnCompleteAuth = new OnCompleteAuthListener();
                OnCompleteAuth.Raised += (se, ev) =>
                {
                    if (ev.task.IsSuccessful)
                    {
                        Toast.MakeText(this, "User authenticated", ToastLength.Short).Show();

                        // Load things
                        Load();
                    }
                    else
                    {
                        Toast.MakeText(this, ev.task.Exception.Message, ToastLength.Short).Show();
                        // Show again auth dialog
                        ShowAuthDialog();
                    }
                };

                auth.SignInWithEmailAndPassword(e.User, e.Password).AddOnCompleteListener(OnCompleteAuth);
            };

            // If we show dialog title, specify if we are adding or editing an existing item
            string title = GetString(Resource.String.authentication);

            // Show dialog
            dialogFragment.Show(transaction, title);


            // Hide loading
            if (loading != null)
            {
                loading.Visibility = ViewStates.Gone;
            }
            // Show auth button (user can press back)
            if (authButton != null)
            {
                authButton.Visibility = ViewStates.Visible;
            }
        }
Example #22
0
 public static bool getTestRoot(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_TESTROOT, OPT_TESTROOT_DEF));
 }
 public BlobFileUpload(Context context)
 {
     this.mContext = context;
     prefs         = PreferenceManager.GetDefaultSharedPreferences(mContext);
     licId         = prefs.GetString("LicenceId", "");
 }
Example #24
0
 public static bool getUseSpatialite(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_SPATIALITE, OPT_SPATIALITE_DEF));
 }
Example #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.MenuPrincipal);

            ////Comentarear Si marca error, es la notificación

            if (!GetString(Resource.String.google_app_id).Equals("1:593192999279:android:7fd609f7126dc407"))
            {
                throw new System.Exception("Invalid Json file");
            }
            Task.Run(() =>
            {
                var instanceId = FirebaseInstanceId.Instance;
                instanceId.DeleteInstanceId();
                Android.Util.Log.Debug("TAG", "{0} {1}", instanceId.Token, instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));
            });

            ///////


            var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);

            SetSupportActionBar(toolbar);
            SupportActionBar.Title = "Menú Principal";
            SupportActionBar.SetLogo(Resource.Drawable.Home);
            //test = FindViewById<Button>(Resource.Id.test);
            //test.Click += test_click;
            perfil        = FindViewById <ImageView>(Resource.Id.IconoPerfil);
            perfil.Click += perfil_Click;
            CustomGridViewAdapter adapter = new CustomGridViewAdapter(this, gridViewString, imageId);

            gridView            = FindViewById <GridView>(Resource.Id.grid_view_image_text);
            gridView.Adapter    = adapter;
            gridView.ItemClick += OnListItemClick;
            //gridView.ItemClick += (s, e) => {
            //    Toast.MakeText(this, "GridView Item: " + gridViewString[e.Position], ToastLength.Short).Show();
            //};



            try
            {
                ISharedPreferences preferencess = PreferenceManager.GetDefaultSharedPreferences(this);
                string             path         = preferencess.GetString("Profile_picture", "");

                Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(path));

                System.IO.Stream input = this.ContentResolver.OpenInputStream(uri);
                Byte[]           pictByteArray;
                //Use bitarray to use less memory
                byte[] buffer = new byte[16 * 1024];
                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    pictByteArray = ms.ToArray();
                }

                input.Close();

                //Get file information
                BitmapFactory.Options options = new BitmapFactory.Options {
                    InJustDecodeBounds = true
                };
                Bitmap bitmap = BitmapFactory.DecodeByteArray(pictByteArray, 0, pictByteArray.Length);
                perfil.SetImageBitmap(bitmap);
            }
            catch (Exception ex)
            {
            }
        }
Example #26
0
 /**
  * Return the numbers of records to retrieve when paging data
  * @param context
  * @return page size
  */
 public static int getFontSize(Context context)
 {
     return(validPositiveIntegerOrNumber(PreferenceManager.GetDefaultSharedPreferences(context)
                                         .GetString(OPT_FONTSIZE, OPT_FONTSIZE_DEF), 0));
 }
 public AndroidKVPersister(Context context)
 {
     preferences = PreferenceManager.GetDefaultSharedPreferences(context);
 }
Example #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);


            if (IsFinishing)
            {
                return;
            }

            SetResult(KeePass.ExitNormal);

            Log.Warn(Tag, "Creating group view");
            Intent intent = Intent;

            PwUuid id = RetrieveGroupId(intent);

            Database db = App.Kp2a.GetDb();

            if (id == null)
            {
                Group = db.Root;
            }
            else
            {
                Group = db.Groups[id];
            }

            Log.Warn(Tag, "Retrieved group");
            if (Group == null)
            {
                Log.Warn(Tag, "Group was null");
                return;
            }


            if (AddGroupEnabled)
            {
                // Add Group button
                View addGroup = FindViewById(Resource.Id.fabAddNewGroup);
                addGroup.Click += (sender, e) => {
                    GroupEditActivity.Launch(this, Group);
                };
            }


            if (AddEntryEnabled)
            {
                View addEntry = FindViewById(Resource.Id.fabAddNewEntry);
                addEntry.Click += (sender, e) =>
                {
                    if (App.Kp2a.GetDb().DatabaseFormat.SupportsTemplates&&
                        !AddTemplateEntries.ContainsAllTemplates(App.Kp2a) &&
                        PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(Askaddtemplates, true))
                    {
                        App.Kp2a.AskYesNoCancel(UiStringKey.AskAddTemplatesTitle, UiStringKey.AskAddTemplatesMessage, UiStringKey.yes, UiStringKey.no,
                                                (o, args) =>
                        {
                            //yes
                            ProgressTask pt = new ProgressTask(App.Kp2a, this,
                                                               new AddTemplateEntries(this, App.Kp2a, new ActionOnFinish(
                                                                                          delegate
                            {
                                StartAddEntry();
                            })));
                            pt.Run();
                        },
                                                (o, args) =>
                        {
                            var edit = PreferenceManager.GetDefaultSharedPreferences(this).Edit();
                            edit.PutBoolean(Askaddtemplates, false);
                            edit.Commit();
                            //no
                            StartAddEntry();
                        }, null, this);
                    }
                    else
                    {
                        StartAddEntry();
                    }
                };
            }

            SetGroupTitle();
            SetGroupIcon();

            FragmentManager.FindFragmentById <GroupListFragment>(Resource.Id.list_fragment).ListAdapter = new PwGroupListAdapter(this, Group);
            Log.Warn(Tag, "Finished creating group");

            var ioc = App.Kp2a.GetDb().Ioc;
            OptionalOut <UiStringKey> reason = new OptionalOut <UiStringKey>();

            if (App.Kp2a.GetFileStorage(ioc).IsReadOnly(ioc, reason))
            {
                bool hasShownReadOnlyReason =
                    PreferenceManager.GetDefaultSharedPreferences(this)
                    .GetBoolean(App.Kp2a.GetDb().IocAsHexString() + "_readonlyreason", false);
                if (!hasShownReadOnlyReason)
                {
                    var b = new AlertDialog.Builder(this);
                    b.SetTitle(Resource.String.FileReadOnlyTitle);
                    b.SetMessage(GetString(Resource.String.FileReadOnlyMessagePre) + " " + App.Kp2a.GetResourceString(reason.Result));
                    b.SetPositiveButton(Android.Resource.String.Ok,
                                        (sender, args) =>
                    {
                        PreferenceManager.GetDefaultSharedPreferences(this).
                        Edit().PutBoolean(App.Kp2a.GetDb().IocAsHexString() + "_readonlyreason", true).Commit();
                    });
                    b.Show();
                }
            }
        }
Example #29
0
 /**
  * Return true if executed statements are stored in database
  * @param context
  * @return
  */
 public static bool getSaveSQL(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_SAVESQL, OPT_SAVESQL_DEF));
 }
        private void RequestRegister(uint registrationId, IdentityKeyPair identityKeyPair, SignedPreKeyRecord signedPreKey, List <PreKeyRecord> preKeys)
        {
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "registerUser";

            // Login_Request has two properties: username and password
            Login_Request myLogin_Request = new Login_Request();

            myLogin_Request.Username                    = username.Text;
            myLogin_Request.Password                    = password.Text.GetHashCode();
            myLogin_Request.RegistrationID              = registrationId;
            myLogin_Request.PublicIdentityKey           = JsonConvert.SerializeObject(identityKeyPair.getPublicKey().serialize());
            myLogin_Request.PublicSignedPreKeyID        = signedPreKey.getId();
            myLogin_Request.PublicSignedPreKeySignature = JsonConvert.SerializeObject(signedPreKey.getSignature());
            myLogin_Request.PublicSignedPreKey          = JsonConvert.SerializeObject(signedPreKey.getKeyPair().getPublicKey().serialize());

            // Save in local Database
            ISharedPreferences       sharedprefs = PreferenceManager.GetDefaultSharedPreferences(this);
            ISharedPreferencesEditor editor      = sharedprefs.Edit();

            // Store identityKeyPair somewhere durable and safe.
            editor.PutString("IdentityKeyPair", JsonConvert.SerializeObject(identityKeyPair.serialize()));
            editor.PutString("SignedPreKey", JsonConvert.SerializeObject(signedPreKey.serialize()));
            editor.PutString("Username", username.Text);
            editor.PutInt("Password", password.Text.GetHashCode());

            // Store registrationId somewhere durable and safe.
            editor.PutString("RegistrationId", registrationId.ToString());
            editor.Apply();

            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response r = JsonConvert.DeserializeObject <API_Response>(response);

            if (r != null)
            {
                if (!r.IsError)
                {
                    foreach (PreKeyRecord preKey in preKeys)
                    {
                        Prekey_Request preKey_Request = new Prekey_Request();
                        preKey_Request.PublicSignedPreKeyID = signedPreKey.getId();
                        preKey_Request.PublicPreKeyID       = preKey.getId();
                        preKey_Request.PublicPreKey         = JsonConvert.SerializeObject(preKey.getKeyPair().getPublicKey().serialize());
                        apiMethod = "storePreKeys";

                        // make http post request
                        string preKeyResponse = Http.Post(apiUrl, new NameValueCollection()
                        {
                            { "api_method", apiMethod },
                            { "api_data", JsonConvert.SerializeObject(preKey_Request) }
                        });

                        // decode json string to dto object
                        API_Response preKeyR = JsonConvert.DeserializeObject <API_Response>(preKeyResponse);
                        if (preKeyR == null)
                        {
                            break;
                        }
                    }
                }
            }
        }
Example #31
0
 public static int getNoOfFiles(Context context)
 {
     return(validPositiveIntegerOrNumber(PreferenceManager.GetDefaultSharedPreferences(context)
                                         .GetString(OPT_FILENO, OPT_FILENO_DEF), 0));
 }
		/**
     * Inflates a preference hierarchy from XML. If a preference hierarchy is
     * given, the new preference hierarchies will be merged in.
     * 
     * @param context The context of the resource.
     * @param resId The resource ID of the XML to inflate.
     * @param rootPreferences Optional existing hierarchy to merge the new
     *            hierarchies into.
     * @return The root hierarchy (if one was not provided, the new hierarchy's
     *         root).
     * @hide
     */
		public	static PreferenceScreen InflateFromResource (PreferenceManager manager, Activity activity, int resId, PreferenceScreen screen)
		{
			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("inflateFromResource", Class.FromType (typeof(Context)), Java.Lang.Integer.Type, Class.FromType (typeof(PreferenceScreen)));
				m.Accessible = true;
				PreferenceScreen prefScreen = (PreferenceScreen)m.Invoke (manager, activity, resId, screen);
				return prefScreen;
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.inflateFromResource by reflection " + e.Message);
			}
			return null;
		}
Example #33
0
 public static int getMaxWidth(Context context)
 {
     return(validPositiveIntegerOrNumber(PreferenceManager.GetDefaultSharedPreferences(context)
                                         .GetString(OPT_MAX_WIDTH, OPT_MAX_WIDTH_DEF), 0));
 }
		/**
     * Called by the {@link PreferenceManager} to dispatch a subactivity result.
     */
		public	static void DispatchActivityResult (PreferenceManager manager, int requestCode, int resultCode, Intent data)
		{
			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("dispatchActivityResult", Java.Lang.Integer.Type, Java.Lang.Integer.Type, Class.FromType (typeof(Intent)));
				m.Accessible = true;
				m.Invoke (manager, requestCode, resultCode, data);
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.dispatchActivityResult by reflection " + e.Message);
			}
		}
Example #35
0
 public static bool getFKList(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_FK2LIST, OPT_FK2LIST_DEF));
 }
		/**
     * Sets the root of the preference hierarchy.
     * 
     * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
     * @return Whether the {@link PreferenceScreen} given is different than the previous. 
     */
		public	static bool SetPreferences (PreferenceManager manager, PreferenceScreen screen)
		{
			try {
				Class cl = Java.Lang.Class.FromType (typeof(PreferenceManager));
				Method m = cl.GetDeclaredMethod ("setPreferences", Class.FromType (typeof(PreferenceScreen)));
				m.Accessible = true;
				return ((bool)m.Invoke (manager, screen));
			} catch (System.Exception e) {
				Console.WriteLine (TAG + " Couldn't call PreferenceManager.setPreferences by reflection " + e.Message);
			}
			return false;
		}
Example #37
0
 public static bool getEnableFK(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_FKON, OPT_FKON_DEF));
 }
Example #38
0
 public static bool getLogging(Context context)
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context)
            .GetBoolean(OPT_LOGGING, OPT_LOGGING_DEF));
 }
		public override void OnCreate (Bundle paramBundle)
		{
			base.OnCreate (paramBundle);
			mPreferenceManager = PreferenceManagerCompat.NewInstance (Activity, FIRST_REQUEST_CODE);
			PreferenceManagerCompat.SetFragment (mPreferenceManager, this);
		}