Exemplo n.º 1
1
        internal TMain()
            : base()
        {
            versionNumber += ", " + PrismApi.NiceVersionString;

            SavePath += "\\Prism";

            PlayerPath = SavePath + "\\Players";
            WorldPath  = SavePath + "\\Worlds" ;

            PrismApi.ModDirectory = SavePath + "\\Mods";

            CloudPlayerPath = "players_Prism";
            CloudWorldPath  = "worlds_Prism" ;

            LocalFavoriteData  = new FavoritesFile(SavePath + "\\favorites.json", false);
            CloudFavoritesData = new FavoritesFile("/favorites_Prism.json", false);

            Configuration = new Preferences(SavePath + "\\config.json", false, false);

            ElapsedTime = 0;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT && graphics.GraphicsProfile == GraphicsProfile.Reach && GraphicsAdapter.DefaultAdapter.IsProfileSupported(GraphicsProfile.HiDef))
                graphics.GraphicsProfile = GraphicsProfile.HiDef;
        }
Exemplo n.º 2
0
        public void SetUp()
        {
            NetworkTable.Shutdown();
            /*
            //We can't run NT or File based tests on the simulator. Just auto pass them.
            if (RobotBase.IsSimulation)
            {
                return;
            }
            */
            try
            {
                string file = "networktables.ini";
                if (File.Exists(file))
                {
                    File.Delete(file);
                }

                using (StreamWriter writer = new StreamWriter(file))
                {
                    writer.Write("[NetworkTables Storage 3.0]\ndouble \"/Preferences/checkedValueInt\"=2\ndouble \"/Preferences/checkedValueDouble\"=.2\ndouble \"/Preferences/checkedValueFloat\"=3.14\ndouble \"/Preferences/checkedValueLong\"=172\nstring \"/Preferences/checkedValueString\"=\"hello \\nHow are you ?\"\nboolean \"/Preferences/checkedValueBoolean\"=false\n");
                }

            }
            catch (IOException exception)
            {
                Console.WriteLine(exception);
            }

            NetworkTable.Initialize();

            pref = Preferences.Instance;
            prefTable = NetworkTable.GetTable("Preferences");
            check = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
        }
        public async Task<PhotosetsResponse> GetPhotosetsAsync(string methodName, User user, Preferences preferences, int page,
                                                               IProgress<ProgressUpdate> progress) {
            var progressUpdate = new ProgressUpdate {
                OperationText = "Getting list of albums...",
                ShowPercent = false
            };
            progress.Report(progressUpdate);

            var extraParams = new Dictionary<string, string> {
                {
                    ParameterNames.UserId, user.UserNsId
                }, {
                    ParameterNames.SafeSearch, preferences.SafetyLevel
                }, {
                    ParameterNames.PerPage, "21"
                }, {
                    ParameterNames.Page, page.ToString(CultureInfo.InvariantCulture)
                }
            };

            var photosetsResponseDictionary = (Dictionary<string, object>)
                await this._oAuthManager.MakeAuthenticatedRequestAsync(methodName, extraParams);

            return photosetsResponseDictionary.GetPhotosetsResponseFromDictionary();
        }
Exemplo n.º 4
0
    //comes from gui/stats.cs
    public StatType(string statisticType, string statisticSubType, string statisticApplyTo, Gtk.TreeView treeview_stats,
			ArrayList sendSelectedSessions, bool sex_active, int statsJumpsType, int limit, 
			ArrayList markedRows, int evolution_mark_consecutives, GraphROptions gRO,
			bool graph, bool toReport, Preferences preferences)
    {
        //some of this will disappear when we use myStatTypeStruct in all classes:
        this.statisticType = statisticType;
        this.statisticSubType = statisticSubType;
        this.statisticApplyTo = statisticApplyTo;
        this.treeview_stats = treeview_stats ;

        this.markedRows = markedRows;

        this.evolution_mark_consecutives = evolution_mark_consecutives;

        this.graph = graph;
        this.toReport = toReport;

        myStatTypeStruct = new StatTypeStruct (
                statisticApplyTo,
                sendSelectedSessions, sex_active,
                statsJumpsType, limit,
                markedRows, gRO,
                toReport, preferences);

        myStat = new Stat(); //create an instance of myStat

        fakeButtonRowCheckedUnchecked = new Gtk.Button();
        fakeButtonRowsSelected = new Gtk.Button();
        fakeButtonNoRowsSelected = new Gtk.Button();
    }
Exemplo n.º 5
0
    public TreeViewJumps(Gtk.TreeView treeview, Preferences preferences, ExpandStates expandState)
    {
        this.treeview = treeview;
        this.preferences = preferences;
        this.expandState = expandState;

        this.pDN = preferences.digitsNumber; //pDN short and very used name

        treeviewHasTwoLevels = false;
        dataLineNamePosition = 0; //position of name in the data to be printed
        dataLineTypePosition = 4; //position of type in the data to be printed
        allEventsName = Constants.AllJumpsName;

        if(preferences.weightStatsPercent)
            weightName += "\n(%)";
        else
            weightName += "\n(Kg)";

        string [] columnsStringPre = { jumperName,
            Catalog.GetString("TC") + "\n(s)",
            Catalog.GetString("TF") + "\n(s)",
            weightName, fallName,
            heightName
           	};

        columnsString = obtainColumnsString(columnsStringPre);

        eventIDColumn = columnsString.Length ; //column where the uniqueID of event will be (and will be hidden).
        store = getStore(columnsString.Length +1); //+1 because, eventID is not show in last col
        treeview.Model = store;
        prepareHeaders(columnsString);

        //on creation, treeview is minimized
        expandState = ExpandStates.MINIMIZED;
    }
        public async Task<Photoset> GetCoverPhotoAsync(User user, Preferences preferences, bool onlyPrivate) {
            var extraParams = new Dictionary<string, string> {
                {
                    ParameterNames.UserId, user.UserNsId
                }, {
                    ParameterNames.SafeSearch, preferences.SafetyLevel
                }, {
                    ParameterNames.PerPage, "1"
                }, {
                    ParameterNames.Page, "1"
                }, {
                    ParameterNames.PrivacyFilter, onlyPrivate ? "5" : "1"
                    // magic numbers: https://www.flickr.com/services/api/flickr.people.getPhotos.html
                }
            };

            var photosetsResponseDictionary = (Dictionary<string, object>)
                await this._oAuthManager.MakeAuthenticatedRequestAsync(Methods.PeopleGetPhotos, extraParams);

            var photo = photosetsResponseDictionary.GetPhotosResponseFromDictionary(false).Photos.FirstOrDefault();

            return photo != null
                ? new Photoset(null, null, null, null, 0, 0, 0,
                    onlyPrivate ? "All Photos" : "All Public Photos", "",
                    onlyPrivate ? PhotosetType.All : PhotosetType.Public,
                    photo.SmallSquare75X75Url)
                : null;
        }
Exemplo n.º 7
0
 /**
  * Construct a new {@code PreferenceChangeEvent} instance.
  *
  * @param p
  *            the {@code Preferences} instance that fired this event; this object is
  *            considered as the event's source.
  * @param k
  *            the changed preference key.
  * @param v
  *            the new value of the changed preference, this value can be
  *            {@code null}, which means the preference has been removed.
  */
 public PreferenceChangeEvent(Preferences p, String k, String v)
     : base(p)
 {
     node = p;
     key = k;
     value = v;
 }
 /// <summary>
 /// Loads project settings from registry.
 /// </summary>
 public void LoadProjectSettingsFromRegistry(ref TfsTeamProjectCollection tfsTeamProjectCollection, ref ITestManagementTeamProject testManagementTeamProject, ref Preferences preferences, ITestManagementService testService, string selectedTestPlan)
 {
     log.Info("Load project info loaded from registry!");
     string teamProjectUri = RegistryManager.Instance.GetTeamProjectUri();
     string teamProjectName = RegistryManager.Instance.GetTeamProjectName();
     string projectDllPath = RegistryManager.Instance.GetProjectDllPath();
     if (!string.IsNullOrEmpty(teamProjectUri) && !string.IsNullOrEmpty(teamProjectName))
     {
         preferences.TfsUri = new Uri(teamProjectUri);
         log.InfoFormat("Registry> TFS URI: {0}", preferences.TfsUri);
         preferences.TestProjectName = teamProjectName;
         log.InfoFormat("Registry> Test Project Name: {0}", preferences.TestProjectName);
         tfsTeamProjectCollection = new TfsTeamProjectCollection(preferences.TfsUri);
         log.InfoFormat("Registry> TfsTeamProjectCollection: {0}", tfsTeamProjectCollection);
         testService = (ITestManagementService)tfsTeamProjectCollection.GetService(typeof(ITestManagementService));
         testManagementTeamProject = testService.GetTeamProject(preferences.TestProjectName);
         selectedTestPlan = RegistryManager.Instance.GetTestPlan();
         log.InfoFormat("Registry> SelectedTestPlan: {0}", selectedTestPlan);
         if (!string.IsNullOrEmpty(selectedTestPlan))
         {
             preferences.TestPlan = TestPlanManager.GetTestPlanByName(testManagementTeamProject, selectedTestPlan);
             this.IsInitializedFromRegistry = true;
         }
     }
 }
Exemplo n.º 9
0
 public PreferencesProxy(Preferences prefs)
 {
     prefSubscribers = new Hashtable();
     currentlyHandling = new Hashtable();
     this.prefs = prefs;
     this.enable = true;
 }
Exemplo n.º 10
0
    public override void OnInspectorGUI()
    {
        if(invoker != null)
        {
            EditorGUILayout.BeginVertical("GroupBox");

            EditorGUILayout.BeginHorizontal();

            GUILayout.Label("Reference", EditorStyles.boldLabel);

            GUILayout.Label("Component", EditorStyles.boldLabel);

            GUILayout.Label("Method", EditorStyles.boldLabel);

            if(GUILayout.Button("Add", GUILayout.Width(32)))
            {
                Preferences temp = new Preferences();
                invoker.preferences.Add(temp);
            }

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();

            if(invoker.Count > 0)
            {
                for(int i = 0; i < invoker.Count; i++)
                {
                    EditorGUILayout.BeginHorizontal();

                    invoker.preferences[i].objectReference = (Transform)EditorGUILayout.ObjectField(invoker.preferences[i].objectReference, typeof(Transform), true);

                    if(invoker.preferences[i].objectReference != null)
                    {
                        invoker.preferences[i].monoIndex = EditorGUILayout.Popup(invoker.preferences[i].monoIndex, invoker.preferences[i].monoNames.ToArray());
                        invoker.preferences[i].methodIndex = EditorGUILayout.Popup(invoker.preferences[i].methodIndex, invoker.preferences[i].methodNames.ToArray());
                    }

                    if(GUILayout.Button("X", GUILayout.Width(16), GUILayout.Height(14)))
                    {
                        invoker.preferences.RemoveAt(i);
                        return;
                    }

                    EditorGUILayout.EndHorizontal();

                    if(GUI.changed)
                    {
                        invoker.preferences[i].GetMonos();
                        invoker.preferences[i].GetMethods();
                    }

                    EditorGUILayout.Space();

                }
            }

            EditorGUILayout.EndVertical();
        }
    }
Exemplo n.º 11
0
        public void SetUp()
        {
            //We can't run NT or File based tests on the simulator. Just auto pass them.
            if (RobotBase.IsSimulation)
            {
                return;
            }
            try
            {
                string file = "/home/lvuser/wpilib-preferences.ini";
                if (File.Exists(file))
                {
                    File.Delete(file);
                }

                using (StreamWriter writer = new StreamWriter(file))
                {
                    writer.Write("checkedValueInt = 2\ncheckedValueDouble = .2\ncheckedValueFloat = 3.14\ncheckedValueLong = 172\ncheckedValueString =\"hello \nHow are you ?\"\ncheckedValueBoolean = false");
                }

            }
            catch (IOException exception)
            {
                Console.WriteLine(exception);
            }

            pref = Preferences.Instance;
            prefTable = NetworkTable.GetTable("Preferences");
            check = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
        }
Exemplo n.º 12
0
        public async Task<PhotosResponse> GetPhotosAsync(Photoset photoset, User user, Preferences preferences, int page,
                                                         IProgress<ProgressUpdate> progress) {
            var progressUpdate = new ProgressUpdate {
                OperationText = "Getting list of photos...",
                ShowPercent = false
            };
            progress.Report(progressUpdate);

            var methodName = GetPhotosetMethodName(photoset.Type);

            var extraParams = new Dictionary<string, string> {
                {
                    ParameterNames.UserId, user.UserNsId
                }, {
                    ParameterNames.SafeSearch, preferences.SafetyLevel
                }, {
                    ParameterNames.PerPage,
                    preferences.PhotosPerPage.ToString(CultureInfo.InvariantCulture)
                }, {
                    ParameterNames.Page, page.ToString(CultureInfo.InvariantCulture)
                }
            };

            var isAlbum = photoset.Type == PhotosetType.Album;
            if (isAlbum) {
                extraParams.Add(ParameterNames.PhotosetId, photoset.Id);
            }

            var photosResponse = (Dictionary<string, object>)
                await this._oAuthManager.MakeAuthenticatedRequestAsync(methodName, extraParams);

            return photosResponse.GetPhotosResponseFromDictionary(isAlbum);
        }
Exemplo n.º 13
0
            public Data(Preferences cPreferences, string sValue)
            {
                _cPreferences = cPreferences;
                string[] aValues = sValue.ToLower().Split(':');
                _sRequest = aValues[0];
                _nTemplate = (1 < aValues.Length ? aValues[1].ToByte() : (byte)0);
				_sValue = (2 < aValues.Length ? aValues[2] : null );
            }
 private Preferences Validate(Preferences preferences) {
     var defaults = Preferences.GetDefault();
     if (preferences.LogLocation == null) {
         preferences.LogLevel = defaults.LogLevel;
         preferences.LogLocation = defaults.LogLocation;
     }
     return preferences;
 }
Exemplo n.º 15
0
        public void Create(string sWorkFolder, string sData)
        {
			_iEffect = null;
            _eStatus = BTL.EffectStatus.Idle;
            _dtStatusChanged = DateTime.Now;
            _sWorkFolder = sWorkFolder;
            _cPreferences = new Preferences(sWorkFolder, sData);
        }
        private async Task DownloadPhotos(IEnumerable<Photo> photos, CancellationToken cancellationToken, IProgress<ProgressUpdate> progress,
                                          Preferences preferences, Photoset photoset) {
            var progressUpdate = new ProgressUpdate {
                Cancellable = true,
                OperationText = "Downloading photos...",
                PercentDone = 0,
                ShowPercent = true
            };
            progress.Report(progressUpdate);

            var doneCount = 0;
            var photosList = photos as IList<Photo> ?? photos.ToList();
            var totalCount = photosList.Count();

            var imageDirectory = CreateDownloadFolder(preferences.DownloadLocation, photoset);

            foreach (var photo in photosList) {
                var photoUrl = photo.OriginalUrl;
                var photoExtension = "jpg";
                switch (preferences.DownloadSize) {
                    case PhotoDownloadSize.Medium:
                        photoUrl = photo.Medium800Url;
                        break;
                    case PhotoDownloadSize.Large:
                        photoUrl = photo.Large1024Url;
                        break;
                    case PhotoDownloadSize.Original:
                        photoUrl = photo.OriginalUrl;
                        photoExtension = photo.DownloadFormat;
                        break;
                }

                var photoWithPreferredTags = photo;

                if (preferences.NeedOriginalTags) {
                    photoWithPreferredTags = await this._originalTagsLogic.GetOriginalTagsTask(photo);
                }

                var photoName = preferences.TitleAsFilename ? GetSafeFilename(photo.Title) : photo.Id;
                var targetFileName = Path.Combine(imageDirectory.FullName,
                    string.Format("{0}.{1}", photoName, photoExtension));
                WriteMetaDataFile(photoWithPreferredTags, targetFileName, preferences);

                var request = WebRequest.Create(photoUrl);

                var buffer = new byte[4096];

                await DownloadAndSavePhoto(targetFileName, request, buffer);

                doneCount++;
                progressUpdate.PercentDone = doneCount * 100 / totalCount;
                progressUpdate.DownloadedPath = imageDirectory.FullName;
                progress.Report(progressUpdate);
                if (doneCount != totalCount) {
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
        }
Exemplo n.º 17
0
    internal bool NewPreferences()
    {
        preferences = new Preferences ();

        preferences.version = version;
        preferences.lastPlayerID = "lastPlayerID";

        return true;
    }
Exemplo n.º 18
0
    public ExportSession(Session mySession, Gtk.Window app1, Preferences preferences)
    {
        this.mySession = mySession;
        this.preferences = preferences;

        spreadsheetString = "";

        checkFile("none");
    }
Exemplo n.º 19
0
        public SipService(ServiceManager serviceManager)
        {
            this.preferences = new Preferences();
            this.sipCallback = new MySipCallback(this);
            this.debugCallback = new MySipDebugCallback();
            this.subPresence = new List<MySubscriptionSession>();

            this.manager = serviceManager;
        }
 public void Logout() {
     this._logic.Logout();
     if (this._preferences != null) {
         this._preferencesLogic.EmptyCacheDirectory(this._preferences.CacheLocation);
     }
     this._preferences = null;
     this._view.ShowSpinner(false);
     this._view.ShowLoggedOutControl();
 }
Exemplo n.º 21
0
        public async Task Download(IEnumerable<Photo> photos, CancellationToken cancellationToken, IProgress<ProgressUpdate> progress,
                                   Preferences preferences, Photoset photoset) {
            var photosList = photos as IList<Photo> ?? photos.ToList();
            if (!photosList.Any()) {
                return;
            }

            await this._downloadLogic.Download(photosList, cancellationToken, progress, preferences, photoset);
        }
Exemplo n.º 22
0
			public ProcessTarget(Preferences.Process cProcess)
			{
				dtMessageLast = DateTime.MinValue;
				nMessageLastAge = 0;
				bFail = false;

				sName = cProcess.sName;
				sOwner = cProcess.sOwner;
				sArguments = cProcess.sArguments;
			}
Exemplo n.º 23
0
 public OBDInterface()
 {
     m_commLog = new OBDCommLog();
     m_commLog.Delete();
     setDevice(1);
     m_listAllParameters = new ArrayList();
     m_listSupportedParameters = new ArrayList();
     m_userpreferences = LoadUserPreferences();
     m_settings = LoadCommSettings();
     m_listVehicleProfiles = LoadVehicleProfiles();
 }
Exemplo n.º 24
0
 public PreferencesTests()
 {
     prefs = new Preferences
     {
         WindowSize = new Size(10, 20),
         WindowLocation = new Point(30, 40),
         HorizontalSplitterDistance = 50,
         VerticalSplitterDistance = 60,
         IsMaximized = true
     };
 }
 public static string ReadPreference(Preferences pref)
 {
     if (prefs == null) {
         if (File.Exists(PrefsFilePath))
             prefs = File.ReadAllLines(PrefsFilePath);
         else {
             prefs = new string[0];
             File.WriteAllLines(PrefsFilePath, prefs);
         }
     }
     return prefs.Length > (int)pref ? prefs[(int)pref] : null;
 }
 public async void InitializeScreen() {
     try {
         this._view.ShowSpinner(true);
         this._view.ShowLoggedOutControl();
         this._preferences = this._preferencesLogic.GetPreferences();
         if (!await this._logic.IsUserLoggedInAsync(ApplyUser)) {
             Logout();
         }
     }
     catch (Exception ex) {
         _view.HandleException(ex);
     }
 }
 public static void SetPreference(Preferences pref, string value)
 {
     if (prefs.Length > (int)pref)
         prefs[(int)pref] = value;
     else {
         List<string> tempPrefs = prefs.ToList();
         while (tempPrefs.Count < (int)pref) {
             tempPrefs.Add(null);
         }
         tempPrefs.Add(value);
         prefs = tempPrefs.ToArray();
     }
     File.WriteAllLines(PrefsFilePath, prefs);
 }
Exemplo n.º 28
0
        public NaoTeacher(Preferences Preferences, Proxies Proxies, Scenario Scenario)
        {
            this.Preferences = Preferences;
            this.Proxies = Proxies;
            this.Scenario = Scenario;

            this.NaoCommenter = new NaoCommenter(this.Proxies);

            this.CurrentTrial = 0;

            // Create thread.
            this.Worker.DoWork += Run;
            this.Worker.WorkerSupportsCancellation = true;
        }
Exemplo n.º 29
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            User objUser = new User();
            //Set user session variable
            if (Session["sess_User"] != null)
            {
                objUser = (User)Session["sess_User"];
            }

            //Set Preferences in User Session
            Preferences preferences = new Preferences();

            preferences.MarketingCookies = radMarketingOn.Checked;
            preferences.MetricsCookies = radMetricsOn.Checked;
            preferences.PersonalisedCookies = radPersonalisedOn.Checked;
            preferences.SocialCookies = radSocialOn.Checked;

            objUser.Preferences = preferences;
            Session["sess_User"] = objUser;

            //Set Opt Out Cookie
            CookieHelper.AddUpdateOptInCookie(CookieKeyNames.MarketingCookies, radMarketingOn.Checked ? "Y" : "N");
            CookieHelper.AddUpdateOptInCookie(CookieKeyNames.MetricsCookies, radMetricsOn.Checked ? "Y" : "N");
            CookieHelper.AddUpdateOptInCookie(CookieKeyNames.PersonalisedCookies, radPersonalisedOn.Checked ? "Y" : "N");
            CookieHelper.AddUpdateOptInCookie(CookieKeyNames.SocialCookies, radSocialOn.Checked ? "Y" : "N");

            if (radPersonalisedOn.Checked == false)
            {
                //Delete personalisation cookie
                CookieHelper.DeleteCookie();
            }

            string classNames = pnlConfirmation.Attributes["class"];
            pnlConfirmation.Attributes.Add("class", classNames.Replace(" hidden", ""));

            classNames = pnlFormPrompt.Attributes["class"];
            pnlFormPrompt.Attributes.Add("class", classNames + " hidden");

            this.Page.FindControl("ScriptPh").Controls.Add(new LiteralControl(@"<script>
                    $(function(){
                        virginactive.reinit();
                    });
                </script>"));
            pnlForm.Update();
        }
 public Update UpdateAvailable(Preferences preferences) {
     var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
     Version latestVersion;
     var update = this._repository.Get();
     if (DateTime.Now.Subtract(TimeSpan.FromDays(1.0)) > update.LastChecked) {
         var request = WebRequest.Create("http://flickrdownloadr.com/build.number");
         var response = (HttpWebResponse) request.GetResponse();
         using (var reader = new StreamReader(response.GetResponseStream())) {
             latestVersion = new Version(reader.ReadToEnd());
         }
         update.LastChecked = DateTime.Now;
         update.LatestVersion = latestVersion.ToString();
     } else {
         latestVersion = new Version(update.LatestVersion);
     }
     update.Available = latestVersion.CompareTo(currentVersion) > 0;
     this._repository.Save(update);
     return update;
 }
Exemplo n.º 31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static async Task <OrderResponse> PlaceOrder(Order order)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();
            var json       = JsonConvert.SerializeObject(order);
            var content    = new StringContent(json, Encoding.UTF8, "application/json");

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.PostAsync(AppSettings.ApiUrl + "api/Orders", content);

            var jsonResult = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Token>(jsonResult);

            return(JsonConvert.DeserializeObject <OrderResponse>(jsonResult));
        }
 public Task <string> GetSavedTenantIdAsync()
 {
     return(Task.FromResult(Preferences.Get(TenantIdKey, string.Empty)));
 }
Exemplo n.º 33
0
 /// <summary>
 /// Force the update check
 /// </summary>
 /// <param name="background">true if you want to perform the update check in the background.</param>
 public void ForceCheckForUpdates(bool background)
 {
     View.CheckForUpdates(background);
     Preferences.instance().setProperty("update.check.last", DateTime.Now.Ticks);
 }
Exemplo n.º 34
0
 public void SaveVertCorrection(double VertCorrection)
 {
     Preferences.Set("VertCorr", VertCorrection);
 }
Exemplo n.º 35
0
 public override void Save()
 {
     Preferences.Set(Preference.MessagesFormLocation, FormLocation);
     Preferences.Set(Preference.MessagesFormSize, FormSize);
     Preferences.Save();
 }
Exemplo n.º 36
0
 private void TapLogout_Tapped(object sender, EventArgs e)
 {
     Preferences.Set("access_token", string.Empty);
     Preferences.Set("token_expiration_time", DateTime.Now.AddYears(-1));
     Application.Current.MainPage = new NavigationPage(new LoginPage());
 }
Exemplo n.º 37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public static async Task <Product> GetProductById(int productId)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "api/Products/" + productId);

            return(JsonConvert.DeserializeObject <Product>(response));
        }
Exemplo n.º 38
0
 public static string GetCurrentLanguageString()
 {
     return(Preferences.Get("CurrentLanguage", Language.Korean.ToString()));
 }
Exemplo n.º 39
0
 public static string GetShareBottomTextString()
 {
     return(Preferences.Get("ShareBottomText", ""));
 }
Exemplo n.º 40
0
 public static Color GetCurrentTextColor()
 {
     return(Color.FromHex(Preferences.Get("CustomTextColor", Constants.DEFAULT_TEXT_COLOR)));
 }
Exemplo n.º 41
0
 public static Color GetCurrentBackgroundDimColor()
 {
     return(Color.FromHex(Preferences.Get("CustomBackgroundDimColor", Constants.DEFAULT_BACKGROUND_DIM_COLOR)));
 }
Exemplo n.º 42
0
 public static double GetCurrentTextSize()
 {
     return(double.TryParse(Preferences.Get("TextSize", "17"), out var font) ? font : 17);
 }
Exemplo n.º 43
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static async Task <List <Category> > GetCategories()
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "api/Categories");

            return(JsonConvert.DeserializeObject <List <Category> >(response));
        }
Exemplo n.º 44
0
        public static async Task <List <MasterData> > GetDetectDatas(Guid detectId)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.GetStringAsync("https://weleaderapi.azurewebsites.net/api/MedicalDetect/p/r2/FFA95EB0-2B8A-47B1-AC10-BBEC1710D10D");

            return(JsonConvert.DeserializeObject <List <MasterData> >(response));
        }
Exemplo n.º 45
0
        public async Task <PhotosResponse> GetPhotosAsync(Photoset photoset, User user, Preferences preferences, int page,
                                                          IProgress <ProgressUpdate> progress, string albumProgress = null)
        {
            var isGettingAlbumPhotos = !string.IsNullOrEmpty(albumProgress);
            var progressUpdate       = new ProgressUpdate
            {
                OperationText = isGettingAlbumPhotos ? "Getting photos in album..." : "Getting list of photos...",
                ShowPercent   = isGettingAlbumPhotos,
                PercentDone   = 0,
                AlbumProgress = albumProgress
            };

            progress.Report(progressUpdate);

            var methodName = GetPhotosetMethodName(photoset.Type);

            var extraParams = new Dictionary <string, string>
            {
                {
                    ParameterNames.UserId, user.UserNsId
                },
                {
                    ParameterNames.SafeSearch, preferences.SafetyLevel
                },
                {
                    ParameterNames.PerPage,
                    preferences.PhotosPerPage.ToString(CultureInfo.InvariantCulture)
                },
                {
                    ParameterNames.Page, page.ToString(CultureInfo.InvariantCulture)
                }
            };

            var isAlbum = photoset.Type == PhotosetType.Album;

            if (isAlbum)
            {
                extraParams.Add(ParameterNames.PhotosetId, photoset.Id);
            }

            var photosResponse = (Dictionary <string, object>)
                                 await _oAuthManager.MakeAuthenticatedRequestAsync(methodName, extraParams);

            return(photosResponse.GetPhotosResponseFromDictionary(isAlbum));
        }
Exemplo n.º 46
0
        public override bool isTrusted(String hostName, X509Certificate[] certs)
        {
            X509Certificate2 serverCert = ConvertCertificate(certs[0]);
            X509Chain        chain      = new X509Chain();

            //todo Online revocation check. Preference.
            chain.ChainPolicy.RevocationMode      = X509RevocationMode.Offline; // | X509RevocationMode.Online
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0, 10);  // set timeout to 10 seconds
            chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.NoFlag;

            for (int index = 1; index < certs.Length; index++)
            {
                chain.ChainPolicy.ExtraStore.Add(ConvertCertificate(certs[index]));
            }
            chain.Build(serverCert);

            string errorFromChainStatus = GetErrorFromChainStatus(chain, hostName);
            bool   certError            = null != errorFromChainStatus;
            bool   hostnameMismatch     = !HostnameVerifier.CheckServerIdentity(certs[0], serverCert, hostName) &&
                                          !CheckForException(hostName, serverCert);

            // check if host name matches
            if (null == errorFromChainStatus && hostnameMismatch)
            {
                errorFromChainStatus = Locale.localizedString(
                    "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk. Would you like to connect to the server anyway?",
                    "Keychain").Replace("%@", hostName);
            }

            if (null != errorFromChainStatus)
            {
                while (true)
                {
                    TaskDialog   d = new TaskDialog();
                    DialogResult r =
                        d.ShowCommandBox(Locale.localizedString("This certificate is not valid", "Keychain"),
                                         Locale.localizedString("This certificate is not valid", "Keychain"),
                                         errorFromChainStatus,
                                         null,
                                         null,
                                         Locale.localizedString("Always Trust", "Keychain"),
                                         String.Format("{0}|{1}|{2}",
                                                       Locale.localizedString("Continue", "Credentials"),
                                                       Locale.localizedString("Disconnect"),
                                                       Locale.localizedString("Show Certificate", "Keychain")),
                                         false,
                                         SysIcons.Warning, SysIcons.Information);
                    if (r == DialogResult.OK)
                    {
                        if (d.CommandButtonResult == 0)
                        {
                            if (d.VerificationChecked)
                            {
                                if (certError)
                                {
                                    //todo can we use the Trusted People and Third Party Certificate Authority Store? Currently X509Chain is the problem.
                                    AddCertificate(serverCert, StoreName.Root);
                                }
                                if (hostnameMismatch)
                                {
                                    Preferences.instance().setProperty(hostName + ".certificate.accept",
                                                                       serverCert.SubjectName.Name);
                                }
                            }
                            return(true);
                        }
                        if (d.CommandButtonResult == 1)
                        {
                            return(false);
                        }
                        if (d.CommandButtonResult == 2)
                        {
                            X509Certificate2UI.DisplayCertificate(serverCert);
                        }
                    }
                }
            }
            return(true);
        }
Exemplo n.º 47
0
        public ProfilPage()
        {
            InitializeComponent();

            lblName.Text = Preferences.Get("userName", " ");
        }
Exemplo n.º 48
0
 public void SignOut()
 {
     AuthenticationToken = string.Empty;
     Preferences.Remove("authenticationKey");
     Preferences.Remove("tokenExpiration");
 }
Exemplo n.º 49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="addToCart"></param>
        /// <returns></returns>
        public static async Task <bool> AddItemsInCart(AddToCart addToCart)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();
            var json       = JsonConvert.SerializeObject(addToCart);
            var content    = new StringContent(json, Encoding.UTF8, "application/json");

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.PostAsync(AppSettings.ApiUrl + "api/ShoppingCartItems", content);

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Send data via email
        /// </summary>
        /// <returns></returns>
        public async Task OnEmailCmd()
        {
            CanNavigate = false;

            // ask for email address
            var result = await _dialogs.PromptAsync("", "Email Stocktake Data", placeholder : "email address");

            // validate email address
            if (!result.Ok || string.IsNullOrEmpty(result.Value.Trim()))
            {
                CanNavigate = true;
                return;
            }

            var emailAddress   = result.Value.Trim();
            var validator      = ViewModelLocator.Container.Resolve <EmailValidator>();
            var validateResult = validator.Validate(emailAddress);

            if (!validateResult.IsValid)
            {
                await _dialogs.AlertAsync(validateResult.Errors.First().ErrorMessage, "Error", "OK");

                CanNavigate = true;
                return;
            }

            // export data
            await ExportData();

            if (_exportedFile == null)
            {
                CanNavigate = true;
                return;
            }

            // get smtp details.
            var provider    = Preferences.Get(Constants.SmtpProvider, "Other");
            var smtpService = ViewModelLocator.Container.Resolve <ISmtpRepository>();
            var smtp        = await smtpService.GetSmtp(provider);

            try
            {
                CancellationTokenSource tokenSource = new CancellationTokenSource();

                var config = new ProgressDialogConfig()
                {
                    Title           = $"Emailing data'",
                    CancelText      = "Cancel",
                    IsDeterministic = false,
                    OnCancel        = tokenSource.Cancel
                };

                string msg;
                using (var progress = _dialogs.Progress(config))
                {
                    progress.Show();

                    // assing email address
                    _uploader.To         = emailAddress;
                    _uploader.SmtpDetail = smtp;

                    // get the from email address
                    var from = await SecureStorage.GetAsync(Constants.SmtpFrom);

                    _uploader.From = provider != "Other" ? emailAddress : from;

                    (_, msg) = await _uploader.Upload(_exportedFile);
                }

                await _dialogs.AlertAsync(msg);
            }
            catch (Exception ex)
            {
                await _dialogs.AlertAsync($"{ex.Message}", "ERROR", "OK");

                _logger.Error(ex, "Email data fail");
            }

            CanNavigate = true;
        }
Exemplo n.º 51
0
 public void SaveCalib(double Lat, double Lon)
 {
     Preferences.Set("Lat", Lat);
     Preferences.Set("Lon", Lon);
 }
Exemplo n.º 52
0
        static void Initialize()
        {
            // Note: Preferences need to be loaded when changing play mode
            // to initialize handle scale correctly.
                        #if !NEW_PREFERENCES_SETTINGS_PROVIDER
            Preferences.Load();
                        #else
            SpinePreferences.Load();
                        #endif

            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            string[] assets    = AssetDatabase.FindAssets("t:script SpineEditorUtilities");
            string   assetPath = AssetDatabase.GUIDToAssetPath(assets[0]);
            editorPath = Path.GetDirectoryName(assetPath).Replace('\\', '/');

            assets = AssetDatabase.FindAssets("t:texture icon-subMeshRenderer");
            if (assets.Length > 0)
            {
                assetPath     = AssetDatabase.GUIDToAssetPath(assets[0]);
                editorGUIPath = Path.GetDirectoryName(assetPath).Replace('\\', '/');
            }
            else
            {
                editorGUIPath = editorPath.Replace("/Utility", "/GUI");
            }
            Icons.Initialize();

            // Drag and Drop
                #if UNITY_2019_1_OR_NEWER
            SceneView.duringSceneGui -= DragAndDropInstantiation.SceneViewDragAndDrop;
            SceneView.duringSceneGui += DragAndDropInstantiation.SceneViewDragAndDrop;
                #else
            SceneView.onSceneGUIDelegate -= DragAndDropInstantiation.SceneViewDragAndDrop;
            SceneView.onSceneGUIDelegate += DragAndDropInstantiation.SceneViewDragAndDrop;
                #endif

            EditorApplication.hierarchyWindowItemOnGUI -= HierarchyHandler.HandleDragAndDrop;
            EditorApplication.hierarchyWindowItemOnGUI += HierarchyHandler.HandleDragAndDrop;

            // Hierarchy Icons
                        #if NEWPLAYMODECALLBACKS
            EditorApplication.playModeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged;
            EditorApplication.playModeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged;
            HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
                        #else
            EditorApplication.playmodeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged;
            EditorApplication.playmodeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged;
            HierarchyHandler.IconsOnPlaymodeStateChanged();
                        #endif

            // Data Refresh Edit Mode.
            // This prevents deserialized SkeletonData from persisting from play mode to edit mode.
                        #if NEWPLAYMODECALLBACKS
            EditorApplication.playModeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged;
            EditorApplication.playModeStateChanged += DataReloadHandler.OnPlaymodeStateChanged;
            DataReloadHandler.OnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode);
                        #else
            EditorApplication.playmodeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged;
            EditorApplication.playmodeStateChanged += DataReloadHandler.OnPlaymodeStateChanged;
            DataReloadHandler.OnPlaymodeStateChanged();
                        #endif

            if (SpineEditorUtilities.Preferences.textureImporterWarning)
            {
                IssueWarningsForUnrecommendedTextureSettings();
            }

            initialized = true;
        }
Exemplo n.º 53
0
 public void Awake()
 {
     _textMesh    = GetComponent <TextMesh>();
     _preferences = _gameRepository.Get().Preferences;
 }
Exemplo n.º 54
0
        /// <summary>
        /// Create each of the geometries, style them and add them to both the respective geometry type array and the 'AllShapes'array (used for centering the map)
        /// </summary>
        /// <returns>A dictionary of geometry layers</returns>
        public static Dictionary <string, ILayer> CreateShapes()
        {
            var layerDic = new Dictionary <string, ILayer>();
            var items    = DataDAO.getDataForMap(App.CurrentProjectId);


            if (items != null && items.Count > 0)
            {
                var points            = new List <Feature>();
                var polygons          = new List <Feature>();
                var lines             = new List <Feature>();
                var pointsNoRecords   = new List <Feature>();
                var polygonsNoRecords = new List <Feature>();
                var linesNoRecords    = new List <Feature>();
                var allShapes         = new List <Feature>();

                foreach (Shape item in items)
                {
                    var coords     = item.shapeGeom.Coordinates;
                    var coordCount = item.shapeGeom.Coordinates.Length;
                    var hasRecords = false;
                    using (SQLiteConnection conn = new SQLiteConnection(Preferences.Get("databaseLocation", "")))
                    {
                        hasRecords = conn.Table <Record>().Select(c => c).Where(c => c.geometry_fk == item.geomId).Count() > 0;
                    }
                    if (coordCount > 0)
                    {
                        if (coordCount == 1)
                        {
                            //Point
                            var coord = coords[0];

                            var point = SphericalMercator.FromLonLat(coord.X, coord.Y);

                            var feature = new Feature
                            {
                                Geometry  = point,
                                ["Name"]  = item.geomId.ToString(),
                                ["Label"] = item.title
                            };
                            feature.Styles.Add(new LabelStyle
                            {
                                Text                = item.title,
                                BackColor           = new Mapsui.Styles.Brush(Mapsui.Styles.Color.White),
                                HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                                Offset              = new Offset(20, 0, false)
                            });
                            if (hasRecords)
                            {
                                points.Add(feature);
                            }
                            else
                            {
                                pointsNoRecords.Add(feature);
                            }
                            allShapes.Add(feature);
                        }
                        else
                        {
                            var coord0 = coords[0];
                            var coordx = coords[coordCount - 1];
                            if (coord0.X == coordx.X && coord0.Y == coordx.Y)
                            {
                                //Polygon
                                var polygon = new Polygon();

                                var localCoords = coords;
                                foreach (NetTopologySuite.Geometries.Coordinate coord in localCoords)
                                {
                                    var pt = SphericalMercator.FromLonLat(coord.X, coord.Y);
                                    polygon.ExteriorRing.Vertices.Add(new Mapsui.Geometries.Point(pt.X, pt.Y));
                                }
                                var feature = new Feature
                                {
                                    Geometry  = polygon,
                                    ["Name"]  = item.geomId.ToString(),
                                    ["Label"] = item.title
                                };
                                feature.Styles.Add(new LabelStyle
                                {
                                    Text                = item.title,
                                    BackColor           = new Mapsui.Styles.Brush(Mapsui.Styles.Color.White),
                                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center
                                });

                                if (hasRecords)
                                {
                                    polygons.Add(feature);
                                }
                                else
                                {
                                    polygonsNoRecords.Add(feature);
                                }
                                allShapes.Add(feature);
                            }
                            else
                            {
                                //Line
                                var line        = new LineString();
                                var localCoords = coords;
                                foreach (NetTopologySuite.Geometries.Coordinate coord in localCoords)
                                {
                                    var pt = SphericalMercator.FromLonLat(coord.X, coord.Y);
                                    line.Vertices.Add(new Mapsui.Geometries.Point(pt.X, pt.Y));
                                }
                                var feature = new Feature
                                {
                                    Geometry  = line,
                                    ["Name"]  = item.geomId.ToString(),
                                    ["Label"] = item.title
                                };
                                feature.Styles.Add(new LabelStyle
                                {
                                    Text                = item.title,
                                    BackColor           = new Mapsui.Styles.Brush(Mapsui.Styles.Color.White),
                                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center
                                });
                                if (hasRecords)
                                {
                                    lines.Add(feature);
                                }
                                else
                                {
                                    linesNoRecords.Add(feature);
                                }
                                allShapes.Add(feature);
                            }
                        }
                    }
                }

                ILayer polygonLayer          = CreatePolygonLayer(polygons, new Mapsui.Styles.Color(0, 0, 200, 255), new Mapsui.Styles.Color(0, 0, 200, 32));
                ILayer pointLayer            = CreatePointLayer(points);
                ILayer lineLayer             = CreateLineLayer(lines, new Mapsui.Styles.Color(0, 0, 200, 255));
                ILayer polygonLayerNoRecords = CreatePolygonLayer(polygonsNoRecords, new Mapsui.Styles.Color(255, 166, 0, 255), new Mapsui.Styles.Color(255, 166, 0, 32));
                ILayer pointLayerNoRecords   = CreatePointLayerNoRecords(pointsNoRecords);
                ILayer lineLayerNoRecords    = CreateLineLayer(linesNoRecords, new Mapsui.Styles.Color(255, 166, 0, 255));
                ILayer allShapesLayer        = CreatePolygonLayer(allShapes, new Mapsui.Styles.Color(0, 0, 200, 255), new Mapsui.Styles.Color(0, 0, 200, 32)); //AllShapes layer is created merely to get bounding box of all shapes. It does not have the correct styles for showing all the shapes


                layerDic.Add("polygons", polygonLayer);
                layerDic.Add("lines", lineLayer);
                layerDic.Add("points", pointLayer);
                layerDic.Add("polygonsNoRecords", polygonLayerNoRecords);
                layerDic.Add("linesNoRecords", lineLayerNoRecords);
                layerDic.Add("pointsNoRecords", pointLayerNoRecords);
                layerDic.Add("all", allShapesLayer);
            }
            return(layerDic);
        }
Exemplo n.º 55
0
 public override void Load()
 {
     FormLocation = Preferences.Get <Point>(Preference.MessagesFormLocation);
     FormSize     = Preferences.Get <Size>(Preference.MessagesFormSize);
 }
Exemplo n.º 56
0
        /// <summary>
        /// Save each of the map layers on-screen (the extent is provided by the screen edges) to an mbtiles file
        /// </summary>
        /// <param name="extent"></param>
        public static async void saveMaps(Extent extent)
        {
            var basemap = Preferences.Get("BaseLayer", "swisstopo_pixelkarte"); //Check which basemap
            var cancel  = false;

            MessagingCenter.Subscribe <Application>(App.Current, "CancelMapSave", (sender) =>
            {
                //Listen for tile save updates and update the count
                cancel = true;
            });


            //Get the online layers
            var layers = GetLayersForMap(App.CurrentProjectId);
            //Create an array for adding the layers into in an ordered fashion
            var mapLayersTemp = new MapLayer[layers.Count];
            //Add online wms layers
            var layerStack = layers.OrderBy(o => o.order).ToList();
            //Calculate number of tiles
            var noOfLayers = 0;

            //Calculate number of tiles
            long noOfTiles = 0;

            foreach (var layer in layerStack)
            {
                if (layer.visible)
                {
                    var tileSource = WMSLayer.CreateTileSource(layer.url, layer.wmsLayer, "EPSG:3857");

                    foreach (var zoomScale in tileSource.Schema.Resolutions)
                    {
                        var tileInfos = tileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);
                        noOfTiles = noOfTiles + tileInfos.Count();
                    }
                    noOfLayers++;
                }
            }

            if (basemap == "swisstopo_pixelkarte")
            {
                string    swisstopoDbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/swisstopo.mbtiles");
                TileLayer swisstopo       = WMSLayer.CreatePixelkarteWMTSTileLayer();
                foreach (var zoomScale in swisstopo.TileSource.Schema.Resolutions)
                {
                    var stTileInfos = swisstopo.TileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);
                    noOfTiles = noOfTiles + stTileInfos.Count();
                }
            }
            else if (basemap == "swissimage")
            {
                string    swisstopoDbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/swissimage.mbtiles");
                TileLayer swisstopo       = WMSLayer.CreateSwissimageWMTSTileLayer();
                foreach (var zoomScale in swisstopo.TileSource.Schema.Resolutions)
                {
                    var stTileInfos = swisstopo.TileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);
                    noOfTiles = noOfTiles + stTileInfos.Count();
                }
            }
            else
            {
                string    osmDbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/osm.mbtiles");
                TileLayer osm       = OpenStreetMap.CreateTileLayer();
                foreach (var zoomScale in osm.TileSource.Schema.Resolutions)
                {
                    var osmTileInfos = osm.TileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);
                    noOfTiles = noOfTiles + osmTileInfos.Count();
                }
            }


            Console.WriteLine(noOfTiles + " tiles in " + (noOfLayers + 1) + " layers");


            //Save tiles
            long tilesSaved = 0;

            MessagingCenter.Subscribe <Application>(App.Current, "TileSavedInternal", (sender) =>
            {
                //Listen for tile save updates and update the count

                var message = tilesSaved + " von " + noOfTiles + " Kacheln aus " + (noOfLayers + 1) + " Ebenen gespeichert";
                if (noOfLayers == 0)
                {
                    message = tilesSaved + " von " + noOfTiles + " Kacheln aus " + (noOfLayers + 1) + " Ebene gespeichert";
                }

                Console.WriteLine(message);
                MessagingCenter.Send <Application, string>(App.Current, "TileSaved", message);
                if (tilesSaved >= noOfTiles - 5 || cancel)
                {
                    MessagingCenter.Send <Application, string>(App.Current, "TileSaved", String.Empty);
                    MessagingCenter.Unsubscribe <Application>(App.Current, "TileSavedInternal");
                    MapModel.MakeArrayOfLayers();
                }
            });

            var tasks = new List <Task>(); // Each layer has to be saved in a single thread due to database access, but we can save layers concurrently

            foreach (var layer in layerStack)
            {
                if (cancel)
                {
                    break;
                }
                if (layer.visible)
                {
                    var    layerNo    = Math.Max(layers.Count - layer.order, 0);
                    var    tileSource = WMSLayer.CreateTileSource(layer.url, layer.wmsLayer, "EPSG:3857");
                    string dbpath     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/" + layer.title + ".mbtiles");
                    //extent = tileSource.Schema.Extent;

                    var layerTask = Task.Run(async() =>
                    {
                        //Create the database
                        Mbtiles.CreateMbTiles(dbpath, layer, tileSource);

                        //Populate the database
                        foreach (var zoomScale in tileSource.Schema.Resolutions)
                        {
                            if (cancel)
                            {
                                break;
                            }
                            await Task.Run(async() =>
                            {
                                var tileInfos = tileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);

                                foreach (var tileInfo in tileInfos)
                                {
                                    if (cancel)
                                    {
                                        break;
                                    }
                                    await Task.Run(() =>
                                    {
                                        tilesSaved++;
                                        saveTile(tileSource, tileInfo, dbpath, layer);
                                    });
                                }
                            });
                        }
                        Console.WriteLine("Saving of 1 layer complete");
                    });
                    tasks.Add(layerTask);
                }
            }

            //Swisstopo layer
            var task = Task.Run(async() =>
            {
                string baselayerDbsavepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/swisstopo_pixelkarte.mbtiles");
                TileLayer baselayer        = WMSLayer.CreatePixelkarteWMTSTileLayer();

                //Create the database
                var baseLayer   = new BioDivCollectorXamarin.Models.DatabaseModel.Layer();
                baseLayer.title = "swisstopo pixelkarte";

                if (basemap == "osm") //OSM case
                {
                    baselayerDbsavepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/osm.mbtiles");
                    baselayer           = OpenStreetMap.CreateTileLayer();

                    //Create the database
                    baseLayer       = new BioDivCollectorXamarin.Models.DatabaseModel.Layer();
                    baseLayer.title = "osm";
                }
                else if (basemap == "swissimage") //Swissimage case
                {
                    baselayerDbsavepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "mbtiles/swissimage.mbtiles");
                    baselayer           = WMSLayer.CreateSwissimageWMTSTileLayer();

                    //Create the database
                    baseLayer       = new BioDivCollectorXamarin.Models.DatabaseModel.Layer();
                    baseLayer.title = "swissimage";
                }
                Mbtiles.CreateMbTiles(baselayerDbsavepath, baseLayer, baselayer.TileSource);

                //Populate the database
                foreach (var zoomScale in baselayer.TileSource.Schema.Resolutions)
                {
                    if (cancel)
                    {
                        break;
                    }
                    await Task.Run(async() =>
                    {
                        var baseLayerTileInfos = baselayer.TileSource.Schema.GetTileInfos(extent, zoomScale.Value.UnitsPerPixel);
                        foreach (var tileInfo in baseLayerTileInfos)
                        {
                            if (cancel)
                            {
                                break;
                            }
                            await Task.Run(() =>
                            {
                                tilesSaved++;
                                saveTile(baselayer.TileSource, tileInfo, baselayerDbsavepath, baseLayer);
                            });
                        }
                    });
                }
                Console.WriteLine("Baselayer saved");
            });

            tasks.Add(task);
            await Task.WhenAll(tasks);
        }
Exemplo n.º 57
0
 private void SetToolbar()
 {
     NotiToolbarItem.IsEnabled = Preferences.Get(SettingConstants.NOTI_ENABLED, false);
 }
Exemplo n.º 58
0
 private void TapLogout_Tapped(object sender, EventArgs e)
 {
     Preferences.Clear();
     Application.Current.MainPage = new NavigationPage(new SignupPge());
 }
Exemplo n.º 59
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task <bool> ClearShoppingCart(int userId)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.DeleteAsync(AppSettings.ApiUrl + "api/ShoppingCartItems/" + userId);

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 60
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task <TotalCartItem> GetTotalCartItems(int userId)
        {
            await TokenValidator.CheckTokenValidity();

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
            var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "api/ShoppingCartItems/TotalItems/" + userId);

            return(JsonConvert.DeserializeObject <TotalCartItem>(response));
        }