private void Initialize()
        {
            // Clear all existing notifications
            ToastNotificationManager.History.Clear();

            var longTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime = DateTime.Now.AddSeconds(30);
            string expiryTimeString = longTime.Format(expiryTime);

            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            //Find the text component of the content
            XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");

            // Set the text on the toast. 
            // The first line of text in the ToastText02 template is treated as header text, and will be bold.
            toastTextElements[0].AppendChild(toastXml.CreateTextNode("Expiring Toast"));
            toastTextElements[1].AppendChild(toastXml.CreateTextNode("It will expire at " +  expiryTimeString));

            // Set the duration on the toast
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
            ((XmlElement)toastNode).SetAttribute("duration", "long");

            // Create the actual toast object using this toast specification.
            ToastNotification toast = new ToastNotification(toastXml);

            toast.ExpirationTime = expiryTime;

            // Send the toast.
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
Example #2
0
        private void PopToast(string text)
        {
            // create and send local notificatio  with new app version
            var xmlString = string.Format(@"
                            <toast>  
                                <visual>
                                    <binding template='ToastGeneric'>                                        
                                        <text>BG task result: {0}</text>
                                    </binding>      
                                </visual>
                            </toast>",
                                          text);

            var            longTime         = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime       = DateTime.Now.AddSeconds(8);
            string         expiryTimeString = longTime.Format(expiryTime);

            XmlDocument toastXml = new XmlDocument();

            toastXml.LoadXml(xmlString);

            // Set the duration on the toast
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", "long");

            // Create the actual toast object using this toast specification.
            ToastNotification toast = new ToastNotification(toastXml);

            toast.ExpirationTime = expiryTime;

            // Send the toast
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        // CurrentAppSimulator は "WindowsStoreProxy.xml" という XML ファイルからテスト専用のライセンス情報を取得します
        // 
        // WindowsStoreProxy.xml のありか
        //  C:\Users\<ユーザー名>\AppData\Local\Packages\<パッケージファミリ名>\LocalState\Microsoft\Windows Store\ApiData
        // アプリケーションのパッケージファミリ名は Package.appxmanifest の 「パッケージ化|パッケージファミリ名」にあります
        private async void ReloadLicense()
        {
            await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                // ライセンスがアクティブである
                if ( CurrentAppSimulator.LicenseInformation.IsActive ) {
                    // 試用版
                    if ( CurrentAppSimulator.LicenseInformation.IsTrial ) {
                        textLicense.Text = "試用版";

                        var longDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter( "longdate" );

                        // 残りの試用期間
                        var daysRemaining = (CurrentAppSimulator.LicenseInformation.ExpirationDate - DateTime.Now).Days;

                        // Let the user know the number of days remaining before the feature expires
                        textRemainDays.Text = daysRemaining.ToString();
                    }
                    // 通常版
                    else {
                        textLicense.Text = "購入版";
                    }

                    textAddContentsLicense.Text = CurrentAppSimulator.LicenseInformation.ProductLicenses["AddContents"].IsActive ? "有効" : "無効";
                }
                // ライセンスがアクティブではない(何かしら不正な状況)
                else {
                }
            } );
        }
Example #4
0
        private async void WriteAppdata_Click(object sender, RoutedEventArgs e)
        {
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            StorageFile sampleFile = await localFolder.CreateFileAsync(dataFileName, CreationCollisionOption.OpenIfExists);

            await FileIO.AppendLinesAsync(sampleFile, new string[] { formatter.Format(DateTime.Now) });
        }
 private void ExpiringProductRefreshScenario()
 {
     LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
     if (licenseInformation.IsActive)
     {
         if (licenseInformation.IsTrial)
         {
             rootPage.NotifyUser("You don't have full license", NotifyType.ErrorMessage);
         }
         else
         {
             var productLicense1 = licenseInformation.ProductLicenses["product1"];
             if (productLicense1.IsActive)
             {
                 var longdateTemplate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                 Product1Message.Text = "Product 1 expires on: " + longdateTemplate.Format(productLicense1.ExpirationDate);
                 var remainingDays = (productLicense1.ExpirationDate - DateTime.Now).Days;
                 rootPage.NotifyUser("Product 1 expires in: " + remainingDays + " days.", NotifyType.StatusMessage);
             }
             else
             {
                 rootPage.NotifyUser("Product 1 is not available.", NotifyType.ErrorMessage);
             }
         }
     }
     else
     {
         rootPage.NotifyUser("You don't have active license.", NotifyType.ErrorMessage);
     }
 }
Example #6
0
        string getTimeStampedMessage(string eventText)
        {
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter dateTimeFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            string dateTime = dateTimeFormat.Format(DateTime.Now);

            return(eventText + "   " + dateTime);
        }
Example #7
0
        /// <summary>
        /// Richiamato quando la pagina sta per essere visualizzata in un Frame.
        /// </summary>
        /// <param name="e">Dati dell'evento in cui vengono descritte le modalità con cui la pagina è stata raggiunta. La proprietà
        /// Parameter viene in genere utilizzata per configurare la pagina.</param>

        void initializeLicense()
        {
            // Initialize the license info for use in the app that is uploaded to the Store.
            // uncomment for release
            licenseInformation = CurrentApp.LicenseInformation;

            // Initialize the license info for testing.
            // comment the next line for release
            //licenseInformation = CurrentAppSimulator.LicenseInformation;

            // Register for the license state change event.
            licenseInformation.LicenseChanged += new LicenseChangedEventHandler(licenseChangedEventHandler);

            if (licenseInformation.IsActive)
            {
                if (licenseInformation.IsTrial)
                {
                    var longDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                    var daysRemaining  = (licenseInformation.ExpirationDate - DateTime.Now).Days;

                    MessageDialog msgDialog = new MessageDialog("Grazie per aver acquistato la versione di prova della tastiera fonetica! \n\r La versione trial dura " + "quantigiornidura.toString()" + " .", "Versione di prova");
                    //msgDialog.ShowAsync();
                }
            }
        }
Example #8
0
        // Method to update the Live Tile with the latest Score information
        private void UpdateLiveTile()
        {
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter _formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            string _timePlayed = _formatter.Format(DateTime.Now).ToString();

            // Get tile template - small tile
            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText04);

            // Set tile info
            XmlNodeList tileText = tileXml.GetElementsByTagName("text");

            tileText[0].InnerText = "Last Played: " + _timePlayed;

            // Wide tile
            XmlDocument wideTileXml  = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideImageAndText02);
            XmlNodeList wideTileText = wideTileXml.GetElementsByTagName("text");

            wideTileText[0].InnerText = "Last Played: " + _timePlayed;
            wideTileText[1].InnerText = "Highest Score: " + m_highScores[0].ToString();

            // Add the wide tile to the square tiles payload by retrieving the binding element
            IXmlNode node = tileXml.ImportNode(wideTileXml.GetElementsByTagName("binding").Item(0), true);

            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            // Apply the tile
            TileNotification tileNotification = new TileNotification(tileXml);

            // Update the app tile
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
        }
Example #9
0
        //</ReloadLicense>

        //<DisplayTrialVersionExpirationTime>
        void DisplayTrialVersionExpirationTime()
        {
            if (licenseInformation.IsActive)
            {
                if (licenseInformation.IsTrial)
                {
                    var longDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");

                    // Display the expiration date using the DateTimeFormatter.
                    // For example, longDateFormat.Format(licenseInformation.ExpirationDate)

                    var daysRemaining = (licenseInformation.ExpirationDate - DateTime.Now).Days;

                    // Let the user know the number of days remaining before the feature expires
                }
                else
                {
                    // ...
                }
            }
            else
            {
                // ...
            }
        }
Example #10
0
        /// <summary>
        /// This is the handler for the DateChanged event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void datePicker_DateChanged(object sender, DatePickerValueChangedEventArgs e)
        {
            // The DateTimeFormatter class formats dates and times with the user's default settings
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter dateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");

            // rootPage.NotifyUser("Date changed to " + dateFormatter.Format(e.NewDate), NotifyType.StatusMessage);
        }
        private void ExpiringProductRefreshScenario()
        {
            LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;

            if (licenseInformation.IsActive)
            {
                if (licenseInformation.IsTrial)
                {
                    rootPage.NotifyUser("You don't have full license", NotifyType.ErrorMessage);
                }
                else
                {
                    var productLicense1 = licenseInformation.ProductLicenses["product1"];
                    if (productLicense1.IsActive)
                    {
                        var longdateTemplate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                        Product1Message.Text = "Product 1 expires on: " + longdateTemplate.Format(productLicense1.ExpirationDate);
                        var remainingDays = (productLicense1.ExpirationDate - DateTime.Now).Days;
                        rootPage.NotifyUser("Product 1 expires in: " + remainingDays + " days.", NotifyType.StatusMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("Product 1 is not available.", NotifyType.ErrorMessage);
                    }
                }
            }
            else
            {
                rootPage.NotifyUser("You don't have active license.", NotifyType.ErrorMessage);
            }
        }
        void UpdateTileExpiring_Click(object sender, RoutedEventArgs e)
        {
            int seconds;

            if (!Int32.TryParse(Time.Text, out seconds))
            {
                seconds = 10;
            }

            Windows.Globalization.Calendar cal = new Windows.Globalization.Calendar();
            cal.SetToNow();
            cal.AddSeconds(seconds);

            var            longTime         = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime       = cal.GetDateTime();
            string         expiryTimeString = longTime.Format(expiryTime);

            ITileWideText04 tileContent = TileContentFactory.CreateTileWideText04();

            tileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;

            ITileSquareText04 squareTileContent = TileContentFactory.CreateTileSquareText04();

            squareTileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;
            tileContent.SquareContent           = squareTileContent;

            TileNotification tileNotification = tileContent.CreateNotification();

            // set the expirationTime
            tileNotification.ExpirationTime = expiryTime;
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            OutputTextBlock.Text = "Tile notification sent. It will expire at " + expiryTimeString;
        }
 private void ExpiringProductRefreshScenario()
 {
     var task = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
         if (licenseInformation.IsActive)
         {
             if (licenseInformation.IsTrial)
             {
                 rootPage.NotifyUser("You don't have a full license to this app.", NotifyType.ErrorMessage);
             }
             else
             {
                 var productLicense1 = licenseInformation.ProductLicenses["product1"];
                 if (productLicense1.IsActive)
                 {
                     var longdateTemplate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                     Product1Message.Text = "Product 1 expires on " + longdateTemplate.Format(productLicense1.ExpirationDate) + ". Days remaining: " + (productLicense1.ExpirationDate - DateTime.Now).Days;
                 }
                 else
                 {
                     rootPage.NotifyUser("Product 1 is not available.", NotifyType.ErrorMessage);
                 }
             }
         }
         else
         {
             rootPage.NotifyUser("You don't have active license.", NotifyType.ErrorMessage);
         }
     });
 }
Example #14
0
 private void ExpiringProductRefreshScenario()
 {
     var task = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
         if (licenseInformation.IsActive)
         {
             if (licenseInformation.IsTrial)
             {
                 rootPage.NotifyUser("You don't have a full license to this app.", NotifyType.ErrorMessage);
             }
             else
             {
                 var productLicense1 = licenseInformation.ProductLicenses["product1"];
                 if (productLicense1.IsActive)
                 {
                     var longdateTemplate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                     Product1Message.Text = "Product 1 expires on " + longdateTemplate.Format(productLicense1.ExpirationDate) + ". Days remaining: " + (productLicense1.ExpirationDate - DateTime.Now).Days;
                 }
                 else
                 {
                     rootPage.NotifyUser("Product 1 is not available.", NotifyType.ErrorMessage);
                 }
             }
         }
         else
         {
             rootPage.NotifyUser("You don't have active license.", NotifyType.ErrorMessage);
         }
     });
 }
        // CurrentAppSimulator は "WindowsStoreProxy.xml" という XML ファイルからテスト専用のライセンス情報を取得します
        //
        // WindowsStoreProxy.xml のありか
        //  C:\Users\<ユーザー名>\AppData\Local\Packages\<パッケージファミリ名>\LocalState\Microsoft\Windows Store\ApiData
        // アプリケーションのパッケージファミリ名は Package.appxmanifest の 「パッケージ化|パッケージファミリ名」にあります
        private async void ReloadLicense()
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                // ライセンスがアクティブである
                if (CurrentAppSimulator.LicenseInformation.IsActive)
                {
                    // 試用版
                    if (CurrentAppSimulator.LicenseInformation.IsTrial)
                    {
                        textLicense.Text = "試用版";

                        var longDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");

                        // 残りの試用期間
                        var daysRemaining = (CurrentAppSimulator.LicenseInformation.ExpirationDate - DateTime.Now).Days;

                        // Let the user know the number of days remaining before the feature expires
                        textRemainDays.Text = daysRemaining.ToString();
                    }
                    // 通常版
                    else
                    {
                        textLicense.Text = "購入版";
                    }

                    textAddContentsLicense.Text = CurrentAppSimulator.LicenseInformation.ProductLicenses["AddContents"].IsActive ? "有効" : "無効";
                }
                // ライセンスがアクティブではない(何かしら不正な状況)
                else
                {
                }
            });
        }
Example #16
0
        private void Initialize()
        {
            // Clear all existing notifications
            ToastNotificationManager.History.Clear();

            var            longTime         = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime       = DateTime.Now.AddSeconds(30);
            string         expiryTimeString = longTime.Format(expiryTime);

            XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            //Find the text component of the content
            XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");

            // Set the text on the toast.
            // The first line of text in the ToastText02 template is treated as header text, and will be bold.
            toastTextElements[0].AppendChild(toastXml.CreateTextNode("Expiring Toast"));
            toastTextElements[1].AppendChild(toastXml.CreateTextNode("It will expire at " + expiryTimeString));

            // Set the duration on the toast
            IXmlNode toastNode = toastXml.SelectSingleNode("/toast");

            ((XmlElement)toastNode).SetAttribute("duration", "long");

            // Create the actual toast object using this toast specification.
            ToastNotification toast = new ToastNotification(toastXml);

            toast.ExpirationTime = expiryTime;

            // Send the toast.
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
Example #17
0
        public void setTime()
        {
            var      formatter    = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("month day dayofweek year hour minute second");
            DateTime dateToFormat = DateTime.Now;
            var      mydate       = formatter.Format(dateToFormat);

            textBlock1.Text = mydate.ToString();
        }
Example #18
0
        private async void WriteTimestamp()
        {
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter =
                new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

            StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.OpenIfExists);

            await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTimeOffset.Now));
        }
Example #19
0
        /// <summary>
        /// Create a file in temporary data if not exist and write the content (replace content if not null)
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="content"></param>
        public async void Write(string FileName, string content)
        {
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter =
                new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

            StorageFile sampleFile = await temporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(sampleFile, content);
        }
        async void WriteTimestamp()
        {
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

            StorageFile sampleFile = await localFolder.CreateFileAsync("favoris.txt", CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
        }
 public MainPage()
 {
     this.InitializeComponent();
     //Get Date time in the format we need
     var dateTimeFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("month day dayofweek year");
     dateLbl.Text = dateTimeFormatter.Format(DateTime.Now);
     //Get currency, get the current user one
     var userCurrency = Windows.System.UserProfile.GlobalizationPreferences.Currencies;
     var currencyFormatter = new Windows.Globalization.NumberFormatting.CurrencyFormatter(userCurrency[0]);
     currencyLbl.Text=currencyFormatter.Format(10.57);
 }
Example #22
0
        public static string GetDateTime()
        {
            var shortDateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
            var shortTimeFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");

            var dateTimeToFormat = DateTime.Now;

            var shortDate = shortDateFormatter.Format(dateTimeToFormat);
            var shortTime = shortTimeFormatter.Format(dateTimeToFormat);

            return(shortDate + " " + shortTime);
        }
Example #23
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Windows.Storage.StorageFolder            localFolder   = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter =
                new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

            StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt",
                                                                       CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
        }
        private async void Button_Click_10(object sender, RoutedEventArgs e)
        {
            var      dtf = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("dayofweek day month year");
            DateTime now = DateTime.Now;

            tbTime.Text = dtf.Format(now);
            //var rass = RandomAccessStreamReference.CreateFromUri(new Uri(this.baseUri, "/Images/6dc470d7jw1dse92lrac2g.gif"));
            //var rass = RandomAccessStreamReference.CreateFromUri(new Uri(this.baseUri, "Images/amy.jpg"));
            var rass         = RandomAccessStreamReference.CreateFromUri(new Uri(this.baseUri, "/Images/ceshi123.gif"));
            var streamRandom = await rass.OpenReadAsync();

            await imageGif.SetSourceAsync(streamRandom);
        }
        private void Draw(object sender, object e)
        {
            //var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            //DateTime dateToFormat = DateTime.Now;
            //TimeTxt.Text = formatter.Format(dateToFormat);
            //TimeTxt.Text = DateTime.Now.ToString("HH:mm:ss");

            //DateTime myTime = DateTime.Now;
            //TimeTxt.Text = myTime.ToLongTimeString();//ToString("t");

            var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}");
            DateTime dateToFormat = DateTime.Now;
            TimeTxt.Text = formatter.Format(dateToFormat);
        }
Example #26
0
        private void Draw(object sender, object e)
        {
            //var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            //DateTime dateToFormat = DateTime.Now;
            //TimeTxt.Text = formatter.Format(dateToFormat);
            //TimeTxt.Text = DateTime.Now.ToString("HH:mm:ss");

            //DateTime myTime = DateTime.Now;
            //TimeTxt.Text = myTime.ToLongTimeString();//ToString("t");

            var      formatter    = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}");
            DateTime dateToFormat = DateTime.Now;

            TimeTxt.Text = formatter.Format(dateToFormat);
        }
        public MainPage()
        {
            this.InitializeComponent();

            // My code
            //IReadOnlyList<string> userLanguages = GlobalizationPreferences.Languages;
            var userLanguages      = GlobalizationPreferences.Languages[0];
            var shortDateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
            var shortTimeFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
            var userCurrency       = GlobalizationPreferences.Currencies[0];
            var userRegion         = GlobalizationPreferences.HomeGeographicRegion;
            var userCalendar       = GlobalizationPreferences.Calendars[0];
            var userWeekStart      = GlobalizationPreferences.WeekStartsOn;
            var userClock          = GlobalizationPreferences.Clocks[0];
            var langDetails        = GlobalizationPreferences.Languages[1];
            var dateTimeToFormat   = DateTime.Now;

            string results = $"Short Date: {shortDateFormatter.Format(dateTimeToFormat)}\n" +
                             $"Short Time: {shortTimeFormatter.Format(dateTimeToFormat)}";

            // Get the user's geographic region and its display name.
            var displayGeo = new GeographicRegion().DisplayName;

            // Loading resources from Resources.resw
            var loader   = new Windows.ApplicationModel.Resources.ResourceLoader();
            var lang     = loader.GetString("chosen_lang");
            var home     = loader.GetString("home_region");
            var calendar = loader.GetString("calendar_setting");
            var clock    = loader.GetString("clock_setting");
            var week     = loader.GetString("week_start");
            var lang_d   = loader.GetString("lang_details");
            var geo      = loader.GetString("geo_details");

            //Globalization Preferences
            chosen_lang.Text      += $"{lang}: {userLanguages}\n";
            home_region.Text      += $"{home}: {userRegion}\n";
            calendar_setting.Text += $"{calendar}: {userCalendar}\n";
            clock_setting.Text    += $"{clock}: {userClock}\n";
            week_start.Text       += $"{week}: {userWeekStart}\n";

            //Language Specifics
            lang_details.Text = $"{lang_d}: {langDetails}\n";

            //Geo Region Specifics
            geo_details.Text = $"{geo}: {displayGeo}\n" +
                               $"User currency: {userCurrency}\n" +
                               results;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            person = e.Parameter as XElement;
            txtPersonInfo.Text = person.Element("Last-Name").Value.ToString() + ", " + person.Element("First-Name").Value.ToString();
            txtCompany.Text = person.Element("Company-Represented").Value.ToString();

            var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
            var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
            DateTime dateToFormat = DateTime.Now;

            var thedate = formatter.Format(dateToFormat);
            var thetime = formatterTime.Format(dateToFormat);

            txtDatetime.Text = thedate + " " + thetime;
        }
        void UpdateTileExpiring_Click(object sender, RoutedEventArgs e)
        {
            int seconds;

            if (!Int32.TryParse(Time.Text, out seconds))
            {
                seconds = 10;
            }

            Windows.Globalization.Calendar cal = new Windows.Globalization.Calendar();
            cal.SetToNow();
            cal.AddSeconds(seconds);

            var            longTime         = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime       = cal.GetDateTime();
            string         expiryTimeString = longTime.Format(expiryTime);

            // Create a notification for the Square310x310 tile using one of the available templates for the size.
            ITileSquare310x310Text09 tileSquare310x310Content = TileContentFactory.CreateTileSquare310x310Text09();

            tileSquare310x310Content.TextHeadingWrap.Text = "This notification will expire at " + expiryTimeString;

            // Create a notification for the Wide310x150 tile using one of the available templates for the size.
            ITileWide310x150Text04 wide310x150TileContent = TileContentFactory.CreateTileWide310x150Text04();

            wide310x150TileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;

            // Create a notification for the Square150x150 tile using one of the available templates for the size.
            ITileSquare150x150Text04 square150x150TileContent = TileContentFactory.CreateTileSquare150x150Text04();

            square150x150TileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;

            // Attach the Square150x150 template to the Wide310x150 template.
            wide310x150TileContent.Square150x150Content = square150x150TileContent;

            // Attach the Wide310x150 template to the Square310x310 template.
            tileSquare310x310Content.Wide310x150Content = wide310x150TileContent;

            TileNotification tileNotification = tileSquare310x310Content.CreateNotification();

            // Set the expiration time and update the tile.
            tileNotification.ExpirationTime = expiryTime;
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            rootPage.NotifyUser("Tile notification sent. It will expire at " + expiryTime, NotifyType.StatusMessage);
        }
 /// <summary>
 /// Converts date to string
 /// </summary>
 /// <param name="value">The source data being passed to the target.</param>
 /// <param name="targetType">The type of the target property, as a type reference </param>
 /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
 /// <param name="language">The language of the conversion.</param>
 /// <returns>The value to be passed to the target dependency property.</returns>
 public object Convert( object value, Type targetType, object parameter, string language )
 {
     string twString = "";
     if( (DateTime)value >= DateTime.Today )
     {
         twString = this._resourceLoader.GetString( "TimeWindow/Today" );
     }
     else if( (DateTime)value >= (DateTime.Today - TimeSpan.FromDays( 1) ) )
     {
         twString = this._resourceLoader.GetString( "TimeWindow/Yesterday" );
     }
     else
     {
         var sdatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter( "shortdate" );
         twString = sdatefmt.Format( (DateTime)value );
     }
     return twString;
 }
Example #31
0
        /// <summary>
        /// Converts date to string
        /// </summary>
        /// <param name="value">The source data being passed to the target.</param>
        /// <param name="targetType">The type of the target property, as a type reference </param>
        /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
        /// <param name="language">The language of the conversion.</param>
        /// <returns>The value to be passed to the target dependency property.</returns>
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string twString = "";

            if ((DateTime)value >= DateTime.Today)
            {
                twString = this._resourceLoader.GetString("TimeWindow/Today");
            }
            else if ((DateTime)value >= (DateTime.Today - TimeSpan.FromDays(1)))
            {
                twString = this._resourceLoader.GetString("TimeWindow/Yesterday");
            }
            else
            {
                var sdatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                twString = sdatefmt.Format((DateTime)value);
            }
            return(twString);
        }
        async void txtName_KeyUp(object sender, KeyRoutedEventArgs e)
        {

            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("logdata.xml");

            lvItems.Items.Clear();

            //   Debug.WriteLine("Attempting to read file  " + file.Path + " into xdocument");
            XDocument doc = XDocument.Load(file.Path);
            var ps = (
                from actions in doc.Root.Elements("Action").Elements("Person")
                select actions
            );
            if(txtName.Text.Count() > 0 ) {
                    IEnumerable<XElement> persons = (
                        from actions in doc.Root.Elements("Action")
                        where (string)actions.Attribute("type") == "Scheduled Visit"
                        from person in actions.Elements("Person")
                        where (person.Element("First-Name").Value.ToUpper().Contains(txtName.Text.ToUpper()) || person.Element("Last-Name").Value.ToUpper().Contains(txtName.Text.ToUpper()))

                        from dates in person.Elements("Date")
                        orderby DateTime.Parse(person.Element("Time-In").Value) ascending
                         where Convert.ToDateTime(dates.Value).Date == DateTime.Now.Date
                        select person
                    );

                    foreach (XElement signin in persons)
                    {
                        ScheduledVisitTile tile = new ScheduledVisitTile();
                        tile.person = signin;
                        tile.txtName.Text = signin.Element("Last-Name").Value.ToString() + ", " + signin.Element("First-Name").Value.ToString();
                        tile.txtCompany.Text = signin.Element("Company-Represented").Value.ToString();
                        var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                        var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                        DateTime dateToFormat = Convert.ToDateTime(signin.Element("Time-In").Value.ToString());
                        var thedate = formatter.Format(dateToFormat);
                        var thetime = formatterTime.Format(dateToFormat);
                        tile.txtDate.Text = thedate + " " + thetime;
                        lvItems.Items.Add(tile);
                    }
                }

        }
Example #33
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var loader = ResourceLoader.GetForCurrentView();

            DynamicText.Text = loader.GetString("Dynamic");

            var currencyText      = loader.GetString("Dollars");
            var currencyFormatter =
                new CurrencyFormatter(Windows.System.UserProfile.GlobalizationPreferences.Currencies[0]);

            Currency.Text = string.Format(currencyText, currencyFormatter.Format(CurrencyValue));

            var dateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
            var timeFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");

            Date.Text = dateFormatter.Format(DateTime.Now);
            Time.Text = timeFormatter.Format(DateTime.Now);
        }
        async void WriteTimestamp()
        {
            Debug.WriteLine("\nTrying!!");

            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            Debug.WriteLine("Local Folder: " + localFolder.ToString());

            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            Debug.WriteLine("Created DateTime: " + formatter.Format(DateTimeOffset.Now));

            StorageFile configFile = await localFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.ReplaceExisting);

            Debug.WriteLine("Created Sample file: " + configFile.ToString());

            await FileIO.WriteTextAsync(configFile, formatter.Format(DateTimeOffset.Now));

            Debug.WriteLine("Finished Writing the timestamp!\n");
        }
        void UpdateTileExpiring_Click(object sender, RoutedEventArgs e)
        {
            int seconds;
            if (!Int32.TryParse(Time.Text, out seconds))
            {
                seconds = 10;
            }

            Windows.Globalization.Calendar cal = new Windows.Globalization.Calendar();
            cal.SetToNow();
            cal.AddSeconds(seconds);

            var longTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            DateTimeOffset expiryTime = cal.GetDateTime();
            string expiryTimeString = longTime.Format(expiryTime);

            // Create a notification for the Square310x310 tile using one of the available templates for the size.
            ITileSquare310x310Text09 tileSquare310x310Content = TileContentFactory.CreateTileSquare310x310Text09();
            tileSquare310x310Content.TextHeadingWrap.Text = "This notification will expire at " + expiryTimeString;

            // Create a notification for the Wide310x150 tile using one of the available templates for the size.
            ITileWide310x150Text04 wide310x150TileContent = TileContentFactory.CreateTileWide310x150Text04();
            wide310x150TileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;

            // Create a notification for the Square150x150 tile using one of the available templates for the size.
            ITileSquare150x150Text04 square150x150TileContent = TileContentFactory.CreateTileSquare150x150Text04();
            square150x150TileContent.TextBodyWrap.Text = "This notification will expire at " + expiryTimeString;

            // Attach the Square150x150 template to the Wide310x150 template.
            wide310x150TileContent.Square150x150Content = square150x150TileContent;

            // Attach the Wide310x150 template to the Square310x310 template.
            tileSquare310x310Content.Wide310x150Content = wide310x150TileContent;

            TileNotification tileNotification = tileSquare310x310Content.CreateNotification();

            // Set the expiration time and update the tile.
            tileNotification.ExpirationTime = expiryTime;
            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

            rootPage.NotifyUser("Tile notification sent. It will expire at " + expiryTime, NotifyType.StatusMessage);
        }
Example #36
0
        async private void WriteDataToIsolatedStorage()
        {
            // We have exlusive access to the mutex so can safely wipe the transfer file
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            StorageFolder localFolder  = ApplicationData.Current.LocalFolder;
            StorageFile   transferFile = await localFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);

            using (var stream = await transferFile.OpenStreamForWriteAsync())
            {
                StreamWriter writer = new StreamWriter(stream);

                writer.WriteLine(weatherData.TimeStamp);
                writer.WriteLine(weatherData.Altitude.ToString());
                writer.WriteLine(weatherData.BarometricPressure.ToString());
                writer.WriteLine(weatherData.CelsiusTemperature.ToString());
                writer.WriteLine(weatherData.FahrenheitTemperature.ToString());
                writer.WriteLine(weatherData.Humidity.ToString());
                writer.Flush();
            }
        }
Example #37
0
        public EventHome()
        {
            db      = new MyDatabase();
            _events = new List <EventModel>();

            string sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();

            Debug.WriteLine(sid);
            InitializeComponent();
            DataContext = App.EventModel;


            FBSession session = FBSession.ActiveSession;

            if (session != null && App.username_sqlite == null)
            {
                try
                {
                    string username = session.User.Name;
                    Debug.WriteLine("hi" + username);
                    usernameTxt.Text = "Hi " + username + " Welcome To the Event Manager";
                }
                catch
                {
                }
            }
            else
            {
                usernameTxt.Text = "Hi " + App.username_sqlite + " : Welcome To the Event Manager";
            }



            if (App.EventModel.EventAddress != null && App.EventModel.EventStartTime != null && App.EventModel.EventName != null)
            {
                ev_address.Text = App.EventModel.EventName + "  @  " + App.EventModel.EventAddress;
                var dateFormatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.full} {day.integer}");
                var eventdate     = dateFormatter.Format(App.EventModel.EventStartTime);
                ev_time.Text = eventdate + "  At  " + App.EventModel.EventDuration;
            }
        }
Example #38
0
        /// <summary>
        /// Populate day selection list
        /// </summary>
        private void PopulateDaySelectionList()
        {
            GeographicRegion userRegion = new GeographicRegion();
            var userDateFormat          = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate", new[] { userRegion.Code });

            for (int i = 0; i < 7; i++)
            {
                var nameOfDay = System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames[((int)DateTime.Now.DayOfWeek + 7 - i) % 7];
                if (i == 0)
                {
                    nameOfDay += " " + _resourceLoader.GetString("Today");
                }
                DateTime itemDate = DateTime.Now.Date - TimeSpan.FromDays(i);
                _daySelectionList.Add(
                    new DaySelectionItem(
                        nameOfDay + " " + userDateFormat.Format(itemDate),
                        itemDate));
            }
            // Add the option to show everything
            _daySelectionList.Add(new DaySelectionItem(_resourceLoader.GetString("All"), null));
        }
Example #39
0
        public static async Task RefreshJumplistAsync()
        {
            if (!JumpList.IsSupported())
            {
                return;
            }
            var jl = await JumpList.LoadCurrentAsync();

            foreach (var item in jl.Items)
            {
                if (item.RemovedByUser && item.GroupName == RECENT_GROUP_NAME)
                {
                    HistoryDb.Remove(new Uri(item.Arguments));
                }
            }
            jl.Items.Clear();
            using (var db = new HistoryDb())
            {
                var          records     = db.HistorySet.OrderByDescending(r => r.TimeStamp).Take(50).ToArray();
                var          added       = new HashSet <HistoryRecord>(HistoryRecordComparer.Instance);
                var          dtformatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate shorttime");
                const string sep         = " - ";
                foreach (var record in records)
                {
                    if (!added.Add(record))
                    {
                        continue;
                    }
                    var item = JumpListItem.CreateWithArguments(record.Uri.ToString(), record.ToDisplayString());
                    item.GroupName   = RECENT_GROUP_NAME;
                    item.Logo        = new Uri($"ms-appx:///Assets/JumpList/{record.Type.ToString()}.png");
                    item.Description = item.DisplayName + sep + dtformatter.Format(record.Time);
                    jl.Items.Add(item);
                }
            }
            await jl.SaveAsync();
        }
Example #40
0
        public async Task loadLog()
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("logdata.xml");
            Debug.WriteLine("Attempting to read file  " + file.Path + " into xdocument");
            XDocument doc = XDocument.Load(file.Path);
            var ps = (
                    from actions in doc.Root.Elements("Action").Elements("Person")
                    select actions
                );

            IEnumerable<XElement> nactions = (
                  from actionsa in doc.Root.Elements("Action")
                 // where (string)actions.Attribute("type") == "Sign In"
                  from person in actionsa.Elements("Person")
                  from dates in person.Elements("Date")
                  orderby (Convert.ToDateTime(person.Element("Date").Value)) descending
                  select actionsa
              );

            foreach (XElement action in nactions)
            {
                LogRecordTile tile = new LogRecordTile();
                tile.txtName.Text = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                tile.txtCompany.Text = action.Element("Person").Element("Company-Represented").Value;
                tile.txtHost.Text = action.Element("Person").Element("Boeing-Host-Name").Value;
                tile.txtAction.Text = action.Attribute("type").Value;
                var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                DateTime dateToFormat = Convert.ToDateTime(action.Element("Person").Element("Time-In").Value.ToString());
                var thedate = formatter.Format(dateToFormat);
                var thetime = formatterTime.Format(dateToFormat);
                tile.txtDate.Text = thedate + " " + thetime; 
                theGrid.Items.Add(tile);
            }
        }
        private async void ButtonSendNotification_Click(object sender, RoutedEventArgs e)
        {
            base.IsEnabled = false;

            try
            {
                if (_tileId == null)
                {
                    await new MessageDialog("No secondary tile was pinned. In the previous step, you had to pin the tile.", "Error").ShowAsync();
                    return;
                }

                SecondaryTile tile = (await SecondaryTile.FindAllAsync()).FirstOrDefault(i => i.TileId.Equals(_tileId));
                if (tile == null)
                {
                    await new MessageDialog("The secondary tile that was previously pinned could not be found. Has it been removed from Start?", "Error").ShowAsync();
                    return;
                }

                // Decide expiration time
                Windows.Globalization.Calendar cal = new Windows.Globalization.Calendar();
                cal.SetToNow();
                cal.AddSeconds(20);

                // Get expiration time and date
                var longTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
                DateTimeOffset expiryTime = cal.GetDateTime();
                string expiryTimeString = longTime.Format(expiryTime);

                // Create the custom tile that will expire
                string tileXmlString = 
                "<tile>"
                + "<visual>"
                + "<binding template='TileMedium'>"
                + "<text hint-wrap='true'>This notification will expire at " + expiryTimeString + "</text>"
                + "</binding>"
                + "<binding template='TileWide'>"
                + "<text hint-wrap='true'>This notification will expire at " + expiryTimeString + "</text>"
                + "</binding>"
                + "<binding template='TileLarge'>"
                + "<text hint-wrap='true'>This notification will expire at " + expiryTimeString + "</text>"
                + "</binding>"
                + "</visual>"
                + "</tile>";

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(tileXmlString);

                // Create the notification
                TileNotification notifyTile = new TileNotification(xmlDoc);

                // Set expiration time for the notification
                notifyTile.ExpirationTime = expiryTime;

                // And send the notification to the tile
                TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notifyTile);
            }

            catch (Exception ex)
            {
                await new MessageDialog(ex.ToString(), "Error updating tile").ShowAsync();
            }

            finally
            {
                base.IsEnabled = true;
            }
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

#if WINDOWS_APP
                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;
#endif

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged += OnGeofenceStatusChanged;
            }
#if WINDOWS_APP
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
#endif
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #43
0
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime          = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar         = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection    = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged        += OnGeofenceStatusChanged;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #44
0
 async void WriteTimestamp()
 {
     Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
     
     StorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.ReplaceExisting);
     //await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
     await FileIO.WriteLinesAsync(sampleFile,massMoneyT);
     
 }
        private async Task loadSignIns()
        {
            Debug.WriteLine("loading sign ins.");
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("logdata.xml");
            Debug.WriteLine("Attempting to read file  " + file.Path + " into xdocument");
            XDocument doc = XDocument.Load(file.Path);
            var ps = (
                    from actions in doc.Root.Elements("Action").Elements("Person")
                    select actions
                );

            var normalized = ps.Select(x => new
            {
                FullName = (string)x.Element("First-Name") + " " + (string)x.Element("Last-Name"),
                id = x.Descendants("ID").Max(y => (int)y)
            });

            var maxids = (from t in normalized
                          group t by t.FullName
                              into g
                              select new
                              {
                                  //FullName = g.Key,
                                  ID = (from t2 in g select t2.id).Max()
                              }
                            );



            List<string> mylist = new List<string>();
            foreach (var i in maxids)
            {
                mylist.Add(i.ID.ToString());
            }



            IEnumerable<XElement> persons = (
                    from actions in doc.Root.Elements("Action")
                    where (string)actions.Attribute("type") == "Sign In"
                    from person in actions.Elements("Person")
                    where mylist.Contains(person.Element("ID").Value)
                    from dates in person.Elements("Date")
                    where Convert.ToDateTime(dates.Value).Date == DateTime.Now.Date //just signins for today - uncertain about this..
                    select person
                );

            Debug.WriteLine(persons.Count());
            Debug.WriteLine(persons);

            //for (var i = 0; i <= 25; i++)
            //{
            //    VisitorTile tile = new VisitorTile();
            //    tile.txtName.Text = "TEst";
            //    tile.txtCompany.Text = "Bobs Butrgers";
            //    tile.txtTimeIn.Text = DateTime.Now.TimeOfDay.ToString();
            //    lvSignIns.Items.Add(tile);

            //}


                foreach (XElement signin in persons)
                {
                    Debug.WriteLine("Adding Tile.");
                    VisitorTile tile = new VisitorTile();
                    tile.person = signin;
                    tile.txtName.Text = signin.Element("Last-Name").Value.ToString() + ", " + signin.Element("First-Name").Value.ToString();
                    tile.txtCompany.Text = signin.Element("Company-Represented").Value.ToString();

                    var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                    var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                    DateTime dateToFormat = Convert.ToDateTime(signin.Element("Time-In").Value.ToString());

                    var thedate = formatter.Format(dateToFormat);
                    var thetime = formatterTime.Format(dateToFormat);

                    tile.txtTimeIn.Text = thedate + " " + thetime; 
                    
                    lvSignIns.Items.Add(tile);
                }

            if(persons.Count() == 0){
                VisitorTile tile = new VisitorTile();

                tile.txtName.Text = "No current visitors";
                tile.txtCompany.Text = "";
                tile.txtTimeIn.Text = "";
                lvSignIns.Items.Add(tile);
            }
        }
Example #46
0
 /// <summary>
 /// Fill the list with current day of week, and in descending order rest of the weekdays
 /// </summary>
 private void FillDateList()
 {
     GeographicRegion userRegion = new GeographicRegion();
     var userDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter( "shortdate", new[] { userRegion.Code } );
     for( int i = 0; i < 7; i++ )
     {
         var nameOfDay = System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames[ ( (int)DateTime.Now.DayOfWeek + 7 - i ) % 7 ];
         if( i == 0 )
         {
             nameOfDay += " " + _resourceLoader.GetString( "Today" );
         }
         DateTime itemDate = DateTime.Now.Date - TimeSpan.FromDays( i );
         _daySelectionList.Add( 
             new DaySelectionItem( 
                 nameOfDay + " " + userDateFormat.Format( itemDate ), 
                 itemDate ) );
     }
     // Add the option to show everything
     _daySelectionList.Add( new DaySelectionItem( _resourceLoader.GetString( "All" ), null ) );
 }
Example #47
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            DateTimeOffset sd = startDate.Date;
            DateTimeOffset ed = endDate.Date;
            string searchStr = txtSearchString.Text;

            Debug.WriteLine("Applying Filter...");
         

            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("logdata.xml");
            Debug.WriteLine("Attempting to read file  " + file.Path + " into xdocument");
            XDocument doc = XDocument.Load(file.Path);
            var ps = (
                    from nodes in doc.Root.Elements("Action").Elements("Person")
                    select nodes
                );

            IEnumerable<XElement> actions = (
                  from nodes in doc.Root.Elements("Action")
                  from person in nodes.Elements("Person")
                  from dates in person.Elements("Date")
                  where (Convert.ToDateTime(person.Element("Time-In").Value) < ed.ToUniversalTime())
                  where (Convert.ToDateTime(person.Element("Time-In").Value) > sd.ToUniversalTime())
                  orderby (Convert.ToDateTime(person.Element("Date").Value)) descending
                  select nodes
              );

            Debug.WriteLine("found " + actions.Count() + "matching records.");

            theGrid.Items.Clear();

            foreach (XElement action in actions)
            {

                if (txtSearchString.Text != "" || txtCompany.Text != "" || txtHost.Text != "")
                {
                    if (txtSearchString.Text != "")
                    {
                        string filter = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                        if (filter.ToUpper().Contains(txtSearchString.Text.ToUpper()))
                        {
                            LogRecordTile tile = new LogRecordTile();
                            tile.txtAction.Text = action.Attribute("type").Value;
                            tile.txtName.Text = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                            tile.txtCompany.Text = action.Element("Person").Element("Company-Represented").Value;
                            tile.txtHost.Text = action.Element("Person").Element("Boeing-Host-Name").Value;
                            var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                            var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                            DateTime dateToFormat = Convert.ToDateTime(action.Element("Person").Element("Time-In").Value.ToString());
                            var thedate = formatter.Format(dateToFormat);
                            var thetime = formatterTime.Format(dateToFormat);
                            tile.txtDate.Text = thedate + " " + thetime;
                            theGrid.Items.Add(tile);
                        }
                    }

                    if(txtCompany.Text != ""){
                        string filter = action.Element("Person").Element("Company-Represented").Value;
                        if (filter.ToUpper().Contains(txtCompany.Text.ToUpper()))
                        {
                            LogRecordTile tile = new LogRecordTile();
                            tile.txtAction.Text = action.Attribute("type").Value;
                            tile.txtName.Text = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                            tile.txtCompany.Text = action.Element("Person").Element("Company-Represented").Value;
                            tile.txtHost.Text = action.Element("Person").Element("Boeing-Host-Name").Value;
                            var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                            var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                            DateTime dateToFormat = Convert.ToDateTime(action.Element("Person").Element("Time-In").Value.ToString());
                            var thedate = formatter.Format(dateToFormat);
                            var thetime = formatterTime.Format(dateToFormat);
                            tile.txtDate.Text = thedate + " " + thetime;
                            theGrid.Items.Add(tile);
                        }
                    }

                    if (txtHost.Text != "")
                    {
                        string filter = action.Element("Person").Element("Boeing-Host-Name").Value;
                        if (filter.ToUpper().Contains(txtHost.Text.ToUpper()))
                        {
                            LogRecordTile tile = new LogRecordTile();
                            tile.txtAction.Text = action.Attribute("type").Value;
                            tile.txtName.Text = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                            tile.txtCompany.Text = action.Element("Person").Element("Company-Represented").Value;
                            tile.txtHost.Text = action.Element("Person").Element("Boeing-Host-Name").Value;
                            var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                            var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                            DateTime dateToFormat = Convert.ToDateTime(action.Element("Person").Element("Time-In").Value.ToString());
                            var thedate = formatter.Format(dateToFormat);
                            var thetime = formatterTime.Format(dateToFormat);
                            tile.txtDate.Text = thedate + " " + thetime;
                            theGrid.Items.Add(tile);
                        }
                    }

                }
                else
                {
                    LogRecordTile tile = new LogRecordTile();
                    tile.txtAction.Text = action.Attribute("type").Value;
                    tile.txtName.Text = action.Element("Person").Element("First-Name").Value + " " + action.Element("Person").Element("Last-Name").Value;
                    tile.txtCompany.Text = action.Element("Person").Element("Company-Represented").Value;
                    tile.txtHost.Text = action.Element("Person").Element("Boeing-Host-Name").Value;
                    var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
                    var formatterTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shorttime");
                    DateTime dateToFormat = Convert.ToDateTime(action.Element("Person").Element("Time-In").Value.ToString());
                    var thedate = formatter.Format(dateToFormat);
                    var thetime = formatterTime.Format(dateToFormat);
                    tile.txtDate.Text = thedate + " " + thetime;
                    theGrid.Items.Add(tile);

                }

            }

        }
Example #48
0
        private void GetGeofenceStateChangedReports(Geoposition pos)
        {
            _geofenceBackgroundEvents.Clear();

            FillEventCollectionWithExistingEvents();

            GeofenceMonitor monitor = GeofenceMonitor.Current;

            Geoposition posLastKnown = monitor.LastKnownGeoposition;

            Windows.Globalization.Calendar calendar = new Windows.Globalization.Calendar();
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatterLongTime;
            formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);

            bool eventOfInterest = true;

            // NOTE TO DEVELOPER:
            // Registered geofence events can be filtered out if the
            // geofence event time is stale.
            DateTimeOffset eventDateTime = pos.Coordinate.Timestamp;

            calendar.SetToNow();
            DateTimeOffset nowDateTime  = calendar.GetDateTime();
            TimeSpan       diffTimeSpan = nowDateTime - eventDateTime;

            long deltaInSeconds = diffTimeSpan.Ticks / oneHundredNanosecondsPerSecond;

            if (true == eventOfInterest)
            {
                if ((posLastKnown.Coordinate.Point.Position.Latitude != pos.Coordinate.Point.Position.Latitude) ||
                    (posLastKnown.Coordinate.Point.Position.Longitude != pos.Coordinate.Point.Position.Longitude))
                {
                    UpdateInforamtion.WipeGeolocDataFromAppData();
                }

                if (true == eventOfInterest)
                {
                    string geofenceItemEvent   = null;
                    int    numEventsOfInterest = 0;

                    // Retrieve a vector of state change reports
                    var reports = GeofenceMonitor.Current.ReadReports();

                    foreach (var report in reports)
                    {
                        GeofenceState state = report.NewState;
                        geofenceItemEvent = report.Geofence.Id + " " + formatterLongTime.Format(eventDateTime);

                        if (state == GeofenceState.Removed)
                        {
                            GeofenceRemovalReason reason = report.RemovalReason;
                            if (reason == GeofenceRemovalReason.Expired)
                            {
                                geofenceItemEvent += " (Removed/Expired)";
                            }
                            else if (reason == GeofenceRemovalReason.Used)
                            {
                                geofenceItemEvent += " (Removed/Used)";
                            }
                        }
                        else if (state == GeofenceState.Entered)
                        {
                            geofenceItemEvent += " (Entered)";
                        }
                        else if (state == GeofenceState.Exited)
                        {
                            geofenceItemEvent += " (Exited)";
                        }

                        AddGeofenceEvent(geofenceItemEvent);

                        ++numEventsOfInterest;
                    }

                    if (true == eventOfInterest && 0 != numEventsOfInterest)
                    {
                        SaveExistingEvents();

                        // NOTE: Other notification mechanisms can be used here, such as Badge and/or Tile updates.
                        DoToast(numEventsOfInterest, geofenceItemEvent);
                    }
                }
            }
        }
        private void GetGeofenceStateChangedReports(Geoposition pos)
        {
            _geofenceBackgroundEvents.Clear();

            FillEventCollectionWithExistingEvents();

            GeofenceMonitor monitor = GeofenceMonitor.Current;

            Geoposition posLastKnown = monitor.LastKnownGeoposition;

            Windows.Globalization.Calendar calendar = new Windows.Globalization.Calendar();
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatterLongTime;
            formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);

            bool eventOfInterest = true;

            // NOTE TO DEVELOPER:
            // Registered geofence events can be filtered out if the
            // geofence event time is stale.
            DateTimeOffset eventDateTime = pos.Coordinate.Timestamp;

            calendar.SetToNow();
            DateTimeOffset nowDateTime = calendar.GetDateTime();
            TimeSpan diffTimeSpan = nowDateTime - eventDateTime;

            long deltaInSeconds = diffTimeSpan.Ticks / oneHundredNanosecondsPerSecond;

            // NOTE TO DEVELOPER:
            // If the time difference between the geofence event and now is too large
            // the eventOfInterest should be set to false.

            if (true == eventOfInterest)
            {
                // NOTE TO DEVELOPER:
                // This event can be filtered out if the
                // geofence event location is too far away.
                if ((posLastKnown.Coordinate.Point.Position.Latitude != pos.Coordinate.Point.Position.Latitude) ||
                    (posLastKnown.Coordinate.Point.Position.Longitude != pos.Coordinate.Point.Position.Longitude))
                {
                    // NOTE TO DEVELOPER:
                    // Use an algorithm like the Haversine formula or Vincenty's formulae to determine
                    // the distance between the current location (pos.Coordinate)
                    // and the location of the geofence event (latitudeEvent/longitudeEvent).
                    // If too far apart set eventOfInterest to false to
                    // filter the event out.
                }

                if (true == eventOfInterest)
                {
                    string geofenceItemEvent = null;
                    int numEventsOfInterest = 0;

                    // Retrieve a vector of state change reports
                    var reports = GeofenceMonitor.Current.ReadReports();

                    foreach (var report in reports)
                    {
                        GeofenceState state = report.NewState;
                        geofenceItemEvent = report.Geofence.Id + " " + formatterLongTime.Format(eventDateTime);

                        if (state == GeofenceState.Removed)
                        {
                            GeofenceRemovalReason reason = report.RemovalReason;
                            if (reason == GeofenceRemovalReason.Expired)
                            {
                                geofenceItemEvent += " (Removed/Expired)";
                            }
                            else if (reason == GeofenceRemovalReason.Used)
                            {
                                geofenceItemEvent += " (Removed/Used)";
                            }
                        }
                        else if (state == GeofenceState.Entered)
                        {
                            geofenceItemEvent += " (Entered)";
                        }
                        else if (state == GeofenceState.Exited)
                        {
                            geofenceItemEvent += " (Exited)";
                        }

                        AddGeofenceEvent(geofenceItemEvent);

                        ++numEventsOfInterest;
                    }

                    if (true == eventOfInterest && 0 != numEventsOfInterest)
                    {
                        SaveExistingEvents();

                        // NOTE: Other notification mechanisms can be used here, such as Badge and/or Tile updates.
                        DoToast(numEventsOfInterest, geofenceItemEvent);
                    }
                }
            }
        }
Example #50
0
        async private void WriteDataToIsolatedStorage()
        {
            // We have exlusive access to the mutex so can safely wipe the transfer file
            Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile transferFile = await localFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);

            using (var stream = await transferFile.OpenStreamForWriteAsync())
            {
                StreamWriter writer = new StreamWriter(stream);

                writer.WriteLine(weatherData.TimeStamp);
                writer.WriteLine(weatherData.Altitude.ToString());
                writer.WriteLine(weatherData.BarometricPressure.ToString());
                writer.WriteLine(weatherData.CelsiusTemperature.ToString());
                writer.WriteLine(weatherData.FahrenheitTemperature.ToString());
                writer.WriteLine(weatherData.Humidity.ToString());
                writer.Flush();
            }
        }
 string getTimeStampedMessage(string eventText)
 {
     Windows.Globalization.DateTimeFormatting.DateTimeFormatter dateTimeFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
     string dateTime = dateTimeFormat.Format(DateTime.Now);
     return eventText + "   " + dateTime;
 }