예제 #1
0
        static public async Task <int> update(bool forceRemote = false, bool calendarOnly = false)
        {
            Debug.WriteLine("[Notification] update begin");

            var updater = TileUpdateManager.CreateTileUpdaterForApplication();

            updater.EnableNotificationQueue(true);
            updater.Clear(); //TODO: should always clear?



            var semester = await DataAccess.getSemester(forceRemote);

            int tileCount = 0;

            var notifier = ToastNotificationManager.CreateToastNotifier();


            try {
                if (!calendarOnly && !DataAccess.credentialAbsent())
                {
                    Debug.WriteLine("[Notification] credential exist");

                    //deadlines
                    var unfiltered = await DataAccess.getAllDeadlines(forceRemote);

                    var unsorted = (from a in unfiltered
                                    where !a.hasBeenFinished && !a.shouldBeIgnored()
                                    select a);
                    var deadlines = DataAccess.sortDeadlines(unsorted.ToList());

                    int n = (from a in deadlines where !a.isPast() select a).Count();
                    setBadgeNumber(n);

                    foreach (var deadline in deadlines)
                    {
                        if (!deadline.isPast() &&
                            (tileCount + 1) < 5)
                        {
                            var tile = new TileNotification(getTileXmlForDeadline(deadline, semester));
                            updater.Update(tile);
                            tileCount++;
                        }

                        if (!deadline.hasBeenFinished)
                        {
                            if (!deadline.hasBeenToasted())
                            {
                                deadline.mark_as_toasted();
                                var toast = new ToastNotification(getToastXmlForDeadline(deadline));
                                notifier.Show(toast);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Debug.WriteLine("[Notification] error dealing with deadlines: " + e.Message);
                throw e;
            }

            //calendar
            try {
                if (tileCount < 5)
                {
                    updater.Update(new TileNotification(getTileXmlForCalendar(semester)));
                }
            } catch (Exception e) {
                Debug.WriteLine("[Notification] error dealing with calendar: " + e.Message);
                throw e;
            }


            Debug.WriteLine("[Notification] update finished");
            return(0);
        }
 private void ClearTile_Click(object sender, RoutedEventArgs e)
 {
     TileUpdateManager.CreateTileUpdaterForApplication().Clear();
     OutputTextBlock.Text = "Tile cleared";
 }
예제 #3
0
파일: TileService.cs 프로젝트: chenf99/uwp
        /*public static XmlDocument CreateTiles(PrimaryTile primaryTile)
         * {
         *  XDocument xDoc = new XDocument(
         *      new XElement("tile", new XAttribute("version", 3),
         *          new XElement("visual",
         *              // Small Tile
         *              new XElement("binding", new XAttribute("branding", primaryTile.branding), new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileSmall"),
         *                  new XElement("group",
         *                      new XElement("subgroup",
         *                          new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
         *                          new XElement("text", primaryTile.message, new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true), new XAttribute("hint-maxLines", 3))
         *                      )
         *                  )
         *              ),
         *
         *              // Medium Tile
         *              new XElement("binding", new XAttribute("branding", primaryTile.branding), new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileMedium"),
         *                  new XElement("group",
         *                      new XElement("subgroup",
         *                          new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
         *                          new XElement("text", primaryTile.message, new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true), new XAttribute("hint-maxLines", 3))
         *                      )
         *                  )
         *              ),
         *
         *              // Wide Tile
         *              new XElement("binding", new XAttribute("branding", primaryTile.branding), new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileWide"),
         *                  new XElement("group",
         *                      new XElement("subgroup",
         *                          new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
         *                          new XElement("text", primaryTile.message, new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true), new XAttribute("hint-maxLines", 3)),
         *                          new XElement("text", primaryTile.message2, new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true), new XAttribute("hint-maxLines", 3))
         *                      ),
         *                      new XElement("subgroup", new XAttribute("hint-weight", 15),
         *                          new XElement("image", new XAttribute("placement", "inline"), new XAttribute("src", "Assets/StoreLogo.png"))
         *                      )
         *                  )
         *              )
         *          )
         *      )
         *  );
         *
         *  XmlDocument xmlDoc = new XmlDocument();
         *  xmlDoc.LoadXml(xDoc.ToString());
         *  return xmlDoc;
         * }*/

        public static void UpdateTiles()
        {
            TileUpdateManager.CreateTileUpdaterForApplication().Clear();
            ListItemViewModel viewModel = ListItemViewModel.GetViewModel();
            TileContent       content;

            for (int i = 0; i < viewModel.AllItems.Count && i < 5; ++i)
            {
                content = new TileContent()
                {
                    Visual = new TileVisual()
                    {
                        Branding  = TileBranding.NameAndLogo,
                        TileSmall = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].Title, HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].description, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileMedium = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].Title, HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].description, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileWide = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].Title, HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].description, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileLarge = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].Title, HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = viewModel.AllItems[i].description, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        }
                    }
                };
                TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(content.GetXml()));
            }
            //如果没有item对磁贴进行初始处理
            if (viewModel.AllItems.Count == 0)
            {
                content = new TileContent()
                {
                    Visual = new TileVisual()
                    {
                        Branding  = TileBranding.NameAndLogo,
                        TileSmall = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = "Title", HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = "Detail", HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileMedium = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = "This is the title", HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = "This is the description", HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileWide = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = "This is the title", HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = "This is the description", HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        },

                        TileLarge = new TileBinding()
                        {
                            Content = new TileBindingContentAdaptive()
                            {
                                BackgroundImage = new TileBackgroundImage()
                                {
                                    Source = "Assets/backgroud.jpg"
                                },

                                Children =
                                {
                                    new AdaptiveText()
                                    {
                                        Text = "This is the title", HintWrap = true
                                    },
                                    new AdaptiveText()
                                    {
                                        Text = "This is the description", HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true
                                    }
                                }
                            }
                        }
                    }
                };
                var xmlDocument = content.GetXml();
                TileNotification tileNotification = new TileNotification(xmlDocument);
                TileUpdater      tileUpdater      = TileUpdateManager.CreateTileUpdaterForApplication();
                tileUpdater.Update(tileNotification);
            }
        }
예제 #4
0
        //第一次创建磁贴时调用
        public async static void FirstCreatTie(string title, string content, int id)
        {
            //创建磁贴过程
            string        tileId = id.ToString();
            SecondaryTile tile   = null;
            var           myList = await SecondaryTile.FindAllAsync();

            var tilelist = myList.ToList();

            if (SecondaryTile.Exists(tileId)) //如果存在
            {
                for (int i = 0; i < tilelist.Count; i++)
                {
                    if (tilelist[i].TileId == tileId)
                    {
                        tile = tilelist[i];
                        var notifyPopup = new NotifyPopup("该便签已存在磁贴");
                        notifyPopup.Show();
                        break;
                    }
                }
            }
            else
            {
                tile = new SecondaryTile(tileId)
                {
                    DisplayName = "StickyNotes",
                    Arguments   = "args"
                };
                tile.VisualElements.Square150x150Logo           = new Uri("ms-appx:///Assets/Square150x150Logo.scale-200.png");
                tile.VisualElements.Wide310x150Logo             = new Uri("ms-appx:///Assets/Wide310x150Logo.scale-400.png");
                tile.VisualElements.Square310x310Logo           = new Uri("ms-appx:///Assets/LargeTile.scale-400.png");
                tile.VisualElements.ShowNameOnSquare150x150Logo = true;
                tile.VisualElements.ShowNameOnSquare310x310Logo = true;
                tile.VisualElements.ShowNameOnWide310x150Logo   = true;
                if (!await tile.RequestCreateAsync())
                {
                    return;
                }

                var notifyPopup = new NotifyPopup("已为该便签添加磁贴");
                notifyPopup.Show();
            }

            //数据绑定过程
            if (title.Length >= 20)
            {
                title = title.Substring(0, 30);
            }

            if (content.Length >= 80)
            {
                content = content.Substring(0, 80);
            }

            TileContent myContent        = Tile.GenerateTileContent(title, content);
            var         tileNotification = new TileNotification(myContent.GetXml())
            {
                Tag = tile.TileId,
            };
            var updater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId);

            updater.EnableNotificationQueue(true);
            updater.Update(tileNotification);
            //var currentTime = DateTime.Now.AddSeconds(2); //2秒后更新
            //var tileNotification =
            //    new Windows.UI.Notifications.ScheduledTileNotification(myContent.GetXml(),
            //            new DateTimeOffset(currentTime)) //产生更新并将此更新的ID设为与磁贴一致
            //    {
            //        Tag = tileId
            //    };
            //updater.AddToSchedule(tileNotification);
        }
        // 清除 application tile 的数据
        private void btnClearTile_Click(object sender, RoutedEventArgs e)
        {
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();

            tileUpdater.Clear();
        }
예제 #6
0
        public async Task <bool> SetAsDefaultLocation()
        {
            bool result = false;

            MessageDialog msg = new MessageDialog($"Are you sure to set \"{CurrentWeather.city.location}\" as your default location?", "Set as default location");

            msg.Commands.Add(new UICommand("Yes", delegate
            {
                AppSettingsService.SaveSetting(AppSettingsService.DEFAULT_LOCATION_MODE, 1);
                AppSettingsService.SaveSetting(AppSettingsService.DEFAULT_LOCATION, $"{CurrentWeather.city.coord.lat}|{CurrentWeather.city.coord.lon}");
                AppSettingsService.SaveSetting(AppSettingsService.DEFAULT_LOCATION_FULL_NAME, $"{CurrentWeather.city.location}");

                #region Update live tile
                var liveTile = TileUpdateManager.CreateTileUpdaterForApplication();

                string temperature = CurrentWeather.temperature.TemperatureUnit ? $"{CurrentWeather.temperature.temp_c}C" : $"{CurrentWeather.temperature.temp_f}F";
                string time        = DateTime.Now.ToString("ddd h:mm tt");

                //tile template
                string tileXMLString = $@"<tile>
                                            <visual baseUri=""Assets/Weather/"">
                                          
                                              <binding template=""TileSmall"" hint-textStacking=""center"">
                                                <text hint-style=""body"" hint-align=""center"">{temperature}</text>
                                              </binding>
                                          
                                              <binding displayName=""{CurrentWeather.city.name}"" template=""TileMedium"" hint-textStacking=""center"">
                                                <text hint-style=""body"" hint-align=""center"">{CurrentWeather.weather.value}</text>
                                                <text hint-style=""titleSubtle"" hint-align=""center"">{temperature}</text>
                                                <text hint-style=""captionSubtle"" hint-align=""center"">{time}</text>
                                              </binding>
                                          
                                              <binding displayName=""{CurrentWeather.city.name}"" template=""TileWide"" branding=""nameAndLogo"" hint-textStacking=""center"">
                                                <group>
                                                  <subgroup hint-weight=""44"">
                                                    <image src=""{CurrentWeather.weather.iconUrl}"" hint-removeMargin=""false""/>
                                                  </subgroup>
                                                  <subgroup>
                                                    <text hint-style=""body"">{CurrentWeather.weather.value}</text>
                                                    <text hint-style=""titleSubtle"">{temperature}</text>
                                                    <text hint-style=""captionSubtle"">{time}</text>
                                                  </subgroup>
                                                </group>
                                              </binding>
                                          
                                              <binding displayName=""{CurrentWeather.city.name}"" template=""TileLarge"" branding=""nameAndLogo"" hint-textStacking=""center"">
                                                <group>
                                                  <subgroup hint-weight=""1""/>
                                                  <subgroup hint-weight=""2"">
                                                    <image src=""{CurrentWeather.weather.iconUrl}""/>
                                                  </subgroup>
                                                  <subgroup hint-weight=""1""/>
                                                </group>
                                                <text hint-style=""body"" hint-align=""center"">{CurrentWeather.weather.value}</text>
                                                <text hint-style=""titleSubtle"" hint-align=""center"">{temperature}</text>
                                                <text hint-style=""captionSubtle"" hint-align=""center"">{time}</text>
                                              </binding>
                                          
                                            </visual>
                                          </tile>";

                XmlDocument tileXML = new XmlDocument();
                tileXML.LoadXml(tileXMLString);
                liveTile.Update(new TileNotification(tileXML));
                #endregion

                result = true;
            }));
            msg.Commands.Add(new UICommand("No"));
            await msg.ShowAsync();

            return(result);
        }
예제 #7
0
        // Ausgeführter Code
        // ----------------------------------------------------------------------------------------------------------------------
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();


            // Ordner öffnen oder erstellen
            StorageFolder SF          = ApplicationData.Current.LocalFolder;
            var           SF_Settings = await SF.CreateFolderAsync("Settings", CreationCollisionOption.OpenIfExists);



            // Variablen für zweites Tile
            string appbarTileId = "MySecondaryTile";



            // Design Auswahl
            string   String_Settings = "";
            int      SetDesign       = 2;
            bool     SetBattery      = true;
            DateTime FirstRunTime    = DateTime.Now;
            bool     FullVersion     = false;
            bool     Run             = false;
            // Sprach Variablen // Werden aus einer Datei geladen
            string Language    = "en-us";
            string Days        = "Days";
            string Day         = "Day";
            string Hours       = "Hours";
            string Hour        = "Hours";
            string Minutes     = "Minutes";
            string Minute      = "Minute";
            string IsLoading   = "is loading";
            string NameBattery = "Battery";



            // Prüfen of "Settings/Settings" besteht
            var F_Settings = await SF_Settings.CreateFileAsync("Settings.dat", CreationCollisionOption.OpenIfExists);

            var Temp_Settings = await FileIO.ReadTextAsync(F_Settings);

            // Prüfen ob Settings besteht
            String_Settings = Convert.ToString(Temp_Settings);
            //Einstellungen umsetzen
            string[] Split_Settings = Regex.Split(String_Settings, ";");
            // Einstellungen durchlaufen
            for (int i = 0; i < Split_Settings.Count(); i++)
            {
                // Einzelne Einstellung zerlegen
                string[] Split_Setting = Regex.Split(Split_Settings[i], "=");
                // Wenn Einstellung "Set_Folder"
                if (Split_Setting[0] == "SetDesign")
                {
                    SetDesign = Convert.ToInt32(Split_Setting[1]);
                }
                // Wenn Einstellung "SetBattery"
                if (Split_Setting[0] == "SetBattery")
                {
                    SetBattery = Convert.ToBoolean(Split_Setting[1]);
                }
            }



            // Prüfen of "Settings/LanguageString" besteht
            var F_LanguageString = await SF_Settings.CreateFileAsync("LanguageString.dat", CreationCollisionOption.OpenIfExists);

            var Temp_LanguageString = await FileIO.ReadTextAsync(F_LanguageString);

            // Prüfen ob Settings besteht
            string String_LanguageString = Convert.ToString(Temp_LanguageString);

            //Einstellungen umsetzen
            string[] Split_LanguageString = Regex.Split(String_LanguageString, ";");
            // Einstellungen durchlaufen
            for (int i = 0; i < Split_LanguageString.Count(); i++)
            {
                // Einzelne Einstellung zerlegen
                string[] Split_Setting = Regex.Split(Split_LanguageString[i], "=");
                // Wenn Einstellung "Language"
                if (Split_Setting[0] == "Language")
                {
                    Language = Split_Setting[1];
                }
                // Wenn Einstellung "Day"
                else if (Split_Setting[0] == "Day")
                {
                    Day = Split_Setting[1];
                }
                // Wenn Einstellung "Days"
                else if (Split_Setting[0] == "Days")
                {
                    Days = Split_Setting[1];
                }
                // Wenn Einstellung "Hour"
                else if (Split_Setting[0] == "Hour")
                {
                    Hour = Split_Setting[1];
                }
                // Wenn Einstellung "Hours"
                else if (Split_Setting[0] == "Hours")
                {
                    Hours = Split_Setting[1];
                }
                // Wenn Einstellung "Minute"
                else if (Split_Setting[0] == "Minute")
                {
                    Minute = Split_Setting[1];
                }
                // Wenn Einstellung "Minutes"
                else if (Split_Setting[0] == "Minutes")
                {
                    Minutes = Split_Setting[1];
                }
                // Wenn Einstellung "IsLoading"
                else if (Split_Setting[0] == "IsLoading")
                {
                    IsLoading = Split_Setting[1];
                }
                // Wenn Einstellung "NameBattery"
                else if (Split_Setting[0] == "NameBattery")
                {
                    NameBattery = Split_Setting[1];
                }
            }



            // Prüfen ob "Settings/FirstRunTime" besteht
            var F_FirstRunTime = await SF_Settings.CreateFileAsync("FirstRunTime.txt", CreationCollisionOption.OpenIfExists);

            var Temp_FirstRunTime = await FileIO.ReadTextAsync(F_FirstRunTime);

            // Prüfen ob FirstRunTime besteht
            string Temp_String = Convert.ToString(Temp_FirstRunTime);

            // Wenn FirstRunTime besteht
            if (Temp_String.Length > 0)
            {
                // DateTime aufteilen
                string[] Split_Temp_String = Regex.Split(Temp_String, ":");
                // FirstRunTime in DateTime umwadeln
                FirstRunTime = new DateTime(Convert.ToInt32(Split_Temp_String[0]), Convert.ToInt32(Split_Temp_String[1]), Convert.ToInt32(Split_Temp_String[2]), Convert.ToInt32(Split_Temp_String[3]), Convert.ToInt32(Split_Temp_String[4]), 0);
            }



            // Prüfen ob "Settings/FulVersion" besteht
            var F_FullVersion = await SF_Settings.CreateFileAsync("FullVersion.txt", CreationCollisionOption.OpenIfExists);

            var Temp_FullVersion = await FileIO.ReadTextAsync(F_FullVersion);

            // Prüfen ob FullVErsion besteht
            Temp_String = Convert.ToString(Temp_FullVersion);
            // Wenn FullVersion besteht
            if (Temp_String.Length > 0)
            {
                // FullVersin in Bool umwandeln
                FullVersion = Convert.ToBoolean(Temp_String);
            }



            // Bei Volversion
            if (FullVersion == false)
            {
                // Trial zeit ermitteln
                DateTime NowTime     = DateTime.Now;
                DateTime ExpiredTime = FirstRunTime.AddDays(2);
                // Wenn Zeit noch nicht abgelaufen ist
                if (NowTime < ExpiredTime)
                {
                    // Angeben das App ausgeführt wird
                    Run = true;
                }
            }



            // Wenn zweites Tile gepinnt wurde
            if (SecondaryTile.Exists(appbarTileId))
            {
                // Tile Updater erstellen
                var tileUpdater    = TileUpdateManager.CreateTileUpdaterForSecondaryTile(appbarTileId);
                var plannedUpdated = tileUpdater.GetScheduledTileNotifications();

                // CultureInfo laden
                //string language = GlobalizationPreferences.Languages.First();
                CultureInfo cultureInfo = new CultureInfo("en-us");
                try
                {
                    cultureInfo = new CultureInfo(Language);
                }
                catch
                { }

                // Batterieleistung ausgeben
                var      BatteryInfo   = Battery.GetDefault();
                TimeSpan BatteryTime   = BatteryInfo.RemainingDischargeTime;
                string   BatteryString = "";

                // Temp DateTime erstellen
                DateTime temp = DateTime.Now;
                // Aktueller DateTime erstellen und Sekunden auf 0 stellen
                DateTime now = new DateTime(temp.Year, temp.Month, temp.Day, temp.Hour, temp.Minute, 0);



                // Zeitrahmen erstellen, bis zu der die Uhr upgedatet wird wird
                DateTime planTill = now.AddMinutes(90);



                // Wenn Task ausgeführt wird
                if (FullVersion | Run)
                {
                    // Design 0 // TileSquareText02 // TileWideText01
                    if (SetDesign == 0)
                    {
                        // Zeit erstellen
                        DateTime updateTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0).AddMinutes(1);
                        //if (plannedUpdated.Count > 0)
                        //    updateTime = plannedUpdated.Select(x => x.DeliveryTime.DateTime).Union(new[] { updateTime }).Max();

                        // Strings für die Tiles erstellen
                        string Str0 = now.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                        string Str1 = now.ToString(cultureInfo.DateTimeFormat.LongDatePattern);
                        string Str2 = "";
                        if (SetBattery == true)
                        {
                            // String der Batterieanzeige ändern
                            BatteryString = "";
                            if (BatteryTime.Days > 100)
                            {
                                BatteryString = IsLoading;
                            }
                            else
                            {
                                if (BatteryTime.Days > 0)
                                {
                                    if (BatteryTime.Days == 1)
                                    {
                                        BatteryString = "1 " + Day + " ";
                                    }
                                    else
                                    {
                                        BatteryString = BatteryTime.Days.ToString() + " " + Days + " ";
                                    }
                                }
                                if (BatteryTime.Hours == 1)
                                {
                                    BatteryString += "1 " + Hour + " ";
                                }
                                else
                                {
                                    BatteryString += BatteryTime.Hours + " " + Hours + " ";
                                }
                                if (BatteryTime.Minutes == 1)
                                {
                                    BatteryString += "1 " + Minute + " ";
                                }
                                else
                                {
                                    BatteryString += BatteryTime.Minutes + " " + Minutes + " ";
                                }
                            }
                            Str1 += "\r\n" + BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                            Str2  = BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                        }

                        // XML für die Tiles erstellen
                        const string xml = @"<tile><visual>
                                        <binding branding='none' template=""TileSquareText02""><text id=""1"">{0}</text><text id=""2"">{1}</text></binding>
                                        <binding branding='none'  template=""TileWideText01""><text id=""1"">{0}</text><text id=""2"">{1}</text><text id=""3"">{2}</text><text id=""4""></text><text id=""5""></text></binding>
                                   </visual></tile>";

                        // Tiles erstellen
                        var         tileXmlNow  = string.Format(xml, Str0, Str1, Str2);
                        XmlDocument documentNow = new XmlDocument();
                        documentNow.LoadXml(tileXmlNow);

                        // Tile Updaten
                        tileUpdater.Update(new TileNotification(documentNow)
                        {
                            ExpirationTime = now.AddMinutes(1)
                        });

                        // Tile Update Plan erstellen
                        for (var startPlanning = updateTime; startPlanning < planTill; startPlanning = startPlanning.AddMinutes(1))
                        {
                            Debug.WriteLine(startPlanning);
                            Debug.WriteLine(planTill);

                            try
                            {
                                // Strings für die Tiles erstellen
                                Str0 = startPlanning.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                                Str1 = startPlanning.ToString(cultureInfo.DateTimeFormat.LongDatePattern);
                                Str2 = "";
                                if (SetBattery == true)
                                {
                                    // Batteriezeit verringern
                                    BatteryTime = BatteryTime.Add(new TimeSpan(0, -1, 0));
                                    // Sting der Batterieanzeige ändern
                                    BatteryString = "";
                                    if (BatteryTime.Days > 100)
                                    {
                                        BatteryString = IsLoading;
                                    }
                                    else
                                    {
                                        if (BatteryTime.Days > 0)
                                        {
                                            if (BatteryTime.Days == 1)
                                            {
                                                BatteryString = "1 " + Day + " ";
                                            }
                                            else
                                            {
                                                BatteryString = BatteryTime.Days.ToString() + " " + Days + " ";
                                            }
                                        }
                                        if (BatteryTime.Hours == 1)
                                        {
                                            BatteryString += "1 " + Hour + " ";
                                        }
                                        else
                                        {
                                            BatteryString += BatteryTime.Hours + " " + Hours + " ";
                                        }
                                        if (BatteryTime.Minutes == 1)
                                        {
                                            BatteryString += "1 " + Minute + " ";
                                        }
                                        else
                                        {
                                            BatteryString += BatteryTime.Minutes + " " + Minutes + " ";
                                        }
                                    }
                                    Str1 += "\r\n" + BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                                    Str2  = BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                                }

                                // Tiles erstellen
                                var         tileXml  = string.Format(xml, Str0, Str1, Str2);
                                XmlDocument document = new XmlDocument();
                                document.LoadXml(tileXml);

                                // Tiles Plan erstellen
                                ScheduledTileNotification scheduledNotification = new ScheduledTileNotification(document, new DateTimeOffset(startPlanning))
                                {
                                    ExpirationTime = startPlanning.AddMinutes(1)
                                };
                                tileUpdater.AddToSchedule(scheduledNotification);

                                Debug.WriteLine("schedule for: " + startPlanning);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("exception: " + e.Message);
                            }
                        }
                    }



                    // Design 1 // TileSquareText02 // TileWideText03
                    else if (SetDesign == 1)
                    {
                        // Zeit erstellen
                        DateTime updateTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0).AddMinutes(1);
                        //if (plannedUpdated.Count > 0)
                        //    updateTime = plannedUpdated.Select(x => x.DeliveryTime.DateTime).Union(new[] { updateTime }).Max();

                        // Strings für die Tiles erstellen
                        string Str0 = now.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                        string Str1 = "";
                        string Str2 = "";
                        if (SetBattery == true)
                        {
                            // String der Batteriezeit verändern
                            if (BatteryTime.Days > 100)
                            {
                                BatteryString = IsLoading;
                            }
                            else
                            {
                                BatteryString = ((BatteryTime.Days * 24) + BatteryTime.Hours).ToString() + ":" + BatteryTime.Minutes;
                            }
                            Str1 = now.ToString(cultureInfo.DateTimeFormat.LongDatePattern) + "\r\n" + BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                            Str2 = Str0 + "\r\n" + Str1;
                        }
                        else
                        {
                            Str1 = now.ToString(cultureInfo.DateTimeFormat.LongDatePattern);
                            Str2 = Str0 + "\r\n" + Str1;
                        }

                        // XML für die Tiles erstellen
                        const string xml = @"<tile><visual>
                                        <binding branding='none' template=""TileSquareText02""><text id=""1"">{0}</text><text id=""2"">{1}</text></binding>
                                        <binding branding='none'  template=""TileWideText03""><text id=""1"">{2}</text></binding>
                                   </visual></tile>";

                        // Tiles erstellen
                        var         tileXmlNow  = string.Format(xml, Str0, Str1, Str2);
                        XmlDocument documentNow = new XmlDocument();
                        documentNow.LoadXml(tileXmlNow);

                        // Tile Updaten
                        tileUpdater.Update(new TileNotification(documentNow)
                        {
                            ExpirationTime = now.AddMinutes(1)
                        });

                        // Tile Update Plan erstellen
                        for (var startPlanning = updateTime; startPlanning < planTill; startPlanning = startPlanning.AddMinutes(1))
                        {
                            Debug.WriteLine(startPlanning);
                            Debug.WriteLine(planTill);

                            try
                            {
                                // Strings für die Tiles erstellen
                                Str0 = startPlanning.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                                Str1 = "";
                                Str2 = "";
                                if (SetBattery == true)
                                {
                                    // Batteriezeit verringern
                                    BatteryTime = BatteryTime.Add(new TimeSpan(0, -1, 0));
                                    // String der Batteriezeit verändern
                                    if (BatteryTime.Days > 100)
                                    {
                                        BatteryString = IsLoading;
                                    }
                                    else
                                    {
                                        BatteryString = ((BatteryTime.Days * 24) + BatteryTime.Hours).ToString() + ":" + BatteryTime.Minutes;
                                    }
                                    Str1 = startPlanning.ToString(cultureInfo.DateTimeFormat.LongDatePattern) + "\r\n" + BatteryInfo.RemainingChargePercent + "% " + BatteryString;
                                    Str2 = Str0 + "\r\n" + Str1;
                                }
                                else
                                {
                                    Str1 = startPlanning.ToString(cultureInfo.DateTimeFormat.LongDatePattern);
                                    Str2 = Str0 + "\r\n" + Str1;
                                }

                                // Tiles erstellen
                                var         tileXml  = string.Format(xml, Str0, Str1, Str2);
                                XmlDocument document = new XmlDocument();
                                document.LoadXml(tileXml);

                                // Tiles Plan erstellen
                                ScheduledTileNotification scheduledNotification = new ScheduledTileNotification(document, new DateTimeOffset(startPlanning))
                                {
                                    ExpirationTime = startPlanning.AddMinutes(1)
                                };
                                tileUpdater.AddToSchedule(scheduledNotification);

                                Debug.WriteLine("schedule for: " + startPlanning);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("exception: " + e.Message);
                            }
                        }
                    }



                    // Design 2 // TileSquareText02 // TileWideBlockAndText01
                    else if (SetDesign == 2)
                    {
                        // Zeit erstellen
                        DateTime updateTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0).AddMinutes(1);
                        // if (plannedUpdated.Count > 0)
                        //    updateTime = plannedUpdated.Select(x => x.DeliveryTime.DateTime).Union(new[] { updateTime }).Max();

                        // Strings für die Tiles erstellen
                        // Strings für die Tiles erstellen
                        int DW = 0;
                        if (now.DayOfWeek.ToString() == "Monday")
                        {
                            DW = 1;
                        }
                        else if (now.DayOfWeek.ToString() == "Tuesday")
                        {
                            DW = 2;
                        }
                        else if (now.DayOfWeek.ToString() == "Wednesday")
                        {
                            DW = 3;
                        }
                        else if (now.DayOfWeek.ToString() == "Thursday")
                        {
                            DW = 4;
                        }
                        else if (now.DayOfWeek.ToString() == "Friday")
                        {
                            DW = 5;
                        }
                        else if (now.DayOfWeek.ToString() == "Saturday")
                        {
                            DW = 6;
                        }
                        string Str0 = now.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                        string Str1 = cultureInfo.DateTimeFormat.DayNames[DW] + "  ";
                        string Str2 = now.ToString(cultureInfo.DateTimeFormat.MonthDayPattern);
                        string Str3 = "";
                        string Str4 = "";
                        if (SetBattery == true)
                        {
                            // Batterie Prozenz anzeigen
                            Str3 = NameBattery + " " + BatteryInfo.RemainingChargePercent + "%";
                            // String der Batteriezeit verändern
                            if (BatteryTime.Days > 100)
                            {
                                BatteryString = IsLoading;
                            }
                            else
                            {
                                if (BatteryTime.Days > 0)
                                {
                                    if (BatteryTime.Days == 1)
                                    {
                                        BatteryString = "1 " + Day + " ";
                                    }
                                    else
                                    {
                                        BatteryString = BatteryTime.Days.ToString() + " " + Days + " ";
                                    }
                                }
                                if (BatteryTime.Hours == 1)
                                {
                                    BatteryString += "1 " + Hour + " ";
                                }
                                else
                                {
                                    BatteryString += BatteryTime.Hours + " " + Hours + " ";
                                }
                                if (BatteryTime.Minutes == 1)
                                {
                                    BatteryString += "1 " + Minute + " ";
                                }
                                else
                                {
                                    BatteryString += BatteryTime.Minutes + " " + Minutes + " ";
                                }
                            }
                            Str4 = BatteryString;
                        }
                        string   Str5   = now.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                        string   Str6   = "";
                        string[] Split5 = Regex.Split(Str5, "AM");
                        if (Split5.Count() > 1)
                        {
                            Str5 = Split5[0].Trim();
                            Str6 = "AM";
                        }
                        else
                        {
                            Split5 = Regex.Split(Str5, "PM");
                            if (Split5.Count() > 1)
                            {
                                Str5 = Split5[0].Trim();
                                Str6 = "PM";
                            }
                        }

                        // XML für die Tiles erstellen
                        const string xml = @"<tile><visual>
                                        <binding branding='none' template=""TileSquareBlock""><text id=""1"">{5}</text><text id=""2"">{6}</text></binding>
                                        <binding branding='none'  template=""TileWideBlockAndText01""><text id=""1"">{0}</text><text id=""2"">{1}</text><text id=""3"">{2}</text><text id=""4"">{3}</text><text id=""5"">{4}</text><text id=""6""></text></binding>
                                   </visual></tile>";

                        // Tiles erstellen
                        var         tileXmlNow  = string.Format(xml, Str0, Str1, Str2, Str3, Str4, Str5, Str6);
                        XmlDocument documentNow = new XmlDocument();
                        documentNow.LoadXml(tileXmlNow);

                        // Tile Updaten
                        tileUpdater.Update(new TileNotification(documentNow)
                        {
                            ExpirationTime = now.AddMinutes(1)
                        });

                        // Tile Update Plan erstellen
                        for (var startPlanning = updateTime; startPlanning < planTill; startPlanning = startPlanning.AddMinutes(1))
                        {
                            Debug.WriteLine(startPlanning);
                            Debug.WriteLine(planTill);

                            try
                            {
                                // Strings für die Tiles erstellen
                                Str0 = startPlanning.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                                Str1 = startPlanning.DayOfWeek.ToString() + " ";
                                Str2 = startPlanning.ToString(cultureInfo.DateTimeFormat.MonthDayPattern);
                                Str3 = "";
                                Str4 = "";
                                if (SetBattery == true)
                                {
                                    // Batterie Prozenz anzeigen
                                    Str3 = NameBattery + " " + BatteryInfo.RemainingChargePercent + "%";
                                    // Batteriezeit verringern
                                    BatteryTime = BatteryTime.Add(new TimeSpan(0, -1, 0));
                                    // String der Batteriezeit verändern
                                    if (BatteryTime.Days > 100)
                                    {
                                        BatteryString = IsLoading;
                                    }
                                    else
                                    {
                                        if (BatteryTime.Days > 0)
                                        {
                                            if (BatteryTime.Days == 1)
                                            {
                                                BatteryString = "1 " + Day + " ";
                                            }
                                            else
                                            {
                                                BatteryString = BatteryTime.Days.ToString() + " " + Days + " ";
                                            }
                                        }
                                        if (BatteryTime.Hours == 1)
                                        {
                                            BatteryString += "1 " + Hour + " ";
                                        }
                                        else
                                        {
                                            BatteryString += BatteryTime.Hours + " " + Hours + " ";
                                        }
                                        if (BatteryTime.Minutes == 1)
                                        {
                                            BatteryString += "1 " + Minute + " ";
                                        }
                                        else
                                        {
                                            BatteryString += BatteryTime.Minutes + " " + Minutes + " ";
                                        }
                                    }
                                    Str4 = BatteryString;
                                }
                                Str5   = startPlanning.ToString(cultureInfo.DateTimeFormat.ShortTimePattern);
                                Str6   = "";
                                Split5 = Regex.Split(Str5, " ");
                                if (Split5.Count() > 1)
                                {
                                    Str5 = Split5[0].Trim();
                                    Str6 = Split5[1].Trim();
                                }

                                // Tiles erstellen
                                var         tileXml  = string.Format(xml, Str0, Str1, Str2, Str3, Str4, Str5, Str6);
                                XmlDocument document = new XmlDocument();
                                document.LoadXml(tileXml);

                                // Tiles Plan erstellen
                                ScheduledTileNotification scheduledNotification = new ScheduledTileNotification(document, new DateTimeOffset(startPlanning))
                                {
                                    ExpirationTime = startPlanning.AddMinutes(1)
                                };
                                tileUpdater.AddToSchedule(scheduledNotification);

                                Debug.WriteLine("schedule for: " + startPlanning);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine("exception: " + e.Message);
                            }
                        }
                    }
                }
            }



            // Wenn Task nicht ausgeführt wird
            else
            {
            }

            deferral.Complete();
        }
        public void ActivateTileNotifications(string tileId, Uri tileContentUri, PeriodicUpdateRecurrence recurrence)
        {
            var tileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId);

            tileUpdater.StartPeriodicUpdate(tileContentUri, recurrence);
        }
예제 #9
0
 public static void ClearAll()
 {
     TileUpdateManager.CreateTileUpdaterForApplication().Clear();
 }
예제 #10
0
        private void EvaluateMessages(Messages obj)
        {
            if (obj == Messages.ExpenseChanged)
            {
                var vm = SimpleIoc.Default.GetInstance <MainViewModel>();
                if (vm != null && vm.ExpenseCollections != null)
                {
                    var newNotes = vm.ExpenseCollections.SelectMany(noteCollectionModel => noteCollectionModel.Expenses).ToList();
                    var adap2    = new TileBindingContentAdaptive()
                    {
                        Children =
                        {
                            new TileText()
                            {
                                Style = TileTextStyle.Body,
                                Text  = newNotes.Sum(n => n.Amount).ToString("0.##") + " total spent"
                            },
                            // For spacing
                            new TileText()
                            {
                                Style = TileTextStyle.Body,
                                Text  = newNotes.Where(n => n.CreateTime > DateTime.Now.Subtract(TimeSpan.FromDays(7))).Sum(n => n.Amount).ToString("0.##") + " spent last 7 days"
                            },
                            // For spacing
                            new TileText()
                            {
                                Style = TileTextStyle.Body,
                                Text  = newNotes.Where(n => n.CreateTime > DateTime.Now.Subtract(DateTime.Now - DateTime.Today)).Sum(n => n.Amount).ToString("0.##") + " spent today"
                            },
                        }
                    };

                    var tileLarge = new TileBinding()
                    {
                        Branding = TileBranding.None,
                        Content  = adap2
                    };

                    var tileSmall = new TileBinding()
                    {
                        Branding = TileBranding.None,
                        Content  = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Style = TileTextStyle.Header,
                                    Text  = newNotes.Count.ToString("00"),
                                    Align = TileTextAlign.Center
                                }
                            }
                        }
                    };

                    var tileVisual = new TileVisual()
                    {
                        TileLarge  = tileLarge,
                        TileMedium = tileLarge,
                        TileWide   = tileLarge,
                        TileSmall  = tileSmall,
                    };

                    var tileContent = new TileContent()
                    {
                        Visual = tileVisual
                    };

                    var notif   = new TileNotification(tileContent.GetXml());
                    var updater = TileUpdateManager.CreateTileUpdaterForApplication();
                    updater.Update(notif);
                }
            }
        }
예제 #11
0
        void ResetLiveTileButton_Click(object sender, RoutedEventArgs e)
        {
            var updater = TileUpdateManager.CreateTileUpdaterForApplication();

            updater.Clear();
        }
예제 #12
0
        public static async void SetLiveTileBackgroundTask(bool Val)
        {
            try
            {
                var req = await BackgroundExecutionManager.RequestAccessAsync();

                if (req == BackgroundAccessStatus.AlwaysAllowed || req == BackgroundAccessStatus.AllowedSubjectToSystemPolicy ||
                    req == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || req == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
                {
                    var list = BackgroundTaskRegistration.AllTasks.Where(x => x.Value.Name == "WinGoMapsTile");
                    foreach (var item in list)
                    {
                        item.Value.Unregister(false);
                    }
                    if (Val)
                    {
                        BackgroundTaskBuilder build = new BackgroundTaskBuilder();
                        build.IsNetworkRequested = true;
                        build.Name           = "WinGoMapsTile";
                        build.TaskEntryPoint = "LiveTileTask.Update";
                        build.SetTrigger(new TimeTrigger(15, false));
                        var b = build.Register();
                        if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed)
                        {
                            var geolocator = new Geolocator();
                            var Location   = await geolocator.GetGeopositionAsync();

                            var ul   = Location.Coordinate.Point.Position;
                            var http = AppCore.HttpClient;
                            http.DefaultRequestHeaders.UserAgent.ParseAdd("MahStudioWinGoMaps");
                            var res      = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=200x200", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var reswide  = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=310x150", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var resLarge = await(await http.GetAsync(new Uri($"https://maps.googleapis.com/maps/api/staticmap?center={ul.Latitude},{ul.Longitude}&zoom=16&size=310x310", UriKind.RelativeOrAbsolute))).Content.ReadAsBufferAsync();
                            var f        = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTile.png", CreationCollisionOption.OpenIfExists);

                            var fWide = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTileWide.png", CreationCollisionOption.OpenIfExists);

                            var fLarge = await ApplicationData.Current.LocalFolder.CreateFileAsync("LiveTileLarge.png", CreationCollisionOption.OpenIfExists);

                            var str = await f.OpenAsync(FileAccessMode.ReadWrite);

                            var strwide = await fWide.OpenAsync(FileAccessMode.ReadWrite);

                            var strLarge = await fLarge.OpenAsync(FileAccessMode.ReadWrite);

                            await str.WriteAsync(res);

                            await strwide.WriteAsync(reswide);

                            await strLarge.WriteAsync(resLarge);

                            str.Dispose();
                            strwide.Dispose();
                            strLarge.Dispose();

                            var    update = TileUpdateManager.CreateTileUpdaterForApplication();
                            string xml    = "<tile>\n";
                            xml += "<visual version=\"4\">\n";
                            xml += "  <binding template=\"TileSquare150x150Image\" fallback=\"TileSquareImage\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTile.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "  <binding template=\"TileWide310x150Image\" fallback=\"TileWideImage\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTileWide.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "  <binding template=\"TileSquare310x310Image\" fallback=\"TileSquareImageLarge\">\n";
                            xml += "      <image id=\"1\" src=\"ms-appdata:///local/LiveTileLarge.png\"/>\n";
                            xml += "  </binding>\n";
                            xml += "</visual>\n";
                            xml += "</tile>";

                            XmlDocument txml = new XmlDocument();
                            txml.LoadXml(xml);
                            TileNotification tNotification = new TileNotification(txml);

                            update.Clear();
                            update.Update(tNotification);
                            //XmlDocument tileXmlwide = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);
                            //new Windows.UI.Popups.MessageDialog(tileXmlwide.GetXml()).ShowAsync();
                            //XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Image);
                            //tileXml.GetElementsByTagName("image")[0].Attributes[1].NodeValue = "ms-appdata:///local/LiveTile.png";
                            //tileXmlwide.GetElementsByTagName("image")[0].Attributes[1].NodeValue = "ms-appdata:///local/LiveTileWide.png";
                            //update.Update(new TileNotification(xml));
                        }
                    }
                }
            }
            catch { }
        }
예제 #13
0
 void StopTilePolling_Click(object sender, RoutedEventArgs e)
 {
     TileUpdateManager.CreateTileUpdaterForApplication().StopPeriodicUpdate();
     rootPage.NotifyUser("Stopped polling.", NotifyType.StatusMessage);
 }
예제 #14
0
        void Toast()
        {
            string title        = "Title";
            string content      = "Content";
            string image        = "https://picsum.photos/360/202?image=883";
            string logo         = "";
            var    toastContent = new ToastContent()
            {
                Visual = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = title
                            },
                            new AdaptiveText()
                            {
                                Text = content
                            },
                            new AdaptiveImage()
                            {
                                Source = image
                            },
                        },
                        AppLogoOverride = new ToastGenericAppLogo()
                        {
                            Source   = logo,
                            HintCrop = ToastGenericAppLogoCrop.Circle
                        }
                    },
                }
            };

            var tileContent = new TileContent
            {
                Visual = new TileVisual
                {
                    TileMedium = new TileBinding
                    {
                        Content = new TileBindingContentAdaptive
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text = title
                                },
                                new AdaptiveText()
                                {
                                    Text = content
                                },
                                new AdaptiveImage()
                                {
                                    Source = image
                                },
                            }
                        }
                    }
                }
            };

            //send toast
            var toastNotification = new ToastNotification(toastContent.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(toastNotification);

            //send tile
            var tileNotification = new TileNotification(tileContent.GetXml());

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            //send badge
            //var badgeContent = new BadgeNumericContent()
            //{
            //    Number = 10,
            //};
            //var badgeNotification = new BadgeNotification(badgeContent.GetXml());
            //BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeNotification);
        }
예제 #15
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings;
            ApplicationDataContainer localSettings   = ApplicationData.Current.LocalSettings;

            resourceLoader = ResourceLoader.GetForViewIndependentUse();

            //main tile
            Windows.UI.Notifications.TileUpdater mainmngr = null;
            try { mainmngr = TileUpdateManager.CreateTileUpdaterForApplication(); }
            catch (Exception)
            {
                deferral.Complete();
                return;
            }

            string town = null;

            if ((bool?)localSettings.Values["location"] != false)
            {
                town = await Utilities.LocationFinder.GetLocation();
            }

            if ((string)localSettings.Values["lastlocation"] == town && (string)localSettings.Values["lastupdate"] == DateTime.Today.Date.ToString())
            {
                deferral.Complete();
                return;
            }

            foreach (var tile in mainmngr.GetScheduledTileNotifications())
            {
                mainmngr.RemoveFromSchedule(tile);
            }
            mainmngr.Clear();

            var             profile = NetworkInformation.GetInternetConnectionProfile();
            NetworkCostType cost    = NetworkCostType.Unknown;

            if (profile != null)
            {
                cost = profile.GetConnectionCost().NetworkCostType;
            }

            if (town != null)
            {
                Utilities.LineSerializer lineSerializer = new Utilities.LineSerializer(resourceLoader);
                IList <Line>             linesfromhere  = await lineSerializer.readLinesFrom(town);

                List <int> busindices = new List <int>();

                if (((bool)localSettings.Values["alwaysupdate"] || cost == NetworkCostType.Unrestricted) && linesfromhere.Count == 0 && (bool)roamingSettings.Values["showhome"] && roamingSettings.Values["homename"] != null)
                {
                    List <Dictionary <string, string> > stops = await Utilities.Autocomplete.GetSuggestions(town, DateTime.Today.Date.ToString());

                    foreach (var stop in stops)
                    {
                        if (stop["Nev"] == town)
                        {
                            Line templine = new Line(stop["VarosID"], (string)roamingSettings.Values["homesid"], stop["MegalloID"], (string)roamingSettings.Values["homelsid"], stop["Nev"], (string)roamingSettings.Values["homename"]);
                            await templine.updateOn(true);

                            bool   isfirst      = true;
                            string previoustime = "";
                            foreach (var bus in templine.Buses)
                            {
                                if (!(!(bool)roamingSettings.Values["canchange"] && bus["vonalnev"].Split('|')[0] == " ∙∙∙") && !((bool)roamingSettings.Values["exact"] && (string)roamingSettings.Values["homename"] != bus["erkezesi_hely"] && ((string)roamingSettings.Values["homename"]).Contains(",")))
                                {
                                    DateTime showUpdateAt;
                                    if (isfirst)
                                    {
                                        showUpdateAt = DateTime.Now.AddSeconds(5);
                                        isfirst      = false;
                                    }
                                    else
                                    {
                                        showUpdateAt = DateTime.Parse(previoustime).AddSeconds(30);
                                    }

                                    previoustime = bus["indulasi_ido"];
                                    XmlDocument xmlDoc = getXML(town, bus["vonalnev"].Split('|')[0], bus["indulasi_ido"], bus["indulasi_hely"], bus["erkezesi_ido"], bus["erkezesi_hely"], false);
                                    ScheduledTileNotification scheduledUpdate = new ScheduledTileNotification(xmlDoc, new DateTimeOffset(showUpdateAt));
                                    scheduledUpdate.ExpirationTime = new DateTimeOffset(DateTime.Today.AddDays(1).AddHours(1));
                                    mainmngr.AddToSchedule(scheduledUpdate);
                                }
                            }
                            deferral.Complete();
                            return;
                        }
                    }
                }

                // update lines
                foreach (var line in linesfromhere)
                {
                    if (((bool)localSettings.Values["alwaysupdate"] || cost == NetworkCostType.Unrestricted) && line.LastUpdated < DateTime.Today.Date)
                    {
                        try { await line.updateOn(DateTime.Today); }
                        catch (System.Net.Http.HttpRequestException)
                        {
                            deferral.Complete();
                            return;
                        }
                        line.LastUpdated = DateTime.Today.Date;

                        await lineSerializer.saveLine(line);
                    }

                    busindices.Add(0);
                }

                bool   done = false;
                int    minind;
                string prevfromtime = "";
                bool   first        = true;

                // go through all possible lines
                while (!done)
                {
                    DateTime mintime = DateTime.Today.AddDays(1);
                    minind = -1;

                    for (int j = 0; j < linesfromhere.Count; j++) // find next time
                    {
                        if (linesfromhere[j].Buses.Count < 1 && j < linesfromhere.Count - 1)
                        {
                            j++;
                        }
                        else if (linesfromhere[j].Buses.Count < 1 && j == linesfromhere.Count - 1)
                        {
                            break;
                        }

                        int i = busindices[j];
                        if (i != -1 && i < linesfromhere[j].Buses.Count)
                        {
                            string fromtime, num, from, to;
                            linesfromhere[j].Buses[i].TryGetValue("vonalnev", out num);
                            linesfromhere[j].Buses[i].TryGetValue("indulasi_ido", out fromtime);
                            linesfromhere[j].Buses[i].TryGetValue("indulasi_hely", out from);
                            linesfromhere[j].Buses[i].TryGetValue("erkezesi_hely", out to);
                            num = num.Split('|')[0];

                            var fromtime_date = DateTime.ParseExact(fromtime, "HH:mm", CultureInfo.InvariantCulture);

                            if (fromtime_date >= DateTime.Now && !(!(bool)roamingSettings.Values["canchange"] && num == " ∙∙∙") &&
                                !((bool)roamingSettings.Values["exact"] && ((linesfromhere[j].From != from && linesfromhere[j].From.Contains(",")) || (linesfromhere[j].To != to && linesfromhere[j].To.Contains(",")))))
                            {
                                if (fromtime_date < mintime)
                                {
                                    minind  = j;
                                    mintime = fromtime_date;
                                }
                            }
                            else if (linesfromhere[j].Buses.Count - 1 > busindices[j])
                            {
                                busindices[j]++;
                                j--;
                            }
                            else
                            {
                                busindices[j] = -1;
                            }
                        }
                    }

                    if (minind != -1)
                    {
                        int    i = busindices[minind];
                        string fromtime, num, from, to, name, totime;
                        name = linesfromhere[minind].Name;
                        linesfromhere[minind].Buses[i].TryGetValue("erkezesi_ido", out totime);
                        linesfromhere[minind].Buses[i].TryGetValue("vonalnev", out num);
                        linesfromhere[minind].Buses[i].TryGetValue("indulasi_ido", out fromtime);
                        linesfromhere[minind].Buses[i].TryGetValue("indulasi_hely", out from);
                        linesfromhere[minind].Buses[i].TryGetValue("erkezesi_hely", out to);
                        num = num.Split('|')[0];

                        XmlDocument xmlDoc = getXML(name, num, fromtime, from, totime, to, false);

                        DateTime showUpdateAt;
                        if (first)
                        {
                            showUpdateAt = DateTime.Now.AddSeconds(5);
                            first        = false;
                        }
                        else
                        {
                            showUpdateAt = DateTime.Parse(prevfromtime).AddSeconds(30);
                        }

                        ScheduledTileNotification scheduledUpdate = new ScheduledTileNotification(xmlDoc, new DateTimeOffset(showUpdateAt));
                        scheduledUpdate.ExpirationTime = new DateTimeOffset(DateTime.Today.AddDays(1).AddHours(1));
                        mainmngr.AddToSchedule(scheduledUpdate);

                        prevfromtime = fromtime;
                        if (busindices[minind] != -1 && linesfromhere[minind].Buses.Count - 1 > busindices[minind])
                        {
                            busindices[minind]++;
                        }
                        else
                        {
                            busindices[minind] = -1;
                        }
                    }

                    done = true;
                    for (int i = 0; i < busindices.Count; i++)
                    {
                        if (busindices[i] == linesfromhere[i].Buses.Count)
                        {
                            busindices[i] = -1;
                        }
                        if (busindices[i] != -1)
                        {
                            done = false;
                        }
                    }
                }

                localSettings.Values["lastlocation"] = town;
                localSettings.Values["lastupdate"]   = DateTime.Today.Date.ToString();
            }
            deferral.Complete();
        }
예제 #16
0
 private static void ClearPrimaryTileNotification()
 {
     TileUpdateManager.CreateTileUpdaterForApplication().Clear();
 }
예제 #17
0
        private void UpdateTile(BaseTrack track)
        {
            // Not supported on xbox
            if (DeviceHelper.IsXbox)
            {
                return;
            }

            var updater = TileUpdateManager.CreateTileUpdaterForApplication();

            updater.EnableNotificationQueue(true);
            updater.Clear();

            var content = new TileContent
            {
                Visual = new TileVisual
                {
                    Branding = TileBranding.NameAndLogo,

                    TileMedium = new TileBinding
                    {
                        Content = new TileBindingContentAdaptive
                        {
                            PeekImage = new TilePeekImage
                            {
                                Source      = track.ArtworkUrl,
                                HintOverlay = 30
                            },

                            Children =
                            {
                                new AdaptiveText
                                {
                                    Text = "Now Playing"
                                },
                                new AdaptiveText
                                {
                                    Text      = track.Title,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                    HintWrap  = true
                                }
                            }
                        }
                    },

                    TileLarge = new TileBinding
                    {
                        Content = new TileBindingContentAdaptive
                        {
                            PeekImage = new TilePeekImage
                            {
                                Source      = track.ArtworkUrl,
                                HintOverlay = 30
                            },

                            Children =
                            {
                                new AdaptiveText
                                {
                                    Text = "Now Playing"
                                },
                                new AdaptiveText
                                {
                                    Text      = track.Title,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                    HintWrap  = true
                                }
                            }
                        }
                    },

                    TileSmall = new TileBinding
                    {
                        Content = new TileBindingContentAdaptive
                        {
                            PeekImage = new TilePeekImage
                            {
                                Source      = track.ArtworkUrl,
                                HintOverlay = 30
                            },

                            Children =
                            {
                                new AdaptiveText
                                {
                                    Text = "Now Playing"
                                },
                                new AdaptiveText
                                {
                                    Text      = track.Title,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                    HintWrap  = true
                                }
                            }
                        }
                    },
                    TileWide = new TileBinding
                    {
                        Content = new TileBindingContentAdaptive
                        {
                            PeekImage = new TilePeekImage
                            {
                                Source      = track.ArtworkUrl,
                                HintOverlay = 30
                            },

                            Children =
                            {
                                new AdaptiveText
                                {
                                    Text = "Now Playing"
                                },
                                new AdaptiveText
                                {
                                    Text      = track.Title,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle,
                                    HintWrap  = true
                                }
                            }
                        }
                    }
                }
            };

            var notification = new TileNotification(content.GetXml());

            updater.Update(notification);
        }
예제 #18
0
 public static void ClearSecondaryTileNofification(string tileId)
 {
     TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId).Clear();
 }
예제 #19
0
        private void update_tile(object sender, RoutedEventArgs e)
        {
            if (ViewModel.getItems.Count < 1)
            {
                return;
            }
            string      titleText = ViewModel.getItems[0].title;
            string      dateText  = "" + ViewModel.getItems[0].date.Year + '-' + ViewModel.getItems[0].date.Month + '-' + ViewModel.getItems[0].date.Day;
            TileContent content   = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileLarge = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text  = titleText,
                                    Style = TileTextStyle.Subheader
                                },
                                new TileText()
                                {
                                    Text  = dateText,
                                    Style = TileTextStyle.Title
                                }
                            }
                        }
                    },
                    TileMedium = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text  = titleText,
                                    Style = TileTextStyle.Subtitle
                                },
                                new TileText()
                                {
                                    Text  = dateText,
                                    Style = TileTextStyle.Body
                                }
                            }
                        }
                    },
                    TileWide = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text  = titleText,
                                    Style = TileTextStyle.Subtitle
                                },
                                new TileText()
                                {
                                    Text  = dateText,
                                    Style = TileTextStyle.Subtitle
                                }
                            }
                        }
                    }
                }
            };

            var notification = new TileNotification(content.GetXml());

            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
        }
예제 #20
0
        async private System.Threading.Tasks.Task GetTasksforLiveTile()
        {
            try
            {
                var updaterWide  = TileUpdateManager.CreateTileUpdaterForApplication();
                var updaterSqure = TileUpdateManager.CreateTileUpdaterForApplication();
                var updaterBadge = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
                updaterWide.EnableNotificationQueue(true);
                updaterSqure.EnableNotificationQueue(true);
                updaterWide.Clear();
                updaterSqure.Clear();
                updaterBadge.Clear();
                int counter = 0;

                var crd = _credentialStore.GetSavedCredentials(PasswordVaultResourceName);
                VIServiceHelper.Instance.ConnectAsync(crd.UserName, crd.Password, new EventAggregator());
                var allTasks = await VIServiceHelper.Instance.SyncTasksFromSvcAsync();

                if (allTasks != null)
                {
                    foreach (var collection in allTasks.InSetsOf(3))
                    {
                        int index = 0;

                        XmlDocument tileXmlSquare = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare310x310TextList01);

                        var bindingElementSquare = (XmlElement)tileXmlSquare.GetElementsByTagName("binding").Item(0);
                        bindingElementSquare.SetAttribute("branding", "name");

                        XmlNodeList tileTextAttributes = tileXmlSquare.GetElementsByTagName("text");

                        foreach (var item in collection)
                        {
                            XmlDocument tileXmlWide = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideBlockAndText02);

                            var bindingElemWide = (XmlElement)tileXmlWide.GetElementsByTagName("binding").Item(0);
                            bindingElemWide.SetAttribute("branding", "name");

                            tileTextAttributes[index].InnerText   = item.CustomerName.ToString();
                            tileTextAttributes[++index].InnerText = item.ContactName.ToString();
                            tileTextAttributes[++index].InnerText = item.StatusDueDate.Day.ToString() + " " + item.StatusDueDate.ToString("MMMM");

                            tileXmlWide.GetElementsByTagName(textElementName)[0].InnerText = item.CustomerName;
                            tileXmlWide.GetElementsByTagName(textElementName)[1].InnerText = item.StatusDueDate.Day.ToString();
                            tileXmlWide.GetElementsByTagName(textElementName)[2].InnerText = item.StatusDueDate.ToString("MMMM");

                            updaterWide.Update(new TileNotification(tileXmlWide));

                            ++index;
                        }
                        if (counter++ > 6)
                        {
                            break;
                        }
                        updaterSqure.Update(new TileNotification(tileXmlSquare));
                    }


                    XmlDocument BadgeXml        = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
                    var         badgeAttributes = BadgeXml.GetElementsByTagName("badge");
                    ((XmlElement)badgeAttributes[0]).SetAttribute("value", allTasks.Count.ToString());

                    updaterBadge.Update(new BadgeNotification(BadgeXml));
                }
            }
            catch (Exception)
            {
            }
        }
        void SendNotifications_Click(object sender, RoutedEventArgs e)
        {
            // Create a notification for the first set of stories with bindings for all 3 tile sizes
            ITileSquare310x310Text09 square310x310TileContent1 = TileContentFactory.CreateTileSquare310x310Text09();

            square310x310TileContent1.TextHeadingWrap.Text = "Main Story";

            ITileWide310x150Text03 wide310x150TileContent1 = TileContentFactory.CreateTileWide310x150Text03();

            wide310x150TileContent1.TextHeadingWrap.Text = "Main Story";

            ITileSquare150x150Text04 square150x150TileContent1 = TileContentFactory.CreateTileSquare150x150Text04();

            square150x150TileContent1.TextBodyWrap.Text = "Main Story";

            wide310x150TileContent1.Square150x150Content = square150x150TileContent1;
            square310x310TileContent1.Wide310x150Content = wide310x150TileContent1;

            // Set the contentId on the Square310x310 tile
            square310x310TileContent1.ContentId = "Main_1";

            // Tag the notification and send it to the tile
            TileNotification tileNotification = square310x310TileContent1.CreateNotification();

            tileNotification.Tag = "1";
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            // Create the first notification for the second set of stories with binding for all 3 tiles sizes
            ITileSquare310x310TextList03 square310x310TileContent2 = TileContentFactory.CreateTileSquare310x310TextList03();

            square310x310TileContent2.TextHeading1.Text = "Additional Story 1";
            square310x310TileContent2.TextHeading2.Text = "Additional Story 2";
            square310x310TileContent2.TextHeading3.Text = "Additional Story 3";

            ITileWide310x150Text03 wide310x150TileContent2 = TileContentFactory.CreateTileWide310x150Text03();

            wide310x150TileContent2.TextHeadingWrap.Text = "Additional Story 1";

            ITileSquare150x150Text04 square150x150TileContent2 = TileContentFactory.CreateTileSquare150x150Text04();

            square150x150TileContent2.TextBodyWrap.Text = "Additional Story 1";

            wide310x150TileContent2.Square150x150Content = square150x150TileContent2;
            square310x310TileContent2.Wide310x150Content = wide310x150TileContent2;

            // Set the contentId on the Square310x310 tile
            square310x310TileContent2.ContentId = "Additional_1";

            // Tag the notification and send it to the tile
            tileNotification     = square310x310TileContent2.CreateNotification();
            tileNotification.Tag = "2";
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            // Create the second notification for the second set of stories with binding for all 3 tiles sizes
            // Notice that we only replace the Wide310x150 and Square150x150 binding elements,
            // and keep the Square310x310 content the same - this will cause the Square310x310 to be ignored for this notification,
            // since the contentId for this size is the same as in the first notification of the second set of stories.
            ITileWide310x150Text03 wide310x150TileContent3 = TileContentFactory.CreateTileWide310x150Text03();

            wide310x150TileContent3.TextHeadingWrap.Text = "Additional Story 2";

            ITileSquare150x150Text04 square150x150TileContent3 = TileContentFactory.CreateTileSquare150x150Text04();

            square150x150TileContent3.TextBodyWrap.Text = "Additional Story 2";

            wide310x150TileContent3.Square150x150Content = square150x150TileContent3;
            square310x310TileContent2.Wide310x150Content = wide310x150TileContent3;

            // Tag the notification and send it to the tile
            tileNotification     = square310x310TileContent2.CreateNotification();
            tileNotification.Tag = "3";
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            // Create the third notification for the second set of stories with binding for all 3 tiles sizes
            // Notice that we only replace the Wide310x150 and Square150x150 binding elements,
            // and keep the Square310x310 content the same again - this will cause the Square310x310 to be ignored for this notification,
            // since the contentId for this size is the same as in the first notification of the second set of stories.
            ITileWide310x150Text03 wide310x150TileContent4 = TileContentFactory.CreateTileWide310x150Text03();

            wide310x150TileContent4.TextHeadingWrap.Text = "Additional Story 3";

            ITileSquare150x150Text04 square150x150TileContent4 = TileContentFactory.CreateTileSquare150x150Text04();

            square150x150TileContent4.TextBodyWrap.Text = "Additional Story 3";

            wide310x150TileContent4.Square150x150Content = square150x150TileContent4;
            square310x310TileContent2.Wide310x150Content = wide310x150TileContent4;

            // Tag the notification and send it to the tile
            tileNotification     = square310x310TileContent2.CreateNotification();
            tileNotification.Tag = "4";
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            OutputTextBlock.Text = "Four notifications sent";
        }
        private void tileButton_Click(object sender, RoutedEventArgs e)
        {
            TileNotification notification = new TileNotification(content.GetXml());

            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
        }
예제 #23
0
 /// <summary>
 /// 删除磁贴
 /// </summary>
 public void DeleteTile() => TileUpdateManager.CreateTileUpdaterForApplication().Clear();
        public static void CreateTiles(List <Article> articles)
        {
            string imageUrl1 = "";
            string imageUrl2 = "";

            for (int i = 0; i < articles.Count; i++)
            {
                if (articles[i].Image != "")
                {
                    imageUrl1 = articles[i].Image;
                    break;
                }
            }

            for (int i = 0; i < articles.Count; i++)
            {
                if (articles[i].Image != "" && articles[i].Image != imageUrl1)
                {
                    imageUrl2 = articles[i].Image;
                    break;
                }
            }

            TileBindingContentAdaptive bindingContent = new TileBindingContentAdaptive()
            {
                BackgroundImage = new TileBackgroundImage()
                {
                    Source  = new TileImageSource(imageUrl1),
                    Overlay = 60
                },

                PeekImage = new TilePeekImage()
                {
                    Source = new TileImageSource(imageUrl2)
                },

                Children =
                {
                    CreateGroup(
                        from: articles[0].Title.Substring(0,         30),
                        body: articles[0].Content.Substring(0,      60)),

                    new TileText(),

                    CreateGroup(
                        from: articles[1].Title.Substring(0,         30),
                        body: articles[1].Content.Substring(0,      60)),

                    new TileText(),

                    CreateGroup(
                        from: articles[2].Title.Substring(0,         30),
                        body: articles[2].Content.Substring(0,      60)),

                    new TileText(),

                    CreateGroup(
                        from: articles[3].Title.Substring(0,         30),
                        body: articles[3].Content.Substring(0, 60))
                }
            };

            TileBinding binding = new TileBinding()
            {
                Branding = TileBranding.NameAndLogo,
                Content  = bindingContent
            };

            TileContent content = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileMedium = binding,
                    TileWide   = binding,
                    TileLarge  = binding
                }
            };

            TileNotification notification = new TileNotification(content.GetXml());

            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
        }
예제 #25
0
        /// <summary>
        /// Creates or updates one or multiple live tiles on the executing platform. How it is manifests itself is determined by the class that
        /// implements this interface. If the platform does not support this feature, then the implementation should do nothing.
        /// </summary>
        /// <param name="model">Model which contains the data necessary to create a new tile or to find the tile to update</param>
        public override async Task <bool> CreateOrUpdateTileAsync(IModel model)
        {
            if (model == null)
            {
                return(false);
            }

            // Do custom tile creation based on the type of the model passed into this method.
            if (model is MainViewModel || model is ModelList <ItemModel> )
            {
                var list = (model as MainViewModel)?.Items ?? model as ModelList <ItemModel>;

                // Get the blank badge XML payload for a badge number
                XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);

                // Set the value of the badge in the XML to our number
                XmlElement badgeElement = badgeXml.SelectSingleNode("/badge") as XmlElement;
                badgeElement.SetAttribute("value", list?.Count.ToString());

                // Create the badge notification
                BadgeNotification badge = new BadgeNotification(badgeXml);

                // Create the badge updater for the application
                BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();

                // And update the badge
                badgeUpdater.Update(badge);
            }
            else if (model is ItemModel)
            {
                var item = model as ItemModel;

                var tile = new SecondaryTile();
                tile.TileId      = Platform.Current.GenerateModelTileID(item);
                tile.Arguments   = Platform.Current.GenerateModelArguments(model);
                tile.DisplayName = item.LineOne;
                var status = await this.CreateOrUpdateSecondaryTileAsync(tile, new TileVisualOptions());

                if (status)
                {
                    #region Create ItemModel TileContent

                    // Construct the tile content
                    TileContent content = new TileContent()
                    {
                        Visual = new TileVisual()
                        {
                            TileMedium = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        new TileText()
                                        {
                                            Text = item.LineOne
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineTwo, Style = TileTextStyle.CaptionSubtle
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineThree, Style = TileTextStyle.CaptionSubtle
                                        }
                                    }
                                }
                            },

                            TileWide = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        new TileText()
                                        {
                                            Text = item.LineOne, Style = TileTextStyle.Subtitle
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineTwo, Style = TileTextStyle.CaptionSubtle
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineThree, Style = TileTextStyle.CaptionSubtle
                                        }
                                    }
                                }
                            },

                            TileLarge = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        new TileText()
                                        {
                                            Text = item.LineOne, Style = TileTextStyle.Subtitle
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineTwo, Style = TileTextStyle.CaptionSubtle
                                        },
                                        new TileText()
                                        {
                                            Text = item.LineThree, Style = TileTextStyle.CaptionSubtle
                                        }
                                    }
                                }
                            }
                        }
                    };

                    #endregion

                    var notification = new TileNotification(content.GetXml());
                    notification.ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(10);
                    TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notification);
                }

                return(status);
            }

            return(false);
        }
예제 #26
0
 private void CleanTile_Click(object sender, RoutedEventArgs e)
 {
     TileUpdateManager.CreateTileUpdaterForApplication().StopPeriodicUpdate();
     TileUpdateManager.CreateTileUpdaterForApplication().Clear();
 }
        public void ModifyTile(string from, string subject, string body)
        {
            TileUpdateManager.CreateTileUpdaterForApplication().Clear();

            TileContent content = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileMedium = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text = from
                                },

                                new TileText()
                                {
                                    Text  = subject,
                                    Style = TileTextStyle.CaptionSubtle
                                },

                                new TileText()
                                {
                                    Text  = body,
                                    Style = TileTextStyle.CaptionSubtle
                                }
                            }
                        }
                    },

                    TileWide = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text  = from,
                                    Style = TileTextStyle.Subtitle
                                },

                                new TileText()
                                {
                                    Text  = subject,
                                    Style = TileTextStyle.CaptionSubtle
                                },

                                new TileText()
                                {
                                    Text  = body,
                                    Style = TileTextStyle.CaptionSubtle
                                }
                            }
                        }
                    },

                    TileLarge = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new TileText()
                                {
                                    Text  = from,
                                    Style = TileTextStyle.Subtitle
                                },

                                new TileText()
                                {
                                    Text  = subject,
                                    Style = TileTextStyle.CaptionSubtle
                                },

                                new TileText()
                                {
                                    Text  = body,
                                    Style = TileTextStyle.CaptionSubtle
                                }
                            }
                        }
                    }
                }
            };

            var notification = new TileNotification(content.GetXml());

            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
        }
        static public void updateTile(string jSonResponse)
        {

            try
            {
                string bg = "";
                string direction = "-";
                string battery = "";

                JObject response = JObject.Parse(jSonResponse);
                string timeframe = JsonConvert.DeserializeObject(response["bgs"][0]["datetime"].ToString()).ToString();

                bg = response["bgs"][0]["sgv"].ToString();
                battery = response["bgs"][0]["battery"].ToString();


                switch (response["bgs"][0]["direction"].ToString().ToLower())
                {
                    case "singleup":
                        direction = '\x25B2'.ToString();
                        break;
                    case "doubleup":
                        direction = string.Concat('\x25B2', '\x25B2');
                        break;
                    case "fortyfiveup":
                        direction = '\x25B3'.ToString();
                        break;
                    case "singledown":
                        direction = '\x25BC'.ToString();
                        break;
                    case "doubledown":
                        direction = string.Concat('\x25BC', '\x25BC');
                        break;
                    case "fortyfivedown":
                        direction = '\x25BD'.ToString();
                        break;
                    case "NOT COMPUTABLE": break;
                }


                string notification = String.Format("Current bg: {0} \r\nTrend: {1} \r\nBattery: {2}% ", bg, direction.ToString(), battery);

                XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text01);
                XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
                tileTextAttributes[0].InnerText = notification;

                XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text04);
                XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
                squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(notification));
                IXmlNode node = tileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
                tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

                TileNotification tileNotification = new TileNotification(tileXml);

                tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(100);

                TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

                XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeGlyph);
                XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
                badgeElement.SetAttribute("value", String.Format("Current bg: {0} \r\nTrend: {1}", bg, direction.ToString()));

                BadgeNotification badge = new BadgeNotification(badgeXml);
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);

                //int reading = System.Int32.Parse(bg);

                //if ((reading > 200) || (reading < 80))
                //{
                //    ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText01;
                //    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
                //    XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                //    toastTextElements[0].AppendChild(toastXml.CreateTextNode(String.Format("Current bg: {0} Trend: {1}", bg, direction.ToString())));

                //    IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                //    ((XmlElement)toastNode).SetAttribute("duration", "long");
                //    XmlElement audio = toastXml.CreateElement("audio");
                //    toastNode.AppendChild(audio);

                //    ToastNotification toast = new ToastNotification(toastXml);
                //    ToastNotificationManager.CreateToastNotifier().Show(toast);
                //}
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }


        }
 public void UpdateTile(TileNotification notification)
 {
     TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
 }
예제 #30
0
        public static async void UpdateTile(List <ClassList> tempList1, List <Transaction> tempList2, int nowWeek, string weekDay)
        {
            //为应用创建磁贴更新
            var updater = TileUpdateManager.CreateTileUpdaterForApplication();

            //这里设置的是所以磁贴都可以为动态
            updater.EnableNotificationQueue(true);
            updater.Clear();
            int        itemCount    = 0;
            List <int> correctCount = new List <int>(0);

            #region 创建动态磁贴XML文档

            //1:创建动态磁贴模板
            string tileXml = "<tile>" +
                             "<visual>" +
                             //中磁贴
                             "<binding template=\"TileMedium\">" +
                             "<text hint-wrap=\"true\"></text>" +
                             "<text></text>" +
                             "<text hint-wrap=\"true\"></text>" +
                             "</binding>" +
                             //宽磁贴
                             "<binding template=\"TileWide\">" +
                             "<text hint-style=\"subtitle\"></text>" +
                             "<text></text>" +
                             "<text hint-wrap=\"true\"></text>" +
                             "</binding>" +
                             //大磁贴
                             "<binding template=\"TileLarge\">" +
                             "<text></text>" +
                             "<group>" +
                             "<subgroup>" +
                             "<text hint-wrap=\"true\" hint-style=\"subtitle\"></text>" +
                             "<text></text>" +
                             "<text hint-wrap=\"true\"></text>" +
                             "</subgroup>" +
                             "</group>" +
                             "<text>" + "\n" + "</text>" +
                             "<group>" +
                             "<subgroup>" +
                             "<text hint-wrap=\"true\" hint-style=\"subtitle\"></text>" +
                             "<text></text>" +
                             "<text hint-wrap=\"true\"></text>" +
                             "</subgroup>" +
                             "</group>" +
                             "</binding>" +
                             "</visual>" +
                             "</tile>";

            #endregion 创建动态磁贴XML文档

            for (int i = 0; i < tempList1.Count; i++)
            {
                int[] weeks = tempList1[i].Week;
                //判断课程是否为本周课程
                for (int j = 0; j < weeks.Length; j++)
                {
                    if (weeks[j] == nowWeek && tempList1[i].Day.Equals(weekDay))
                    {
                        //满足条件的课程编号存入correctCount
                        correctCount.Add(i);
                        //微软规定动态磁贴的队列数目小于5个
                        if (itemCount++ > 5)
                        {
                            break;
                        }
                    }
                }
            }
            //为XML对象赋值并推送更新
            for (int i = 0; i < correctCount.Count; i++)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(tileXml);
                XmlNodeList elements = doc.GetElementsByTagName("text");
                //中磁贴
                elements[0].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Course));
                elements[1].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Teacher));
                elements[2].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Lesson));
                elements[2].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Classroom));
                //宽磁贴
                elements[3].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Course));
                elements[4].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Teacher));
                elements[5].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Lesson));
                elements[5].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Classroom));
                //大磁贴
                elements[7].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Course));
                elements[8].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Teacher));
                elements[9].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Lesson));
                elements[9].AppendChild(doc.CreateTextNode(tempList1[correctCount[i]].Classroom));
                try
                {
                    elements[11].AppendChild(doc.CreateTextNode("提醒:" + tempList2[i].Title));
                    elements[12].AppendChild(doc.CreateTextNode(tempList2[i].Content));
                    for (int j = 0; j < tempList2[i].Date[0].Week.Length; j++)
                    {
                        elements[13].AppendChild(doc.CreateTextNode("第" + tempList2[i].Date[0].Week[j].ToString() + "周" + " "));
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    Debug.WriteLine("事项数组越界");
                    elements[11].AppendChild(doc.CreateTextNode("暂无待办事项"));
                    elements[12].AppendChild(doc.CreateTextNode("记得好好复习哟~"));
                }
                finally
                {
                    updater.Update(new TileNotification(doc));
                }
            }
        }