Esempio n. 1
0
        static public async Task <bool> AddFeed(string FeedLink)
        {
            try
            {
                string[][]    RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                StringContent PostContent   = new StringContent("quickadd=" + WebUtility.HtmlEncode(FeedLink), Encoding.UTF8, "application/x-www-form-urlencoded");
                Uri           PostUri       = new Uri(ApiConnectionUrl + "subscription/quickadd");

                string PostHttp = await AVDownloader.SendPostRequestAsync(10000, "News Scroll", RequestHeader, PostUri, PostContent);

                JObject WebJObject = JObject.Parse(PostHttp);
                if (WebJObject["numResults"].ToString() == "0")
                {
                    await new MessagePopup().OpenPopup("Invalid feed link", "The entered feed link is invalid or does not contain a feed, please check your link and try again.", "Ok", "", "", "", "", false);
                    //System.Diagnostics.Debug.WriteLine(WebJObject["error"].ToString());
                    return(false);
                }
                else
                {
                    await new MessagePopup().OpenPopup("Feed has been added", "Your new feed has been added to your account, and will appear on the next feed refresh.", "Ok", "", "", "", "", false);
                    return(true);
                }
            }
            catch
            {
                await new MessagePopup().OpenPopup("Failed to add feed", "Please check your account settings, internet connection and try again.", "Ok", "", "", "", "", false);
                return(false);
            }
        }
Esempio n. 2
0
        static public async Task <bool> AllNewsItems(bool Preload, bool IgnoreDate, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading latest items...", true);
                }
                Debug.WriteLine("Downloading latest items...");

                //Date time calculations
                Int64    UnixTimeTicks    = 0;
                DateTime RemoveItemsRange = DateTime.UtcNow.AddDays(-Convert.ToDouble(AppVariables.ApplicationSettings["RemoveItemsRange"]));
                if (AppVariables.ApplicationSettings["LastItemsUpdate"].ToString() == "Never")
                {
                    UnixTimeTicks = (RemoveItemsRange.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000000; //Second
                }
                else
                {
                    UnixTimeTicks = ((Convert.ToDateTime(AppVariables.ApplicationSettings["LastItemsUpdate"], AppVariables.CultureInfoEnglish).AddMinutes(-15)).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000000; //Second
                }

                //Set the last update time string
                string LastUpdate = DateTime.UtcNow.ToString(AppVariables.CultureInfoEnglish);

                string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                string     DownloadString = await AVDownloader.DownloadStringAsync(20000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "stream/contents?output=json&n=" + AppVariables.ItemsMaximumLoad + "&ot=" + UnixTimeTicks));

                bool UpdatedItems = await DownloadToTableItemList(Preload, IgnoreDate, DownloadString, Silent, EnableUI);

                if (UpdatedItems)
                {
                    //Save the last update time string
                    AppVariables.ApplicationSettings["LastItemsUpdate"] = LastUpdate;

                    if (EnableUI)
                    {
                        await EventProgressEnableUI();
                    }
                    return(true);
                }
                else
                {
                    await EventProgressEnableUI();

                    return(false);
                }
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 3
0
        //Download platform version id information
        public async Task <ApiIGDBPlatformVersions[]> ApiIGDBDownloadPlatformVersions(string platformId)
        {
            try
            {
                Debug.WriteLine("Downloading platform versions for: " + platformId);

                //Authenticate with Twitch
                string authAccessToken = await Api_Twitch_Authenticate();

                if (string.IsNullOrWhiteSpace(authAccessToken))
                {
                    return(null);
                }

                //Set request headers
                string[]   requestAccept        = new[] { "Accept", "application/json" };
                string[]   requestClientID      = new[] { "Client-ID", vApiIGDBClientID };
                string[]   requestAuthorization = new[] { "Authorization", "Bearer " + authAccessToken };
                string[][] requestHeaders       = new string[][] { requestAccept, requestClientID, requestAuthorization };

                //Create request uri
                Uri requestUri = new Uri("https://api.igdb.com/v4/platform_versions");

                //Create request body
                string        requestBodyString        = "fields *; limit 100; where id = " + platformId + ";";
                StringContent requestBodyStringContent = new StringContent(requestBodyString, Encoding.UTF8, "application/text");

                //Download available platform versions
                string resultSearch = await AVDownloader.SendPostRequestAsync(5000, "CtrlUI", requestHeaders, requestUri, requestBodyStringContent);

                if (string.IsNullOrWhiteSpace(resultSearch))
                {
                    Debug.WriteLine("Failed downloading platform versions.");
                    return(null);
                }

                //Check if status is set
                if (resultSearch.Contains("\"status\"") && resultSearch.Contains("\"type\""))
                {
                    Debug.WriteLine("Received invalid platform versions data.");
                    return(null);
                }

                //Return platform versions
                return(JsonConvert.DeserializeObject <ApiIGDBPlatformVersions[]>(resultSearch));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading platform versions: " + ex.Message);
                return(null);
            }
        }
Esempio n. 4
0
        //Download all available games
        public async Task <IEnumerable <ApiIGDBGames> > ApiIGDB_DownloadGames(string gameName)
        {
            try
            {
                Debug.WriteLine("Downloading games for: " + gameName);

                //Authenticate with Twitch
                string authAccessToken = await ApiTwitch_Authenticate();

                if (string.IsNullOrWhiteSpace(authAccessToken))
                {
                    return(null);
                }

                //Set request headers
                string[]   requestAccept        = new[] { "Accept", "application/json" };
                string[]   requestClientID      = new[] { "Client-ID", vApiIGDBClientID };
                string[]   requestAuthorization = new[] { "Authorization", "Bearer " + authAccessToken };
                string[][] requestHeaders       = new string[][] { requestAccept, requestClientID, requestAuthorization };

                //Create request uri
                Uri requestUri = new Uri("https://api.igdb.com/v4/games");

                //Create request body
                string        requestBodyString        = "fields *; limit 100; search \"" + gameName + "\";";
                StringContent requestBodyStringContent = new StringContent(requestBodyString, Encoding.UTF8, "application/text");

                //Download available games
                string resultSearch = await AVDownloader.SendPostRequestAsync(5000, "CtrlUI", requestHeaders, requestUri, requestBodyStringContent);

                if (string.IsNullOrWhiteSpace(resultSearch))
                {
                    Debug.WriteLine("Failed downloading games.");
                    return(null);
                }

                //Check if status is set
                if (resultSearch.Contains("\"status\"") && resultSearch.Contains("\"type\""))
                {
                    Debug.WriteLine("Received invalid games data.");
                    return(null);
                }

                //Return games sorted
                return(JsonConvert.DeserializeObject <IEnumerable <ApiIGDBGames> >(resultSearch).OrderBy(x => x.name));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading games: " + ex.Message);
                return(null);
            }
        }
Esempio n. 5
0
        //Download image id information
        public async Task <string> Api_Twitch_Authenticate()
        {
            try
            {
                //Check if auth token is cached
                if (vApiIGDBTokenExpire != null && DateTime.Now < vApiIGDBTokenExpire)
                {
                    Debug.WriteLine("Returning auth cache from Twitch.");
                    return(vApiIGDBTokenCache);
                }

                Debug.WriteLine("Authenticating with Twitch.");

                //Set request headers
                string[]   requestAccept  = new[] { "Accept", "application/json" };
                string[][] requestHeaders = new string[][] { requestAccept };

                //Create request uri
                Uri requestUri = new Uri("https://id.twitch.tv/oauth2/token?client_id=" + vApiIGDBClientID + "&client_secret=" + vApiIGDBAuthorization + "&grant_type=client_credentials");

                //Authenticate with Twitch
                string resultAuth = await AVDownloader.SendPostRequestAsync(5000, "CtrlUI", requestHeaders, requestUri, null);

                if (string.IsNullOrWhiteSpace(resultAuth))
                {
                    Debug.WriteLine("Failed authenticating with Twitch, no connection.");
                    return(string.Empty);
                }

                //Deserialize json string
                ApiTwitchOauth2 jsonAuth = JsonConvert.DeserializeObject <ApiTwitchOauth2>(resultAuth);

                //Check if authenticated
                if (!string.IsNullOrWhiteSpace(jsonAuth.access_token))
                {
                    vApiIGDBTokenCache  = jsonAuth.access_token;
                    vApiIGDBTokenExpire = DateTime.Now.AddSeconds(jsonAuth.expires_in).AddSeconds(-30);
                    return(vApiIGDBTokenCache);
                }
                else
                {
                    Debug.WriteLine("Failed authenticating with Twitch: " + jsonAuth.message);
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed authenticating with Twitch: " + ex.Message);
                return(string.Empty);
            }
        }
Esempio n. 6
0
        static public async Task <bool> SingleItem(string DownloadId, bool Preload, bool IgnoreDate, bool Silent, bool EnableUI)
        {
            try
            {
                string     DownloadItems = DownloadId.Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };

                Uri    DownloadUri    = new Uri(ApiConnectionUrl + "stream/items/contents?output=json&i=" + DownloadItems);
                string DownloadString = await AVDownloader.DownloadStringAsync(7500, "News Scroll", RequestHeader, DownloadUri);

                return(await DownloadToTableItemList(Preload, IgnoreDate, DownloadString, Silent, EnableUI));
            }
            catch { return(false); }
        }
Esempio n. 7
0
        static public async Task <bool> MultiItems(string DownloadItemIds, bool Preload, bool IgnoreDate, bool Silent, bool EnableUI)
        {
            try
            {
                string     DownloadItems = DownloadItemIds.Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };

                HttpStringContent PostContent = new HttpStringContent(DownloadItems, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                Uri PostUri = new Uri(ApiConnectionUrl + "stream/items/contents?output=json");
                HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(20000, "News Scroll", RequestHeader, PostUri, PostContent);

                return(await DownloadToTableItemList(Preload, IgnoreDate, PostHttp.Content.ToString(), Silent, EnableUI));
            }
            catch { return(false); }
        }
Esempio n. 8
0
        static public async Task <bool> DeleteFeed(string FeedId)
        {
            try
            {
                string[][]          RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                HttpStringContent   PostContent   = new HttpStringContent("ac=unsubscribe&s=feed/" + FeedId, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                HttpResponseMessage PostHttp      = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "subscription/edit"), PostContent);

                if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                {
                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Clear feed from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableFeeds WHERE feed_id = ('" + FeedId + "')");

                    //Clear items from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableItems WHERE item_feed_id = ('" + FeedId + "') AND item_star_status = ('0')");

                    //Delete the feed icon
                    IStorageItem LocalFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(FeedId + ".png");

                    if (LocalFile != null)
                    {
                        try { await LocalFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch { }
                    }

                    Debug.WriteLine("Deleted the feed and items off: " + FeedId);
                    return(true);
                }
                else
                {
                    Debug.WriteLine("Failed to delete feed: " + FeedId + " / server error.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to delete feed: " + FeedId + " / " + ex.Message);
                return(false);
            }
        }
Esempio n. 9
0
        //Download igdb genres
        public async Task ApiIGDBDownloadGenres()
        {
            try
            {
                Debug.WriteLine("Downloading IGDB genres.");

                //Authenticate with Twitch
                string authAccessToken = await Api_Twitch_Authenticate();

                if (string.IsNullOrWhiteSpace(authAccessToken))
                {
                    return;
                }

                //Set request headers
                string[]   requestAccept        = new[] { "Accept", "application/json" };
                string[]   requestClientID      = new[] { "Client-ID", vApiIGDBClientID };
                string[]   requestAuthorization = new[] { "Authorization", "Bearer " + authAccessToken };
                string[][] requestHeaders       = new string[][] { requestAccept, requestClientID, requestAuthorization };

                //Create request uri
                Uri requestUri = new Uri("https://api.igdb.com/v4/genres");

                //Create request body
                string        requestBodyString        = "fields *; limit 500; sort id asc;";
                StringContent requestBodyStringContent = new StringContent(requestBodyString, Encoding.UTF8, "application/text");

                //Download igdb genres
                string resultSearch = await AVDownloader.SendPostRequestAsync(5000, "CtrlUI", requestHeaders, requestUri, requestBodyStringContent);

                if (string.IsNullOrWhiteSpace(resultSearch))
                {
                    Debug.WriteLine("Failed downloading IGDB genres.");
                    return;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading IGDB genres: " + ex.Message);
                return;
            }
        }
Esempio n. 10
0
        //Login to the api
        static public async Task <bool> Login(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    EventProgressDisableUI("Logging into The Old Reader...", true);
                }
                Debug.WriteLine("Logging into The Old Reader.");

                string        PostString  = "client=NewsScroll&accountType=HOSTED_OR_GOOGLE&service=reader&output=json&Email=" + WebUtility.HtmlEncode(AppSettingLoad("ApiAccount").ToString()) + "&Passwd=" + WebUtility.HtmlEncode(AppSettingLoad("ApiPassword").ToString());
                StringContent PostContent = new StringContent(PostString, Encoding.UTF8, "application/x-www-form-urlencoded");
                Uri           PostUri     = new Uri(ApiConnectionUrl + "accounts/ClientLogin");

                string PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", null, PostUri, PostContent);

                JObject WebJObject = JObject.Parse(PostHttp);
                if (WebJObject["Auth"] != null)
                {
                    ApiMessageError = string.Empty;
                    await AppSettingSave("ConnectApiAuth", WebJObject["Auth"].ToString());

                    if (EnableUI)
                    {
                        EventProgressEnableUI();
                    }
                    return(true);
                }
                else
                {
                    EventProgressEnableUI();
                    return(false);
                }
            }
            catch
            {
                EventProgressEnableUI();
                return(false);
            }
        }
Esempio n. 11
0
        //Mark item as un/read from string list
        static public async Task <bool> MarkItemReadStringList(List <string> MarkIds, bool MarkType)
        {
            try
            {
                //Add items to post string
                string PostStringItemIds = string.Empty;
                foreach (string ItemId in MarkIds)
                {
                    PostStringItemIds += "&i=" + ItemId;
                }

                string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };

                StringContent PostContent;
                if (MarkType)
                {
                    PostContent = new StringContent("a=user/-/state/com.google/read" + PostStringItemIds, Encoding.UTF8, "application/x-www-form-urlencoded");
                }
                else
                {
                    PostContent = new StringContent("r=user/-/state/com.google/read" + PostStringItemIds, Encoding.UTF8, "application/x-www-form-urlencoded");
                }
                Uri PostUri = new Uri(ApiConnectionUrl + "edit-tag");

                string PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, PostUri, PostContent);

                if (PostHttp != null && (PostHttp == "OK" || PostHttp.Contains("<error>Not found</error>")))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 12
0
        //Login to the api
        static public async Task <bool> Login(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Logging into The Old Reader...", true);
                }
                Debug.WriteLine("Logging into The Old Reader.");

                HttpStringContent   PostContent = new HttpStringContent("client=NewsScroll&accountType=HOSTED_OR_GOOGLE&service=reader&output=json&Email=" + WebUtility.HtmlEncode(AppVariables.ApplicationSettings["ApiAccount"].ToString()) + "&Passwd=" + WebUtility.HtmlEncode(AppVariables.ApplicationSettings["ApiPassword"].ToString()), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                HttpResponseMessage PostHttp    = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", null, new Uri(ApiConnectionUrl + "accounts/ClientLogin"), PostContent);

                JObject WebJObject = JObject.Parse(PostHttp.Content.ToString());
                if (WebJObject["Auth"] != null)
                {
                    ApiMessageError = String.Empty;
                    AppVariables.ApplicationSettings["ConnectApiAuth"] = WebJObject["Auth"].ToString();

                    if (EnableUI)
                    {
                        await EventProgressEnableUI();
                    }
                    return(true);
                }
                else
                {
                    await EventProgressEnableUI();

                    return(false);
                }
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 13
0
        static public async Task <bool> DeleteFeed(string FeedId)
        {
            try
            {
                string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };

                string        PostString  = "ac=unsubscribe&s=feed/" + FeedId;
                StringContent PostContent = new StringContent(PostString, Encoding.UTF8, "application/x-www-form-urlencoded");
                Uri           PostUri     = new Uri(ApiConnectionUrl + "subscription/edit");

                string PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, PostUri, PostContent);

                if (PostHttp != null && (PostHttp == "OK" || PostHttp.Contains("<error>Not found</error>")))
                {
                    //Clear feed from database
                    await vSQLConnection.ExecuteAsync("DELETE FROM TableFeeds WHERE feed_id = ('" + FeedId + "')");

                    //Clear items from database
                    await vSQLConnection.ExecuteAsync("DELETE FROM TableItems WHERE item_feed_id = ('" + FeedId + "') AND item_star_status = ('0')");

                    //Delete the feed icon
                    AVFiles.File_Delete(FeedId + ".png", true);

                    Debug.WriteLine("Deleted the feed and items off: " + FeedId);
                    return(true);
                }
                else
                {
                    Debug.WriteLine("Failed to delete feed: " + FeedId + " / server error.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to delete feed: " + FeedId + " / " + ex.Message);
                return(false);
            }
        }
Esempio n. 14
0
        //Mark item as un/read from string list
        static public async Task <bool> MarkItemReadStringList(List <String> MarkIds, bool MarkType)
        {
            try
            {
                //Add items to post string
                string PostStringItemIds = String.Empty;
                foreach (String ItemId in MarkIds)
                {
                    PostStringItemIds += "&i=" + ItemId;
                }

                string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };

                HttpStringContent PostContent;
                if (MarkType)
                {
                    PostContent = new HttpStringContent("a=user/-/state/com.google/read" + PostStringItemIds, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                }
                else
                {
                    PostContent = new HttpStringContent("r=user/-/state/com.google/read" + PostStringItemIds, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                }

                HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "edit-tag"), PostContent);

                if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch { return(false); }
        }
Esempio n. 15
0
        //Mark items till as read
        public static async Task <bool> MarkReadTill(ObservableCollection <Items> UpdateList, Items EndItem, bool Confirm, bool Silent, bool EnableUI)
        {
            try
            {
                if (Confirm)
                {
                    Int32 MsgBoxResult = await AVMessageBox.Popup("Mark items read till item", "Do you want to mark all items for the selected feed till this item as read?", "Mark read till item", "", "", "", "", true);

                    if (MsgBoxResult == 0)
                    {
                        return(false);
                    }
                }

                bool   MarkStatus = false;
                string EndItemId  = EndItem.item_id;

                //Check the selected items
                List <Items> TableEditItems = UpdateList.Where(x => x.item_id == EndItemId || x.item_read_status == Visibility.Collapsed).ToList();

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Off marking read till item...", true);
                    }
                    Debug.WriteLine("Off marking read till item...");

                    //Add items to string list
                    List <String> ReadItemIds = new List <String>();
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        ReadItemIds.Add(NewsItemId);

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the string list.");
                            break;
                        }
                    }

                    await AddOfflineSync(ReadItemIds, "Read");

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Marking read till item...", true);
                    }
                    Debug.WriteLine("Marking read till item...");

                    //Add items to post string
                    string PostStringItemIds = String.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        PostStringItemIds += "&i=" + NewsItemId;

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the post string.");
                            break;
                        }
                    }

                    string[][]        RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                    HttpStringContent PostContent   = new HttpStringContent("a=user/-/state/com.google/read" + PostStringItemIds, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(10000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "edit-tag"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked items till this item as read on the server or offline sync list.");

                    //Add items to post string
                    string SqlStringItemIds = String.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        SqlStringItemIds += "'" + NewsItemId + "',";

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the sql string.");
                            break;
                        }
                    }

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    SqlStringItemIds = AVFunctions.StringRemoveEnd(SqlStringItemIds, ",");
                    await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + SqlStringItemIds + ") AND item_read_status = ('0')");

                    //Update current items list
                    foreach (Items NewsItem in UpdateList.ToList())
                    {
                        //Mark the item as read or remove it from list
                        if ((bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                        {
                            UpdateList.Remove(NewsItem);
                        }
                        else
                        {
                            NewsItem.item_read_status = Visibility.Visible;
                        }

                        //Check if the end item has been reached
                        if (EndItemId == NewsItem.item_id)
                        {
                            Debug.WriteLine("Marked items till this item as read in the list and database.");
                            break;
                        }
                    }

                    if (EnableUI)
                    {
                        await EventProgressEnableUI();
                    }
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                await AVMessageBox.Popup("Failed to mark items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 16
0
        static public async Task <bool> ItemsStarred(bool Preload, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    EventProgressDisableUI("Downloading starred status...", true);
                }
                Debug.WriteLine("Downloading starred status...");

                string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };
                string     DownloadString = await AVDownloader.DownloadStringAsync(15000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "stream/items/ids?output=json&s=user/-/state/com.google/starred&n=" + AppVariables.StarredMaximumLoad));

                if (!string.IsNullOrWhiteSpace(DownloadString))
                {
                    JObject WebJObject = JObject.Parse(DownloadString);
                    if (WebJObject["itemRefs"] != null && WebJObject["itemRefs"].HasValues)
                    {
                        if (!Silent)
                        {
                            EventProgressDisableUI("Updating " + WebJObject["itemRefs"].Count() + " star status...", true);
                        }
                        Debug.WriteLine("Updating " + WebJObject["itemRefs"].Count() + " star status...");

                        //Check and set the received star item ids
                        List <TableItems> TableEditItems = await vSQLConnection.Table <TableItems>().ToListAsync();

                        string        DownloadItemIds = string.Empty;
                        List <string> StarItemsID     = new List <string>();
                        foreach (JToken JTokenRoot in WebJObject["itemRefs"])
                        {
                            string FoundItemId = JTokenRoot["id"].ToString().Replace(" ", string.Empty).Replace("tag:google.com,2005:reader/item/", string.Empty);
                            StarItemsID.Add(FoundItemId);

                            //Check if star item exists
                            if (!TableEditItems.Any(x => x.item_id == FoundItemId))
                            {
                                DownloadItemIds += "&i=" + FoundItemId;
                            }
                        }

                        //Update the star status in database
                        string StarUpdateString = string.Empty;
                        foreach (string StarItem in StarItemsID)
                        {
                            StarUpdateString += "'" + StarItem + "',";
                        }
                        StarUpdateString = AVFunctions.StringRemoveEnd(StarUpdateString, ",");
                        if (StarItemsID.Any())
                        {
                            int UpdatedItems = await vSQLConnection.ExecuteAsync("UPDATE TableItems SET item_star_status = ('1'), item_read_status = ('1') WHERE item_id IN (" + StarUpdateString + ") AND item_star_status = ('0')");

                            Debug.WriteLine("Updated star items: " + UpdatedItems);
                        }

                        //Update the unstar status in database
                        List <string> UnstarItemsID      = TableEditItems.Where(x => x.item_star_status == true).Select(x => x.item_id).Except(StarItemsID).ToList();
                        string        UnstarUpdateString = string.Empty;
                        foreach (string UnstarItem in UnstarItemsID)
                        {
                            UnstarUpdateString += "'" + UnstarItem + "',";
                        }
                        UnstarUpdateString = AVFunctions.StringRemoveEnd(UnstarUpdateString, ",");
                        if (UnstarItemsID.Any())
                        {
                            int UpdatedItems = await vSQLConnection.ExecuteAsync("UPDATE TableItems SET item_star_status = ('0') WHERE item_id IN (" + UnstarUpdateString + ") AND item_star_status = ('1')");

                            Debug.WriteLine("Updated unstar items: " + UpdatedItems);
                        }

                        //Download all missing starred items
                        if (!string.IsNullOrWhiteSpace(DownloadItemIds))
                        {
                            if (!Silent)
                            {
                                EventProgressDisableUI("Downloading starred items...", true);
                            }
                            Debug.WriteLine("Downloading starred items...");

                            bool UpdatedItems = await MultiItems(DownloadItemIds, true, true, Silent, EnableUI);

                            if (!UpdatedItems)
                            {
                                EventProgressEnableUI();
                                return(false);
                            }
                        }
                    }

                    if (EnableUI)
                    {
                        EventProgressEnableUI();
                    }
                    return(true);
                }
                else
                {
                    EventProgressEnableUI();
                    return(false);
                }
            }
            catch
            {
                EventProgressEnableUI();
                return(false);
            }
        }
Esempio n. 17
0
        private static async Task <bool> MarkReadSingle(ObservableCollection <Items> UpdateList, Items ListItem, string ActionType, bool Silent)
        {
            try
            {
                bool   MarkStatus = false;
                string ItemId     = ListItem.item_id;

                //Check if internet is available
                if (Connectivity.NetworkAccess != NetworkAccess.Internet || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        EventProgressDisableUI("Off marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Off marking item as " + ActionType.ToLower() + "...");

                    await AddOfflineSync(ItemId, ActionType);

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        EventProgressDisableUI("Marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Marking item as " + ActionType.ToLower() + "...");

                    string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };

                    StringContent PostContent;
                    if (ActionType == "Read")
                    {
                        PostContent = new StringContent("i=" + ItemId + "&a=user/-/state/com.google/read", Encoding.UTF8, "application/x-www-form-urlencoded");
                    }
                    else
                    {
                        PostContent = new StringContent("i=" + ItemId + "&r=user/-/state/com.google/read", Encoding.UTF8, "application/x-www-form-urlencoded");
                    }
                    Uri PostUri = new Uri(ApiConnectionUrl + "edit-tag");

                    string PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, PostUri, PostContent);

                    if (PostHttp != null && (PostHttp == "OK" || PostHttp.Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    //Get the current page name
                    string currentPage = App.Current.MainPage.ToString();

                    //Mark item in database and list
                    TableItems TableEditItems = await vSQLConnection.Table <TableItems>().Where(x => x.item_id == ItemId).FirstOrDefaultAsync();

                    if (TableEditItems != null)
                    {
                        if (ActionType == "Read")
                        {
                            TableEditItems.item_read_status = true;
                            ListItem.item_read_status       = true;
                            ListItem.item_read_icon         = ImageSource.FromResource("NewsScroll.Assets.iconRead-Dark.png");
                        }
                        else
                        {
                            TableEditItems.item_read_status = false;
                            ListItem.item_read_status       = false;
                            ListItem.item_read_icon         = null;
                        }
                    }

                    //Update the items in database
                    await vSQLConnection.UpdateAsync(TableEditItems);
                }
                else
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Ok");

                    await MessagePopup.Popup("Failed to mark item " + ActionType.ToLower(), "Please check your internet connection and try again.", messageAnswers);

                    EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                Debug.WriteLine("Failed to un/read item.");
                return(false);
            }
        }
Esempio n. 18
0
        //Mark all items as read
        public static async Task <bool> MarkReadAll(ObservableCollection <Items> UpdateList, bool Confirm)
        {
            try
            {
                //Check if user is logged in
                if (!CheckLogin())
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Ok");

                    await MessagePopup.Popup("Not logged in", "Marking all items read can only be done when you are logged in.", messageAnswers);

                    return(false);
                }

                if (Confirm)
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Mark all items read");
                    messageAnswers.Add("Cancel");

                    string messageResult = await MessagePopup.Popup("Mark all items read", "Do you want to mark all items for every feed as read?", messageAnswers);

                    if (messageResult == "Cancel")
                    {
                        return(false);
                    }
                }

                bool MarkStatus = false;

                //Check if internet is available
                if (Connectivity.NetworkAccess != NetworkAccess.Internet || ApiMessageError.StartsWith("(Off)"))
                {
                    EventProgressDisableUI("Off marking all items as read...", true);
                    Debug.WriteLine("Off marking all items as read...");

                    List <string> UnreadItemList = (await vSQLConnection.Table <TableItems>().Where(x => !x.item_read_status).ToListAsync()).Select(x => x.item_id).ToList();
                    await AddOfflineSync(UnreadItemList, "Read");

                    MarkStatus = true;
                }
                else
                {
                    EventProgressDisableUI("Marking all items as read...", true);
                    Debug.WriteLine("Marking all items as read...");

                    //Date time variables
                    long UnixTimeTicks = 0;
                    if (AppSettingLoad("LastItemsUpdate").ToString() != "Never")
                    {
                        UnixTimeTicks = (Convert.ToDateTime(AppSettingLoad("LastItemsUpdate"), AppVariables.CultureInfoEnglish).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10; //Nanoseconds
                    }

                    //Mark all items as read on api server
                    string[][]    RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };
                    StringContent PostContent   = new StringContent("s=user/-/state/com.google/reading-list&ts=" + UnixTimeTicks, Encoding.UTF8, "application/x-www-form-urlencoded");
                    Uri           PostUri       = new Uri(ApiConnectionUrl + "mark-all-as-read");

                    string PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, PostUri, PostContent);

                    if (PostHttp != null && (PostHttp == "OK" || PostHttp.Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked all items as read on the server or offline sync list.");

                    //Update items in database
                    await vSQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_read_status = ('0')");

                    //Update current items list
                    List <Items> ListItems = UpdateList.Where(x => x.item_read_status == false).ToList();
                    foreach (Items NewsItem in ListItems)
                    {
                        //Mark the item as read
                        NewsItem.item_read_status = true;
                        NewsItem.item_read_icon   = ImageSource.FromResource("NewsScroll.Assets.iconRead-Dark.png");
                    }

                    EventProgressEnableUI();
                }
                else
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Ok");

                    await MessagePopup.Popup("Failed to mark all items read", "Please check your internet connection and try again.", messageAnswers);

                    EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                List <string> messageAnswers = new List <string>();
                messageAnswers.Add("Ok");

                await MessagePopup.Popup("Failed to mark all items read", "Please check your internet connection and try again.", messageAnswers);

                EventProgressEnableUI();
                return(false);
            }
        }
Esempio n. 19
0
        private static async Task <bool> MarkReadSingle(ObservableCollection <Items> UpdateList, Items ListItem, string ActionType, bool Silent)
        {
            try
            {
                bool   MarkStatus = false;
                string ItemId     = ListItem.item_id;

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Off marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Off marking item as " + ActionType.ToLower() + "...");

                    await AddOfflineSync(ItemId, ActionType);

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Marking item as " + ActionType.ToLower() + "...", true);
                    }
                    Debug.WriteLine("Marking item as " + ActionType.ToLower() + "...");

                    string[][] RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };

                    HttpStringContent PostContent;
                    if (ActionType == "Read")
                    {
                        PostContent = new HttpStringContent("i=" + ItemId + "&a=user/-/state/com.google/read", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                    }
                    else
                    {
                        PostContent = new HttpStringContent("i=" + ItemId + "&r=user/-/state/com.google/read", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "edit-tag"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Mark item in database and list
                    TableItems TableEditItems = await SQLConnection.Table <TableItems>().Where(x => x.item_id == ItemId).FirstOrDefaultAsync();

                    if (TableEditItems != null)
                    {
                        if (ActionType == "Read")
                        {
                            TableEditItems.item_read_status = true;
                            ListItem.item_read_status       = Visibility.Visible; //Updates itemviewer
                            if (App.vApplicationFrame.SourcePageType.ToString().EndsWith("NewsPage") && NewsPage.vCurrentLoadingFeedFolder.feed_id != "1" && (bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                            {
                                UpdateList.Remove(ListItem);
                            }
                        }
                        else
                        {
                            TableEditItems.item_read_status = false;
                            ListItem.item_read_status       = Visibility.Collapsed; //Updates itemviewer
                            if (App.vApplicationFrame.SourcePageType.ToString().EndsWith("NewsPage") && NewsPage.vCurrentLoadingFeedFolder.feed_id == "1" && (bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                            {
                                UpdateList.Remove(ListItem);
                            }
                        }
                    }

                    //Update the items in database
                    await SQLConnection.UpdateAsync(TableEditItems);
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark item " + ActionType.ToLower(), "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                Debug.WriteLine("Failed to un/read item.");
                return(false);
            }
        }
Esempio n. 20
0
        static public async Task <bool> ItemsRead(ObservableCollection <Items> UpdateList, bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading read status...", true);
                }
                Debug.WriteLine("Downloading read status...");

                //Wait for busy database
                await ApiUpdate.WaitForBusyDatabase();

                //Get all stored items from the database
                List <TableItems> CurrentItems = await SQLConnection.Table <TableItems>().ToListAsync();

                if (CurrentItems.Any())
                {
                    //Get last stored item date minus starred items
                    TableItems LastStoredItem = CurrentItems.Where(x => x.item_star_status == false).OrderByDescending(x => x.item_datetime).LastOrDefault();
                    if (LastStoredItem != null)
                    {
                        //Date time calculations
                        DateTime RemoveItemsRange = LastStoredItem.item_datetime.AddHours(-1);
                        //Debug.WriteLine("Downloading read items till: " + LastStoredItem.item_title + "/" + RemoveItemsRange);
                        Int64 UnixTimeTicks = (RemoveItemsRange.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000000; //Second

                        string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                        Uri        DownloadUri    = new Uri(ApiConnectionUrl + "stream/items/ids?output=json&s=user/-/state/com.google/read&n=" + AppVariables.ItemsMaximumLoad + "&ot=" + UnixTimeTicks);
                        string     DownloadString = await AVDownloader.DownloadStringAsync(10000, "News Scroll", RequestHeader, DownloadUri);

                        if (!String.IsNullOrWhiteSpace(DownloadString))
                        {
                            JObject WebJObject = JObject.Parse(DownloadString);
                            if (WebJObject["itemRefs"] != null && WebJObject["itemRefs"].HasValues)
                            {
                                if (!Silent)
                                {
                                    await EventProgressDisableUI("Updating " + WebJObject["itemRefs"].Count() + " read status...", true);
                                }
                                Debug.WriteLine("Updating " + WebJObject["itemRefs"].Count() + " read status...");

                                //Check and set the received read item ids
                                string        ReadUpdateString = String.Empty;
                                List <String> ReadItemsList    = new List <String>();
                                foreach (JToken JTokenRoot in WebJObject["itemRefs"])
                                {
                                    string FoundItemId = JTokenRoot["id"].ToString().Replace(" ", String.Empty).Replace("tag:google.com,2005:reader/item/", String.Empty);
                                    ReadUpdateString += "'" + FoundItemId + "',";
                                    ReadItemsList.Add(FoundItemId);
                                }

                                //Update the read status in database
                                if (ReadItemsList.Any())
                                {
                                    ReadUpdateString = AVFunctions.StringRemoveEnd(ReadUpdateString, ",");
                                    Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + ReadUpdateString + ") AND item_read_status = ('0')");

                                    Debug.WriteLine("Updated read items: " + UpdatedItems);
                                }

                                //Update the read status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> ReadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Collapsed && ReadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items ReadItem in ReadItemsIDList)
                                        {
                                            ReadItem.item_read_status = Visibility.Visible;
                                        }
                                    }
                                    catch { }
                                });

                                //Update the unread status in database
                                string        UnreadUpdateString = String.Empty;
                                List <String> UnreadItemsList    = (await SQLConnection.Table <TableItems>().ToListAsync()).Where(x => x.item_read_status == true && x.item_datetime > RemoveItemsRange).Select(x => x.item_id).Except(ReadItemsList).ToList();
                                foreach (String UnreadItem in UnreadItemsList)
                                {
                                    UnreadUpdateString += "'" + UnreadItem + "',";
                                }
                                if (UnreadItemsList.Any())
                                {
                                    UnreadUpdateString = AVFunctions.StringRemoveEnd(UnreadUpdateString, ",");
                                    Int32 UpdatedItems = await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('0') WHERE item_id IN (" + UnreadUpdateString + ") AND item_read_status = ('1')");

                                    Debug.WriteLine("Updated unread items: " + UpdatedItems);
                                }

                                //Update the unread status in list
                                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    try
                                    {
                                        List <Items> UnreadItemsIDList = UpdateList.Where(x => x.item_read_status == Visibility.Visible && UnreadItemsList.Any(y => y == x.item_id)).ToList();
                                        foreach (Items UnreadItem in UnreadItemsIDList)
                                        {
                                            UnreadItem.item_read_status = Visibility.Collapsed;
                                        }
                                    }
                                    catch { }
                                });
                            }
                        }
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 21
0
        //Download location
        async Task <bool> DownloadLocation()
        {
            try
            {
                Debug.WriteLine("Downloading Location update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings(null, "Never", null, null, "NoWifiEthernet");
                    return(false);
                }

                //Load and set current GPS location
                if (setWeatherGpsLocation)
                {
                    try
                    {
                        //Get current GPS position from geolocator
                        Geolocator Geolocator = new Geolocator();
                        Geolocator.DesiredAccuracy = PositionAccuracy.Default;
                        Geoposition ResGeoposition = await Geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(setBackgroundDownloadIntervalMin), TimeSpan.FromSeconds(6));

                        DownloadWeatherLocation = ResGeoposition.Coordinate.Point.Position.Latitude.ToString().Replace(",", ".") + "," + ResGeoposition.Coordinate.Point.Position.Longitude.ToString().Replace(",", ".");
                    }
                    catch { DownloadGpsUpdateFailed = true; }
                }
                else
                {
                    if (String.IsNullOrEmpty(setWeatherNonGpsLocation))
                    {
                        DownloadGpsUpdateFailed = true;
                    }
                    else
                    {
                        DownloadWeatherLocation = setWeatherNonGpsLocation;
                    }
                }

                //Load and set manual location
                if (DownloadGpsUpdateFailed)
                {
                    string PreviousLocation = BgStatusWeatherCurrentLocationFull.Replace("!", "");
                    if (PreviousLocation != "N/A" && !String.IsNullOrEmpty(PreviousLocation))
                    {
                        DownloadWeatherLocation = PreviousLocation;
                    }
                    else
                    {
                        Debug.WriteLine("Failed no previous location has been set.");
                        BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsPrevUpdateFailed");
                        return(false);
                    }
                }

                //Download and save the weather location
                string LocationResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/locations/search/" + DownloadWeatherLocation + DownloadWeatherUnits));

                //Check if there is location data available
                JObject LocationJObject = JObject.Parse(LocationResult);
                if (LocationJObject["responses"][0]["locations"] == null || !LocationJObject["responses"][0]["locations"].Any())
                {
                    Debug.WriteLine("Failed no overall info for location found.");
                    BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsNoLocationOverall");
                    return(false);
                }
                else
                {
                    JToken HttpJTokenGeo = LocationJObject["responses"][0]["locations"][0];

                    //Set current location coords
                    if (HttpJTokenGeo["coordinates"]["lat"] != null && HttpJTokenGeo["coordinates"]["lon"] != null)
                    {
                        DownloadWeatherLocation = HttpJTokenGeo["coordinates"]["lat"].ToString().Replace(",", ".") + "," + HttpJTokenGeo["coordinates"]["lon"].ToString().Replace(",", ".");
                    }
                    else
                    {
                        if (!setWeatherGpsLocation || DownloadGpsUpdateFailed)
                        {
                            Debug.WriteLine("Failed no gps coords for location found.");
                            BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsNoLocationCoords");
                            return(false);
                        }
                    }

                    //Set weather current location
                    if (HttpJTokenGeo["displayName"] != null)
                    {
                        string LocationName = HttpJTokenGeo["displayName"].ToString();
                        if (!String.IsNullOrEmpty(LocationName))
                        {
                            BgStatusWeatherCurrentLocationFull = LocationName;
                            vApplicationSettings["BgStatusWeatherCurrentLocationFull"] = BgStatusWeatherCurrentLocationFull;

                            if (LocationName.Contains(","))
                            {
                                LocationName = LocationName.Split(',')[0];
                            }
                            BgStatusWeatherCurrentLocation = LocationName;
                            vApplicationSettings["BgStatusWeatherCurrentLocation"] = BgStatusWeatherCurrentLocation;
                        }
                        else
                        {
                            Debug.WriteLine("Failed empty location name found.");
                            BackgroundStatusUpdateSettings(null, "Failed", null, null, "NoLocationNameEmpty");
                            return(false);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Failed no location name found.");
                        BackgroundStatusUpdateSettings(null, "Failed", null, null, "NoLocationNameFound");
                        return(false);
                    }
                }

                //Save Location status
                BgStatusDownloadLocation = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadLocation"] = BgStatusDownloadLocation;
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the location info.");
                BackgroundStatusUpdateSettings(null, "Failed", null, null, "CatchDownloadLocation" + ex.Message);
                return(false);
            }
        }
Esempio n. 22
0
        //Download console information
        public async Task <DownloadInfoConsole> DownloadInfoConsole(string nameConsole, int imageWidth)
        {
            try
            {
                //Filter the name
                string nameConsoleSave = FilterNameRom(nameConsole, true, false, false, 0);

                //Show the text input popup
                string nameConsoleDownload = await Popup_ShowHide_TextInput("Console search", nameConsoleSave, "Search information for the console", true);

                if (string.IsNullOrWhiteSpace(nameConsoleDownload))
                {
                    Debug.WriteLine("No search term entered.");
                    return(null);
                }
                nameConsoleDownload = FilterNameRom(nameConsoleDownload, false, true, false, 0);

                //Search for consoles
                IEnumerable <ApiIGDBPlatforms> iGDBPlatforms = vApiIGDBPlatforms.Where(x => FilterNameRom(x.name, false, true, false, 0).Contains(nameConsoleDownload) || (x.alternative_name != null && FilterNameRom(x.alternative_name, false, true, false, 0).Contains(nameConsoleDownload)));
                if (iGDBPlatforms == null || !iGDBPlatforms.Any())
                {
                    Debug.WriteLine("No consoles found");
                    await Notification_Send_Status("Close", "No consoles found");

                    return(null);
                }

                //Ask user which console to download
                List <DataBindString> Answers     = new List <DataBindString>();
                BitmapImage           imageAnswer = FileToBitmapImage(new string[] { "Assets/Default/Icons/Emulator.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                foreach (ApiIGDBPlatforms infoPlatforms in iGDBPlatforms)
                {
                    DataBindString answerDownload = new DataBindString();
                    answerDownload.ImageBitmap = imageAnswer;
                    answerDownload.Name        = infoPlatforms.name;
                    answerDownload.NameSub     = infoPlatforms.alternative_name;
                    answerDownload.Data1       = infoPlatforms;
                    Answers.Add(answerDownload);
                }

                //Get selected result
                DataBindString messageResult = await Popup_Show_MessageBox("Select a found console (" + Answers.Count() + ")", "* Information will be saved in the \"Assets\\User\\Games\\Downloaded\" folder as:\n" + nameConsoleSave, "Download image and description for the console:", Answers);

                if (messageResult == null)
                {
                    Debug.WriteLine("No console selected");
                    return(null);
                }

                //Create downloaded directory
                AVFiles.Directory_Create("Assets/User/Games/Downloaded", false);

                //Convert result back to json
                ApiIGDBPlatforms selectedConsole = (ApiIGDBPlatforms)messageResult.Data1;

                await Notification_Send_Status("Download", "Downloading information");

                Debug.WriteLine("Downloading information for: " + nameConsole);

                //Get the platform versions id
                string firstPlatformId = selectedConsole.versions.FirstOrDefault().ToString();
                ApiIGDBPlatformVersions[] iGDBPlatformVersions = await ApiIGDBDownloadPlatformVersions(firstPlatformId);

                if (iGDBPlatformVersions == null || !iGDBPlatformVersions.Any())
                {
                    Debug.WriteLine("No information found");
                    await Notification_Send_Status("Close", "No information found");

                    return(null);
                }

                ApiIGDBPlatformVersions targetPlatformVersions = iGDBPlatformVersions.FirstOrDefault();

                await Notification_Send_Status("Download", "Downloading image");

                Debug.WriteLine("Downloading image for: " + nameConsole);

                //Get the image url
                BitmapImage downloadedBitmapImage = null;
                string      downloadImageId       = targetPlatformVersions.platform_logo.ToString();
                if (downloadImageId != "0")
                {
                    ApiIGDBImage[] iGDBImages = await ApiIGDB_DownloadImage(downloadImageId, "platform_logos");

                    if (iGDBImages == null || !iGDBImages.Any())
                    {
                        Debug.WriteLine("No images found");
                        await Notification_Send_Status("Close", "No images found");

                        return(null);
                    }

                    //Download and save image
                    ApiIGDBImage infoImages = iGDBImages.FirstOrDefault();
                    Uri          imageUri   = new Uri("https://images.igdb.com/igdb/image/upload/t_720p/" + infoImages.image_id + ".png");
                    byte[]       imageBytes = await AVDownloader.DownloadByteAsync(5000, "CtrlUI", null, imageUri);

                    if (imageBytes != null && imageBytes.Length > 256)
                    {
                        try
                        {
                            //Convert bytes to a BitmapImage
                            downloadedBitmapImage = BytesToBitmapImage(imageBytes, imageWidth);

                            //Save bytes to image file
                            File.WriteAllBytes("Assets/User/Games/Downloaded/" + nameConsoleSave + ".png", imageBytes);
                            Debug.WriteLine("Saved image: " + imageBytes.Length + "bytes/" + imageUri);
                        }
                        catch { }
                    }
                }

                //Json settings
                JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
                jsonSettings.NullValueHandling = NullValueHandling.Ignore;

                //Json serialize
                string serializedObject = JsonConvert.SerializeObject(targetPlatformVersions, jsonSettings);

                //Save json information
                File.WriteAllText("Assets/User/Games/Downloaded/" + nameConsoleSave + ".json", serializedObject);

                await Notification_Send_Status("Download", "Downloaded information");

                Debug.WriteLine("Downloaded and saved information for: " + nameConsole);

                //Return the information
                DownloadInfoConsole downloadInfo = new DownloadInfoConsole();
                downloadInfo.ImageBitmap = downloadedBitmapImage;
                downloadInfo.Details     = targetPlatformVersions;
                return(downloadInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading console information: " + ex.Message);
                await Notification_Send_Status("Close", "Failed downloading");

                return(null);
            }
        }
Esempio n. 23
0
        //Download game information
        public async Task <DownloadInfoGame> DownloadInfoGame(string nameRom, int imageWidth, bool saveOriginalName)
        {
            try
            {
                //Filter the game name
                string nameRomSaveOriginal = FilterNameFile(nameRom);
                string nameRomSaveFilter   = FilterNameRom(nameRom, true, false, true, 0);

                //Show the text input popup
                string nameRomDownload = await Popup_ShowHide_TextInput("Game search", nameRomSaveFilter, "Search information for the game", true);

                if (string.IsNullOrWhiteSpace(nameRomDownload))
                {
                    Debug.WriteLine("No search term entered.");
                    return(null);
                }
                nameRomDownload = nameRomDownload.ToLower();

                await Notification_Send_Status("Download", "Downloading information");

                Debug.WriteLine("Downloading information for: " + nameRom);

                //Download available games
                IEnumerable <ApiIGDBGames> iGDBGames = await ApiIGDB_DownloadGames(nameRomDownload);

                if (iGDBGames == null || !iGDBGames.Any())
                {
                    Debug.WriteLine("No games found");
                    await Notification_Send_Status("Close", "No games found");

                    return(null);
                }

                //Ask user which game to download
                List <DataBindString> Answers     = new List <DataBindString>();
                BitmapImage           imageAnswer = FileToBitmapImage(new string[] { "Assets/Default/Icons/Game.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0);
                foreach (ApiIGDBGames infoGames in iGDBGames)
                {
                    //Check if information is available
                    if (infoGames.cover == 0 && string.IsNullOrWhiteSpace(infoGames.summary))
                    {
                        continue;
                    }

                    //Release date
                    string gameReleaseDate = string.Empty;
                    string gameReleaseYear = string.Empty;
                    ApiIGDB_ReleaseDateToString(infoGames, out gameReleaseDate, out gameReleaseYear);

                    //Game platforms
                    string gamePlatforms = string.Empty;
                    if (infoGames.platforms != null)
                    {
                        foreach (int platformId in infoGames.platforms)
                        {
                            ApiIGDBPlatforms apiIGDBPlatforms = vApiIGDBPlatforms.Where(x => x.id == platformId).FirstOrDefault();
                            gamePlatforms = AVFunctions.StringAdd(gamePlatforms, apiIGDBPlatforms.name, ",");
                        }
                    }

                    DataBindString answerDownload = new DataBindString();
                    answerDownload.ImageBitmap = imageAnswer;
                    answerDownload.Name        = infoGames.name;
                    answerDownload.NameSub     = gamePlatforms;
                    answerDownload.NameDetail  = gameReleaseYear;
                    answerDownload.Data1       = infoGames;
                    Answers.Add(answerDownload);
                }

                //Get selected result
                DataBindString messageResult = await Popup_Show_MessageBox("Select a found game (" + Answers.Count() + ")", "* Information will be saved in the \"Assets\\User\\Games\\Downloaded\" folder as:\n" + nameRomSaveFilter, "Download image and description for the game:", Answers);

                if (messageResult == null)
                {
                    Debug.WriteLine("No game selected");
                    return(null);
                }

                //Create downloaded directory
                AVFiles.Directory_Create("Assets/User/Games/Downloaded", false);

                //Convert result back to json
                ApiIGDBGames selectedGame = (ApiIGDBGames)messageResult.Data1;

                await Notification_Send_Status("Download", "Downloading image");

                Debug.WriteLine("Downloading image for: " + nameRom);

                //Get the image url
                BitmapImage downloadedBitmapImage = null;
                string      downloadImageId       = selectedGame.cover.ToString();
                if (downloadImageId != "0")
                {
                    ApiIGDBImage[] iGDBImages = await ApiIGDB_DownloadImage(downloadImageId, "covers");

                    if (iGDBImages == null || !iGDBImages.Any())
                    {
                        Debug.WriteLine("No images found");
                        await Notification_Send_Status("Close", "No images found");

                        return(null);
                    }

                    //Download and save image
                    ApiIGDBImage infoImages = iGDBImages.FirstOrDefault();
                    Uri          imageUri   = new Uri("https://images.igdb.com/igdb/image/upload/t_720p/" + infoImages.image_id + ".png");
                    byte[]       imageBytes = await AVDownloader.DownloadByteAsync(5000, "CtrlUI", null, imageUri);

                    if (imageBytes != null && imageBytes.Length > 256)
                    {
                        try
                        {
                            //Convert bytes to a BitmapImage
                            downloadedBitmapImage = BytesToBitmapImage(imageBytes, imageWidth);

                            //Save bytes to image file
                            if (saveOriginalName)
                            {
                                File.WriteAllBytes("Assets/User/Games/Downloaded/" + nameRomSaveOriginal + ".png", imageBytes);
                            }
                            else
                            {
                                File.WriteAllBytes("Assets/User/Games/Downloaded/" + nameRomSaveFilter + ".png", imageBytes);
                            }

                            Debug.WriteLine("Saved image: " + imageBytes.Length + "bytes/" + imageUri);
                        }
                        catch { }
                    }
                }

                //Json settings
                JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
                jsonSettings.NullValueHandling = NullValueHandling.Ignore;

                //Json serialize
                string serializedObject = JsonConvert.SerializeObject(selectedGame, jsonSettings);

                //Save json information
                if (saveOriginalName)
                {
                    File.WriteAllText("Assets/User/Games/Downloaded/" + nameRomSaveOriginal + ".json", serializedObject);
                }
                else
                {
                    File.WriteAllText("Assets/User/Games/Downloaded/" + nameRomSaveFilter + ".json", serializedObject);
                }

                await Notification_Send_Status("Download", "Downloaded information");

                Debug.WriteLine("Downloaded and saved information for: " + nameRom);

                //Return the information
                DownloadInfoGame downloadInfo = new DownloadInfoGame();
                downloadInfo.ImageBitmap = downloadedBitmapImage;
                downloadInfo.Details     = selectedGame;
                return(downloadInfo);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed downloading game information: " + ex.Message);
                await Notification_Send_Status("Close", "Failed downloading");

                return(null);
            }
        }
Esempio n. 24
0
        //Download Bing wallpaper
        async Task DownloadBingWallpaper()
        {
            try
            {
                Debug.WriteLine("Downloading Bing update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings(null, null, "Never", null, "NoWifiEthernet"); return;
                }

                //Load and set Download Information
                string DownloadBingRegion = "en-US";
                switch (setDownloadBingRegion)
                {
                case 0: { DownloadBingRegion = vCultureInfoReg.Name; break; }

                case 2: { DownloadBingRegion = "en-GB"; break; }

                case 3: { DownloadBingRegion = "en-AU"; break; }

                case 4: { DownloadBingRegion = "de-DE"; break; }

                case 5: { DownloadBingRegion = "en-CA"; break; }

                case 6: { DownloadBingRegion = "ja-JP"; break; }

                case 7: { DownloadBingRegion = "zh-CN"; break; }

                case 8: { DownloadBingRegion = "fr-FR"; break; }

                case 9: { DownloadBingRegion = "pt-BR"; break; }

                case 10: { DownloadBingRegion = "nz-NZ"; break; }
                }
                string DownloadBingResolution = "1920x1080";
                switch (setDownloadBingResolution)
                {
                case 1: { DownloadBingResolution = "1280x720"; break; }

                case 2: { DownloadBingResolution = "1080x1920"; break; }

                case 3: { DownloadBingResolution = "720x1280"; break; }

                case 4: { DownloadBingResolution = "1024x768"; break; }
                }

                //Download and read Bing Wallpaper XML
                XDocument XDocumentBing = XDocument.Parse(await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://www.bing.com/HPImageArchive.aspx?format=xml&n=1&mkt=" + DownloadBingRegion)));

                //Read and check current Bing wallpaper
                XElement XElement        = XDocumentBing.Descendants("image").First();
                string   BingUrlName     = XElement.Element("urlBase").Value + "_" + DownloadBingResolution + ".jpg";
                string   BingDescription = XElement.Element("copyright").Value;
                if (BgStatusBingDescription != BingDescription)
                {
                    //Download and Save Bing Wallpaper image
                    IBuffer BingWallpaperFile = await AVDownloader.DownloadBufferAsync(5000, "TimeMe", new Uri("https://www.bing.com" + BingUrlName));

                    if (BingWallpaperFile != null)
                    {
                        //Save the Bing wallpaper image
                        StorageFile BingSaveFile = await AVFile.SaveBuffer("TimeMeTilePhoto.png" + new String(' ', new Random().Next(1, 50)), BingWallpaperFile);

                        //Set background photo as device wallpaper
                        try
                        {
                            if (setDeviceWallpaper)
                            {
                                await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(BingSaveFile);
                            }
                        }
                        catch { Debug.WriteLine("Failed to update Device wallpaper."); }

                        //Set background photo as lockscreen wallpaper
                        try
                        {
                            if (setLockWallpaper)
                            {
                                if (setDevStatusMobile)
                                {
                                    await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Tiles/TimeMeTileColor.png")));
                                }
                                await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(BingSaveFile);
                            }
                        }
                        catch { Debug.WriteLine("Failed to update Lock screen wallpaper."); }

                        //Save Bing photo name
                        BgStatusPhotoName = BingUrlName;
                        vApplicationSettings["BgStatusPhotoName"] = BgStatusPhotoName;

                        //Save Bing description status
                        BgStatusBingDescription = BingDescription;
                        vApplicationSettings["BgStatusBingDescription"] = BgStatusBingDescription;

                        //Notification - Bing description
                        ShowNotiBingDescription();

                        //Force live tile update
                        TileLive_ForceUpdate = true;
                    }
                    else
                    {
                        Debug.WriteLine("Failed downloading the Bing wallpaper.");
                        BackgroundStatusUpdateSettings(null, null, "Never", null, "FailedDownloadBingWallpaper");
                        return;
                    }
                }

                //Save Bing update status
                BgStatusDownloadBing = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadBing"] = BgStatusDownloadBing;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the Bing wallpaper.");
                BackgroundStatusUpdateSettings(null, null, "Never", null, "CatchDownloadBingWallpaper" + ex.Message);
            }
        }
Esempio n. 25
0
        //Save the image
        private async void button_iconSave_Tap(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(vBitmapLink))
                {
                    //Check internet connection
                    if (!AppVariables.InternetAccess)
                    {
                        await new MessagePopup().OpenPopup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false);
                        System.Diagnostics.Debug.WriteLine("Failed to download the image, no internet access.");
                        return;
                    }

                    //Get the file name
                    string FileName = "Unknown";
                    try
                    {
                        FileName = Path.GetFileNameWithoutExtension(vBitmapLink);
                    }
                    catch { }
                    if (string.IsNullOrWhiteSpace(FileName))
                    {
                        FileName = "Unknown";
                    }

                    //Get the file extension
                    string FileExtensionFile    = ".jpg";
                    string FileExtensionDisplay = "JPG";
                    try
                    {
                        FileExtensionFile = Path.GetExtension(vBitmapLink).ToLower();
                    }
                    catch { }
                    if (string.IsNullOrWhiteSpace(FileExtensionFile))
                    {
                        FileExtensionFile = ".jpg";
                    }
                    FileExtensionDisplay = FileExtensionFile.ToUpper().Replace(".", string.Empty);

                    FileSavePicker saveFilePicker = new FileSavePicker();
                    saveFilePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                    saveFilePicker.FileTypeChoices.Add(FileExtensionDisplay, new List <string>()
                    {
                        FileExtensionFile
                    });
                    saveFilePicker.SuggestedFileName = FileName;

                    StorageFile saveStorageFile = await saveFilePicker.PickSaveFileAsync();

                    if (saveStorageFile != null)
                    {
                        System.Diagnostics.Debug.WriteLine("Downloading and saving online image: " + vBitmapLink);
                        await EventProgressDisableUI("Downloading and saving image...", false);

                        Uri    imageUri    = new Uri(vBitmapLink);
                        byte[] ImageBuffer = await AVDownloader.DownloadByteAsync(10000, "News Scroll", null, imageUri);

                        if (ImageBuffer != null)
                        {
                            await FileIO.WriteBytesAsync(saveStorageFile, ImageBuffer);
                        }
                        else
                        {
                            await new MessagePopup().OpenPopup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false);
                            System.Diagnostics.Debug.WriteLine("Failed to download the image, no internet access.");
                        }

                        await EventProgressEnableUI();
                    }
                }
            }
            catch (Exception ex)
            {
                await new MessagePopup().OpenPopup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false);
                System.Diagnostics.Debug.WriteLine("Failed to save the image: " + ex.Message);
                await EventProgressEnableUI();
            }
        }
Esempio n. 26
0
        //Mark all items as read
        public static async Task <bool> MarkReadAll(ObservableCollection <Items> UpdateList, bool Confirm)
        {
            try
            {
                //Check if user is logged in
                if (!CheckLogin())
                {
                    await AVMessageBox.Popup("Not logged in", "Marking all items read can only be done when you are logged in.", "Ok", "", "", "", "", false);

                    return(false);
                }

                if (Confirm)
                {
                    Int32 MsgBoxResult = await AVMessageBox.Popup("Mark all items read", "Do you want to mark all items for every feed as read?", "Mark all items read", "", "", "", "", true);

                    if (MsgBoxResult == 0)
                    {
                        return(false);
                    }
                }

                bool MarkStatus = false;

                //Check if internet is available
                if (!NetworkInterface.GetIsNetworkAvailable() || ApiMessageError.StartsWith("(Off)"))
                {
                    await EventProgressDisableUI("Off marking all items as read...", true);

                    Debug.WriteLine("Off marking all items as read...");

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    List <String> UnreadItemList = (await SQLConnection.Table <TableItems>().Where(x => !x.item_read_status).ToListAsync()).Select(x => x.item_id).ToList();
                    await AddOfflineSync(UnreadItemList, "Read");

                    MarkStatus = true;
                }
                else
                {
                    await EventProgressDisableUI("Marking all items as read...", true);

                    Debug.WriteLine("Marking all items as read...");

                    //Date time variables
                    Int64 UnixTimeTicks = 0;
                    if (AppVariables.ApplicationSettings["LastItemsUpdate"].ToString() != "Never")
                    {
                        UnixTimeTicks = (Convert.ToDateTime(AppVariables.ApplicationSettings["LastItemsUpdate"], AppVariables.CultureInfoEnglish).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10; //Nanoseconds
                    }

                    //Mark all items as read on api server
                    string[][]        RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                    HttpStringContent PostContent   = new HttpStringContent("s=user/-/state/com.google/reading-list&ts=" + UnixTimeTicks, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

                    HttpResponseMessage PostHttp = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "mark-all-as-read"), PostContent);

                    if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked all items as read on the server or offline sync list.");

                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Update items in database
                    await SQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_read_status = ('0')");

                    //Update current items list
                    List <Items> ListItems = UpdateList.Where(x => x.item_read_status == Visibility.Collapsed).ToList();
                    foreach (Items NewsItem in ListItems)
                    {
                        if ((bool)AppVariables.ApplicationSettings["HideReadMarkedItem"])
                        {
                            UpdateList.Remove(NewsItem);
                        }
                        else
                        {
                            NewsItem.item_read_status = Visibility.Visible;
                        }
                    }

                    await EventProgressEnableUI();
                }
                else
                {
                    await AVMessageBox.Popup("Failed to mark all items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                    await EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                await AVMessageBox.Popup("Failed to mark all items read", "Please check your internet connection and try again.", "Ok", "", "", "", "", false);
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 27
0
        static public async Task <bool> Feeds(bool Silent, bool EnableUI)
        {
            try
            {
                if (!Silent)
                {
                    await EventProgressDisableUI("Downloading latest feeds...", true);
                }
                System.Diagnostics.Debug.WriteLine("Downloading latest feeds...");

                string[][] RequestHeader  = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                string     DownloadString = await AVDownloader.DownloadStringAsync(10000, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "subscription/list?output=json"));

                JObject WebJObject = JObject.Parse(DownloadString);
                if (WebJObject["subscriptions"] != null && WebJObject["subscriptions"].HasValues)
                {
                    if (!Silent)
                    {
                        await EventProgressDisableUI("Processing " + WebJObject["subscriptions"].Count() + " feeds...", true);
                    }
                    System.Diagnostics.Debug.WriteLine("Processing " + WebJObject["subscriptions"].Count() + " feeds...");

                    List <string> ApiFeedIdList = new List <string>();
                    IReadOnlyList <IStorageItem> LocalFileList = await ApplicationData.Current.LocalFolder.GetItemsAsync();

                    List <TableFeeds> TableUpdatedFeeds = new List <TableFeeds>();
                    List <TableFeeds> TableCurrentFeeds = await SQLConnection.Table <TableFeeds>().ToListAsync();

                    foreach (JToken JTokenRoot in WebJObject["subscriptions"])
                    {
                        string FeedId    = JTokenRoot["sortid"].ToString();
                        string FeedTitle = JTokenRoot["title"].ToString();

                        string HtmlUrl = WebUtility.HtmlDecode(JTokenRoot["htmlUrl"].ToString());
                        HtmlUrl = WebUtility.UrlDecode(HtmlUrl);

                        Uri FullUrl = new Uri(HtmlUrl);
                        ApiFeedIdList.Add(FeedId);

                        TableFeeds TableResult = TableCurrentFeeds.Where(x => x.feed_id == FeedId).FirstOrDefault();
                        if (TableResult == null)
                        {
                            //System.Diagnostics.Debug.WriteLine("Adding feed: " + FeedTitle);

                            TableFeeds AddFeed = new TableFeeds();
                            AddFeed.feed_id    = FeedId;
                            AddFeed.feed_title = FeedTitle;
                            AddFeed.feed_link  = FullUrl.Scheme + "://" + FullUrl.Host;

                            AddFeed.feed_ignore_status = false;
                            if (JTokenRoot["categories"] != null && JTokenRoot["categories"].HasValues)
                            {
                                AddFeed.feed_folder = JTokenRoot["categories"][0]["label"].ToString();
                            }

                            TableUpdatedFeeds.Add(AddFeed);
                        }
                        else
                        {
                            //System.Diagnostics.Debug.WriteLine("Updating feed: " + FeedTitle);

                            TableResult.feed_title = FeedTitle;
                            TableResult.feed_link  = FullUrl.Scheme + "://" + FullUrl.Host;

                            if (JTokenRoot["categories"] != null && JTokenRoot["categories"].HasValues)
                            {
                                TableResult.feed_folder = JTokenRoot["categories"][0]["label"].ToString();
                            }

                            TableUpdatedFeeds.Add(TableResult);
                        }

                        //Check and download feed logo
                        if (!LocalFileList.Any(x => x.Name == FeedId + ".png"))
                        {
                            try
                            {
                                if (!Silent)
                                {
                                    await EventProgressDisableUI("Downloading " + FeedTitle + " icon...", true);
                                }

                                Uri    IconUrl      = new Uri("https://s2.googleusercontent.com/s2/favicons?domain=" + FullUrl.Host);
                                byte[] HttpFeedIcon = await AVDownloader.DownloadByteAsync(3000, "News Scroll", null, IconUrl);

                                if (HttpFeedIcon != null && HttpFeedIcon.Length > 75)
                                {
                                    await AVFile.SaveBytes(FeedId + ".png", HttpFeedIcon);

                                    System.Diagnostics.Debug.WriteLine("Downloaded transparent logo: " + HttpFeedIcon.Length + "bytes/" + IconUrl);
                                }
                                else
                                {
                                    System.Diagnostics.Debug.WriteLine("No logo found for: " + IconUrl);
                                }
                            }
                            catch { }
                        }
                    }

                    //Update the feeds in database
                    if (TableUpdatedFeeds.Any())
                    {
                        await SQLConnection.InsertAllAsync(TableUpdatedFeeds, "OR REPLACE");
                    }

                    //Delete removed feeds from the database
                    List <string> DeletedFeeds = TableCurrentFeeds.Select(x => x.feed_id).Except(ApiFeedIdList).ToList();
                    System.Diagnostics.Debug.WriteLine("Found deleted feeds: " + DeletedFeeds.Count());
                    foreach (string DeleteFeedId in DeletedFeeds)
                    {
                        await DeleteFeed(DeleteFeedId);
                    }
                }

                if (EnableUI)
                {
                    await EventProgressEnableUI();
                }
                return(true);
            }
            catch
            {
                await EventProgressEnableUI();

                return(false);
            }
        }
Esempio n. 28
0
        //Mark items till as read
        public static async Task <bool> MarkReadTill(ObservableCollection <Items> UpdateList, Items EndItem, bool Confirm, bool Silent, bool EnableUI)
        {
            try
            {
                if (Confirm)
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Mark read till item");
                    messageAnswers.Add("Cancel");

                    string messageResult = await MessagePopup.Popup("Mark items read till item", "Do you want to mark all items for the selected feed till this item as read?", messageAnswers);

                    if (messageResult == "Cancel")
                    {
                        return(false);
                    }
                }

                bool   MarkStatus = false;
                string EndItemId  = EndItem.item_id;

                //Check the selected items
                List <Items> TableEditItems = UpdateList.Where(x => x.item_id == EndItemId || x.item_read_status == false).ToList();

                //Check if internet is available
                if (Connectivity.NetworkAccess != NetworkAccess.Internet || ApiMessageError.StartsWith("(Off)"))
                {
                    if (!Silent)
                    {
                        EventProgressDisableUI("Off marking read till item...", true);
                    }
                    Debug.WriteLine("Off marking read till item...");

                    //Add items to string list
                    List <string> ReadItemIds = new List <string>();
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        ReadItemIds.Add(NewsItemId);

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the string list.");
                            break;
                        }
                    }

                    await AddOfflineSync(ReadItemIds, "Read");

                    MarkStatus = true;
                }
                else
                {
                    if (!Silent)
                    {
                        EventProgressDisableUI("Marking read till item...", true);
                    }
                    Debug.WriteLine("Marking read till item...");

                    //Add items to post string
                    string PostStringItemIds = string.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        PostStringItemIds += "&i=" + NewsItemId;

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the post string.");
                            break;
                        }
                    }

                    string[][]    RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppSettingLoad("ConnectApiAuth").ToString() } };
                    StringContent PostContent   = new StringContent("a=user/-/state/com.google/read" + PostStringItemIds, Encoding.UTF8, "application/x-www-form-urlencoded");
                    Uri           PostUri       = new Uri(ApiConnectionUrl + "edit-tag");

                    string PostHttp = await AVDownloader.SendPostRequestAsync(10000, "News Scroll", RequestHeader, PostUri, PostContent);

                    if (PostHttp != null && (PostHttp == "OK" || PostHttp.Contains("<error>Not found</error>")))
                    {
                        MarkStatus = true;
                    }
                }

                if (MarkStatus)
                {
                    Debug.WriteLine("Marked items till this item as read on the server or offline sync list.");

                    //Add items to post string
                    string SqlStringItemIds = string.Empty;
                    foreach (Items NewsItem in TableEditItems)
                    {
                        string NewsItemId = NewsItem.item_id;
                        SqlStringItemIds += "'" + NewsItemId + "',";

                        //Check if the end item has been reached
                        if (EndItemId == NewsItemId)
                        {
                            Debug.WriteLine("Added all news items to the sql string.");
                            break;
                        }
                    }

                    SqlStringItemIds = AVFunctions.StringRemoveEnd(SqlStringItemIds, ",");
                    await vSQLConnection.ExecuteAsync("UPDATE TableItems SET item_read_status = ('1') WHERE item_id IN (" + SqlStringItemIds + ") AND item_read_status = ('0')");

                    //Update current items list
                    foreach (Items NewsItem in UpdateList.ToList())
                    {
                        //Mark the item as read
                        NewsItem.item_read_status = true;
                        NewsItem.item_read_icon   = ImageSource.FromResource("NewsScroll.Assets.iconRead-Dark.png");

                        //Check if the end item has been reached
                        if (EndItemId == NewsItem.item_id)
                        {
                            Debug.WriteLine("Marked items till this item as read in the list and database.");
                            break;
                        }
                    }

                    if (EnableUI)
                    {
                        EventProgressEnableUI();
                    }
                }
                else
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Ok");

                    await MessagePopup.Popup("Failed to mark items read", "Please check your internet connection and try again.", messageAnswers);

                    EventProgressEnableUI();
                }

                return(MarkStatus);
            }
            catch
            {
                List <string> messageAnswers = new List <string>();
                messageAnswers.Add("Ok");

                await MessagePopup.Popup("Failed to mark items read", "Please check your internet connection and try again.", messageAnswers);

                EventProgressEnableUI();
                return(false);
            }
        }
Esempio n. 29
0
        //Save the image
        private async void button_iconSave_Tap(object sender, RoutedEventArgs e)
        {
            try
            {
                if (vBitmapImage != null && vBitmapImage.PixelHeight > 0)
                {
                    //Get the url path
                    string UrlPath = String.Empty;
                    try { UrlPath = vBitmapImage.UriSource.AbsolutePath; } catch { }
                    if (String.IsNullOrWhiteSpace(UrlPath))
                    {
                        UrlPath = vBitmapImage.UriSource.ToString();
                    }

                    //Get the file name
                    string FileName = "Unknown";
                    try { FileName = Path.GetFileNameWithoutExtension(UrlPath); } catch { }
                    if (String.IsNullOrWhiteSpace(FileName))
                    {
                        FileName = "Unknown";
                    }

                    //Check if network is available
                    bool IsNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();

                    //Get the file extension
                    string FileExtensionFile    = ".jpg";
                    string FileExtensionDisplay = "JPG";
                    if (IsNetworkAvailable)
                    {
                        try { FileExtensionFile = Path.GetExtension(UrlPath).ToLower(); } catch { }
                        if (String.IsNullOrWhiteSpace(FileExtensionFile))
                        {
                            FileExtensionFile = ".jpg";
                        }
                        FileExtensionDisplay = FileExtensionFile.ToUpper().Replace(".", String.Empty);
                    }
                    else
                    {
                        Int32 MessageResult = await AVMessageBox.Popup("Offline saving", "Saving images while in offline mode may save the image in a lower quality and animations will be saved as a static image.", "Save image", "", "", "", "", true);

                        if (MessageResult == 0)
                        {
                            return;
                        }
                    }

                    FileSavePicker FileSavePicker = new FileSavePicker();
                    FileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                    FileSavePicker.FileTypeChoices.Add(FileExtensionDisplay, new List <string>()
                    {
                        FileExtensionFile
                    });
                    FileSavePicker.SuggestedFileName = FileName;

                    StorageFile NewFile = await FileSavePicker.PickSaveFileAsync();

                    if (NewFile != null)
                    {
                        //Download the bitmapimage source uri
                        if (IsNetworkAvailable)
                        {
                            Debug.WriteLine("Saving online image...");

                            IBuffer ImageBuffer = await AVDownloader.DownloadBufferAsync(10000, "News Scroll", vBitmapImage.UriSource);

                            if (ImageBuffer != null)
                            {
                                await FileIO.WriteBufferAsync(NewFile, ImageBuffer);
                            }
                            else
                            {
                                await AVMessageBox.Popup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false);

                                Debug.WriteLine("Failed to download the image.");
                            }
                        }
                        //Capture the image displayed in xaml
                        else
                        {
                            Debug.WriteLine("Saving offline image...");

                            ////Set the image size temporarily to bitmap size
                            //Double PreviousWidth = image_ImageViewer.ActualWidth;
                            //Double PreviousHeight = image_ImageViewer.ActualHeight;
                            //image_ImageViewer.Width = vBitmapImage.PixelWidth;
                            //image_ImageViewer.Height = vBitmapImage.PixelHeight;

                            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                            await renderTargetBitmap.RenderAsync(image_source);

                            IBuffer PixelBuffer = await renderTargetBitmap.GetPixelsAsync();

                            using (IRandomAccessStream fileStream = await NewFile.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                BitmapEncoder bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);

                                bitmapEncoder.SetPixelData(
                                    BitmapPixelFormat.Bgra8,
                                    BitmapAlphaMode.Ignore,
                                    (uint)renderTargetBitmap.PixelWidth,
                                    (uint)renderTargetBitmap.PixelHeight,
                                    DisplayInformation.GetForCurrentView().LogicalDpi,
                                    DisplayInformation.GetForCurrentView().LogicalDpi,
                                    PixelBuffer.ToArray());
                                await bitmapEncoder.FlushAsync();
                            }

                            //Debug.WriteLine("From: " + image_ImageViewer.Width + " setting back: " + PreviousWidth);
                            //image_ImageViewer.Width = PreviousWidth;
                            //image_ImageViewer.Height = PreviousHeight;
                        }
                    }
                }
            }
            catch
            {
                await AVMessageBox.Popup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false);

                Debug.WriteLine("Failed to save the image.");
            }
        }
Esempio n. 30
0
        //Download weather and forecast
        async Task DownloadWeather()
        {
            try
            {
                Debug.WriteLine("Downloading Weather update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWifiEthernet");
                    return;
                }

                //Check if location is available
                if (String.IsNullOrEmpty(DownloadWeatherLocation))
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWeatherLocation");
                    return;
                }

                //Download and save weather summary
                string WeatherSummaryResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/summary/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherSummaryResult))
                {
                    //Update weather summary status
                    UpdateWeatherSummaryStatus(WeatherSummaryResult);

                    //Notification - Current Weather
                    ShowNotiWeatherCurrent();

                    //Save weather summary data
                    await AVFile.SaveText("TimeMeWeatherSummary.js", WeatherSummaryResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather summary found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherSummary");
                    return;
                }

                //Download and save weather forecast
                string WeatherForecastResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/forecast/daily/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherForecastResult))
                {
                    //Save weather forecast data
                    await AVFile.SaveText("TimeMeWeatherForecast.js", WeatherForecastResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather forecast found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherForecast");
                    return;
                }

                //Save Weather status
                BgStatusDownloadWeather = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadWeather"] = BgStatusDownloadWeather;
                BgStatusDownloadWeatherTime = BgStatusDownloadWeather;
                vApplicationSettings["BgStatusDownloadWeatherTime"] = BgStatusDownloadWeather;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the weather info.");
                BackgroundStatusUpdateSettings("Failed", null, null, null, "CatchDownloadWeather" + ex.Message);
            }

            //Update weather summary status
            void UpdateWeatherSummaryStatus(string WeatherSummaryResult)
            {
                try
                {
                    //Check if there is summary data available
                    JObject SummaryJObject = JObject.Parse(WeatherSummaryResult);
                    if (SummaryJObject["responses"][0]["weather"] != null)
                    {
                        //Set Weather Provider Information
                        JToken HttpJTokenProvider = SummaryJObject["responses"][0]["weather"][0]["provider"];
                        if (HttpJTokenProvider["name"] != null)
                        {
                            string Provider = HttpJTokenProvider["name"].ToString();
                            if (!String.IsNullOrEmpty(Provider))
                            {
                                BgStatusWeatherProvider = Provider; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                            else
                            {
                                BgStatusWeatherProvider = "N/A"; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                        }

                        //Set Weather Current Conditions
                        string Icon               = "";
                        string Condition          = "";
                        string Temperature        = "";
                        string WindSpeedDirection = "";
                        JToken UnitsJToken        = SummaryJObject["units"];
                        JToken HttpJTokenCurrent  = SummaryJObject["responses"][0]["weather"][0]["current"];
                        if (HttpJTokenCurrent["icon"] != null)
                        {
                            Icon = HttpJTokenCurrent["icon"].ToString();
                        }
                        if (HttpJTokenCurrent["cap"] != null)
                        {
                            Condition = HttpJTokenCurrent["cap"].ToString();
                        }
                        if (HttpJTokenCurrent["temp"] != null)
                        {
                            Temperature = HttpJTokenCurrent["temp"].ToString() + "°";
                        }
                        if (HttpJTokenCurrent["windSpd"] != null && HttpJTokenCurrent["windDir"] != null)
                        {
                            WindSpeedDirection = HttpJTokenCurrent["windSpd"].ToString() + " " + UnitsJToken["speed"].ToString() + " " + AVFunctions.DegreesToCardinal(Convert.ToDouble((HttpJTokenCurrent["windDir"].ToString())));
                        }

                        //Set Weather Forecast Conditions
                        string RainChance         = "";
                        string TemperatureLow     = "";
                        string TemperatureHigh    = "";
                        JToken HttpJTokenForecast = SummaryJObject["responses"][0]["weather"][0]["forecast"]["days"][0];
                        if (HttpJTokenForecast["precip"] != null)
                        {
                            RainChance = HttpJTokenForecast["precip"].ToString() + "%";
                        }
                        if (HttpJTokenForecast["tempLo"] != null)
                        {
                            TemperatureLow = HttpJTokenForecast["tempLo"].ToString() + "°";
                        }
                        if (HttpJTokenForecast["tempHi"] != null)
                        {
                            TemperatureHigh = HttpJTokenForecast["tempHi"].ToString() + "°";
                        }

                        //Set Weather Icon
                        if (!String.IsNullOrEmpty(Icon))
                        {
                            BgStatusWeatherCurrentIcon = Icon;
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }
                        else
                        {
                            BgStatusWeatherCurrentIcon = "0";
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }

                        //Set Weather Temperature and Condition
                        if (!String.IsNullOrEmpty(Temperature) && !String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrent = AVFunctions.ToTitleCase(Condition) + ", " + Temperature;
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }
                        else
                        {
                            BgStatusWeatherCurrent = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }

                        //Set Weather Temperature
                        if (!String.IsNullOrEmpty(Temperature))
                        {
                            BgStatusWeatherCurrentTemp = Temperature;
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTemp = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }

                        //Set Weather Condition
                        if (!String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrentText = AVFunctions.ToTitleCase(Condition);
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }
                        else
                        {
                            BgStatusWeatherCurrentText = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }

                        //Set Weather Wind Speed and Direction
                        if (!String.IsNullOrEmpty(WindSpeedDirection))
                        {
                            BgStatusWeatherCurrentWindSpeed = WindSpeedDirection;
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }
                        else
                        {
                            BgStatusWeatherCurrentWindSpeed = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }

                        //Set Weather Rain Chance
                        if (!String.IsNullOrEmpty(RainChance))
                        {
                            BgStatusWeatherCurrentRainChance = RainChance;
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }
                        else
                        {
                            BgStatusWeatherCurrentRainChance = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }

                        //Set Weather Temp Low
                        if (!String.IsNullOrEmpty(TemperatureLow))
                        {
                            BgStatusWeatherCurrentTempLow = TemperatureLow;
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempLow = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }

                        //Set Weather Temp High
                        if (!String.IsNullOrEmpty(TemperatureHigh))
                        {
                            BgStatusWeatherCurrentTempHigh = TemperatureHigh;
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempHigh = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                    }
                }
                catch { }
            }
        }