internal static async Task SetValueAsync(string name, string value)
        {
            var conn = StreetFooRuntime.GetSystemDatabase();

            // load an existing value...
            var setting = await conn.Table <SettingItem>().Where(v => v.Name == name).FirstOrDefaultAsync();

            if (setting != null)
            {
                // change and update...
                setting.Value = value;
                await conn.UpdateAsync(setting);
            }
            else
            {
                setting = new SettingItem()
                {
                    Name  = name,
                    Value = value
                };

                // save...
                await conn.InsertAsync(setting);
            }
        }
        // updates the local cache of the reports...
        public static async Task UpdateCacheFromServerAsync()
        {
            IEnumerable <ReportItem> reports = await GetSpooledReportsAsync();

            if (reports == null)
            {
                // create a service proxy to call up to the server...
                var proxy  = TinyIoCContainer.Current.Resolve <IGetReportsByUserServiceProxy>();
                var result = await proxy.GetReportsByUserAsync();

                // did it actually work?
                result.AssertNoErrors();

                // set...
                reports = result.Reports;
            }

            // update...
            var conn = StreetFooRuntime.GetUserDatabase();

            foreach (var report in reports)
            {
                // load the existing one, deleting it if we find it...
                var existing = await conn.Table <ReportItem>().Where(v => v.NativeId == report.NativeId).FirstOrDefaultAsync();

                if (existing != null)
                {
                    await conn.DeleteAsync(existing);
                }

                // create...
                await conn.InsertAsync(report);
            }
        }
        public async Task <bool> RestorePersistentLogonAsync()
        {
            var token = await SettingItem.GetValueAsync(LogonTokenKey);

            if (!(string.IsNullOrEmpty(token)))
            {
                var username = await SettingItem.GetValueAsync(LastUsernameKey);

                if (!(string.IsNullOrEmpty(username)))
                {
                    // logon...
                    await StreetFooRuntime.LogonAsync(username, token);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 4
0
        private static async Task SetValueAsyncInternal(string name, string value, SQLiteAsyncConnection conn)
        {
            // if we don't have a connection, assume the system one...
            if (conn == null)
            {
                conn = StreetFooRuntime.GetSystemDatabase();
            }

            // load an existing value...
            var setting = await conn.Table <SettingItem>().Where(v => v.Name == name).FirstOrDefaultAsync();

            if (setting != null)
            {
                // change and update...
                setting.Value = value;
                await conn.UpdateAsync(setting);
            }
            else
            {
                setting = new SettingItem()
                {
                    Name  = name,
                    Value = value
                };

                // save...
                await conn.InsertAsync(setting);
            }
        }
        internal static async Task <ReportItem> CreateReportItemAsync(string title, string description,
                                                                      IMappablePoint point, IStorageFile image)
        {
            var item = new ReportItem()
            {
                Title       = title,
                Description = description,
                NativeId    = Guid.NewGuid().ToString(),
                Status      = ReportItemStatus.New
            };

            item.SetLocation(point);

            // save...
            var conn = StreetFooRuntime.GetUserDatabase();
            await conn.InsertAsync(item);

            // stage the image...
            if (image != null)
            {
                // new path...
                var manager = new ReportImageCacheManager();
                var folder  = await manager.GetCacheFolderAsync();

                // create...
                await image.CopyAsync(folder, item.NativeId + ".jpg");
            }

            // return...
            return(item);
        }
        //private static async Task EnsureSearchSuggestionsPopulated()
        //{
        //    // get all the items that we currently have...
        //    var conn = StreetFooRuntime.GetUserDatabase();
        //    var suggestions = await conn.Table<SearchSuggestionItem>().ToListAsync();

        //    // do we have anything?
        //    if (!(suggestions.Any()))
        //    {
        //        // get all the items...
        //        var reports = await GetAllFromCacheAsync();

        //        // go through and dig out the words...
        //        List<string> words = new List<string>();
        //        var regex = new Regex(@"\b\w+\b", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        //        foreach (var report in reports)
        //        {
        //            foreach (Match match in regex.Matches(report.Title))
        //            {
        //                var word = match.Value;
        //                if (word.Length > 2)
        //                {
        //                    word = word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower();
        //                    if (!(words.Contains(word)))
        //                        words.Add(word);
        //                }
        //            }
        //        }

        //        // create suggestions from that...
        //        foreach (var word in words)
        //        {
        //            var suggestion = new SearchSuggestionItem()
        //            {
        //                Suggestion = word
        //            };
        //            await conn.InsertAsync(suggestion);
        //        }
        //    }
        //}

        public static async Task <Dictionary <string, List <ReportItem> > > GetSearchSuggestionsAsync(string queryText)
        {
            // get everything and sort by the title...
            var conn    = StreetFooRuntime.GetUserDatabase();
            var reports = await conn.QueryAsync <ReportItem>("select * from ReportItem where title like ? order by title",
                                                             new object[] { queryText + "%" });

            // walk and build a distinct list of matches...
            var results = new Dictionary <string, List <ReportItem> >(StringComparer.CurrentCultureIgnoreCase);

            foreach (var report in reports)
            {
                // if we don't have a result with that title...
                if (!(results.ContainsKey(report.Title)))
                {
                    results[report.Title] = new List <ReportItem>();
                }

                // add...
                results[report.Title].Add(report);
            }

            // return...
            return(results);
        }
        public static async Task <ReportItem> GetByIdAsync(int id)
        {
            var conn  = StreetFooRuntime.GetUserDatabase();
            var query = conn.Table <ReportItem>().Where(v => v.Id == id);

            // return...
            return((await query.ToListAsync()).FirstOrDefault());
        }
        internal static async Task <IEnumerable <ReportItem> > SearchCacheAsync(string queryText)
        {
            // run a regex to extract out the words...
            var words = new List <string>();
            var regex = new Regex(@"\b\w+\b", RegexOptions.Singleline | RegexOptions.IgnoreCase);

            foreach (Match match in regex.Matches(queryText))
            {
                var word = match.Value.ToLower();
                if (!(words.Contains(word)))
                {
                    words.Add(word);
                }
            }

            // do we have anything to find?
            if (words.Count > 0)
            {
                // build up some sql...
                var sql        = new StringBuilder();
                var parameters = new List <object>();
                sql.Append("select * from reportitem where ");
                bool first = true;
                foreach (var word in words)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        sql.Append(" and ");
                    }

                    // add...
                    sql.Append("title like ?");
                    parameters.Add("%" + word + "%");
                }

                // run...
                var conn = StreetFooRuntime.GetUserDatabase();
                return(await conn.QueryAsync <ReportItem>(sql.ToString(), parameters.ToArray()));
            }
            else
            {
                // return the lot...
                return(await GetAllFromCacheAsync());
            }
        }
        private async void DoLogon(CommandExecutionContext context)
        {
            // validate...
            ErrorBucket errors = new ErrorBucket();

            Validate(errors);

            // ok?
            if (!(errors.HasErrors))
            {
                // get a handler...
                var proxy = TinyIoCContainer.Current.Resolve <ILogonServiceProxy>();

                // call...
                using (this.EnterBusy())
                {
                    var result = await proxy.LogonAsync(this.Username, this.Password);

                    if (!(result.HasErrors))
                    {
                        // logon... pass through the username as each user gets their own database...
                        await StreetFooRuntime.LogonAsync(this.Username, result.Token);

                        // while we're here - store a setting containing the logon name of the user...
                        await SettingItem.SetValueAsync(LastUsernameKey, this.Username);

                        // remember the user?
                        if (this.RememberMe)
                        {
                            await SettingItem.SetValueAsync(LogonTokenKey, result.Token);
                        }

                        // show the reports page...
                        this.Host.ShowView(typeof(IReportsPageViewModel));
                    }
                    else
                    {
                        errors.CopyFrom(result);
                    }
                }
            }

            // errors?
            if (errors.HasErrors)
            {
                await this.Host.ShowAlertAsync(errors);
            }
        }
        internal static async Task <string> GetValueAsync(string name)
        {
            var conn = StreetFooRuntime.GetSystemDatabase();

            // load any existing value...
            var setting = (await conn.Table <SettingItem>().Where(v => v.Name == name).ToListAsync()).FirstOrDefault();

            if (setting != null)
            {
                return(setting.Value);
            }
            else
            {
                return(null);
            }
        }
        // runs the operation...
        public async Task RunAsync(IBackgroundTaskInstance instance)
        {
            // configure the logging system to use a streaming target...
            try
            {
                LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal,
                                                                 new FileStreamingTarget());
            }
            catch
            {
                // no-op... waiting for a change in MetroLog to see if the config
                // has already been done...
            }

            // logging is a bit tricky as we have to gather all of the messages
            // and flush them out...
            var logTasks = new List <Task <LogWriteOperation[]> >();

            // do some logging...
            var asyncLogger = (ILoggerAsync)this.Logger;

            logTasks.Add(asyncLogger.InfoAsync("Started background task '{0}' (#{1})...",
                                               instance.Task.Name, instance.Task.TaskId));

            // run...
            try
            {
                // start the app...
                await StreetFooRuntime.Start("Tasks");

                // defer...
                await DoRunAsync(instance);
            }
            catch (Exception ex)
            {
                logTasks.Add(asyncLogger.FatalAsync(string.Format("Background task '{0}' (#{1}) failed.",
                                                                  instance.Task.Name, instance.Task.TaskId), ex));
            }

            // finish...
            logTasks.Add(asyncLogger.InfoAsync("Finished background task '{0}' (#{1}).",
                                               instance.Task.Name, instance.Task.TaskId));

            // wait...
            await Task.WhenAll(logTasks);
        }
        internal async Task UpdateAsync(IStorageFile newImage)
        {
            // set the flag...
            this.Status = ReportItemStatus.Updated;

            // do we have a new image?
            if (newImage != null)
            {
                // set the flag...
                this.ImageChanged = true;

                // copy...
                await this.StageImageAsync(newImage);
            }

            // update the database...
            var conn = StreetFooRuntime.GetUserDatabase();
            await conn.UpdateAsync(this);
        }
        // sends the update to the server...
        internal async Task PushServerUpdateAsync()
        {
            this.Logger.Info("Pushing update for #{0} ({1})...", this.Id, this.Status);

            // what happened?
            if (this.Status == ReportItemStatus.Unchanged)
            {
                // no-op...
            }
            else if (this.Status == ReportItemStatus.New)
            {
                // insert...
                var service = new CreateReportServiceProxy();
                var result  = await service.CreateReportAsync(this.Title, this.Description, this.Longitude, this.Latitude);

                // patch back the native ID, if it worked...
                if (!(result.HasErrors))
                {
                    this.NativeId = result.NativeId;
                }
                else
                {
                    this.Logger.Warn("Failed to insert report: " + result.GetErrorsAsString());
                }
            }
            else
            {
                throw new NotSupportedException(string.Format("Cannot handle '{0}'.", this.Status));
            }

            // push the image update...
            await PushServerImageUpdateAsync();

            // reset our flag...
            this.Status = ReportItemStatus.Unchanged;

            // set...
            var conn = StreetFooRuntime.GetUserDatabase();
            await conn.UpdateAsync(this);
        }
        // indicates whether the cache is empty...
        internal static async Task <bool> IsCacheEmpty()
        {
            var conn = StreetFooRuntime.GetUserDatabase();

            return((await conn.Table <ReportItem>().FirstOrDefaultAsync()) == null);
        }
        private static async Task <IEnumerable <ReportItem> > GetLocallyChangedReportsAsync()
        {
            var conn = StreetFooRuntime.GetUserDatabase();

            return(await conn.Table <ReportItem>().Where(v => v.Status != ReportItemStatus.Unchanged || v.ImageChanged).ToListAsync());
        }
        // reads the local cache and populates a collection...
        internal static async Task <IEnumerable <ReportItem> > GetAllFromCacheAsync()
        {
            var conn = StreetFooRuntime.GetUserDatabase();

            return(await conn.Table <ReportItem>().ToListAsync());
        }
Exemplo n.º 17
0
 public static async Task <string> GetValueAsyncForUser(string name)
 {
     return(await GetValueAsyncInternal(name, StreetFooRuntime.GetUserDatabase()));
 }
Exemplo n.º 18
0
 public static async Task SetValueAsyncForUser(string name, string value)
 {
     await SetValueAsyncInternal(name, value, StreetFooRuntime.GetUserDatabase());
 }