Пример #1
0
 private string ReportRegionData(GeographicRegion region)
 {
     return("Display Name: " + region.DisplayName + "\n" +
            "Native Name: " + region.NativeName + "\n" +
            "Currencies in use: " + string.Join(", ", region.CurrenciesInUse) + "\n" +
            "Codes: " + region.CodeTwoLetter + ", " + region.CodeThreeLetter + ", " + region.CodeThreeDigit + "\n\n");
 }
Пример #2
0
        /// <summary>Initialize the client using NobleConnectSettings. The region used is determined by the Relay Server Address in the NobleConnectSettings.</summary>
        /// <remarks>
        /// The default address is connect.noblewhale.com, which will automatically select the closest 
        /// server based on geographic region.
        /// 
        /// If you would like to connect to a specific region you can use one of the following urls:
        /// <pre>
        ///     us-east.connect.noblewhale.com - Eastern United States
        ///     us-west.connect.noblewhale.com - Western United States
        ///     eu.connect.noblewhale.com - Europe
        ///     ap.connect.noblewhale.com - Asia-Pacific
        ///     sa.connect.noblewhale.com - South Africa
        ///     hk.connect.noblewhale.com - Hong Kong
        /// </pre>
        /// 
        /// Note that region selection will ensure each player connects to the closest relay server, but it does not 
        /// prevent players from connecting across regions. If you want to prevent joining across regions you will 
        /// need to implement that separately (by filtering out unwanted regions during matchmaking for example).
        /// </remarks>
        /// <param name="topo">The HostTopology to use for the NetworkClient. Must be the same on host and client.</param>
        /// <param name="onFatalError">A method to call if something goes horribly wrong.</param>
        /// <param name="allocationResendTimeout">Initial timeout before resending refresh messages. This is doubled for each failed resend.</param>
        /// <param name="maxAllocationResends">Max number of times to try and resend refresh messages before giving up and shutting down the relay connection. If refresh messages fail for 30 seconds the relay connection will be closed remotely regardless of these settings.</param>
        public NobleClient(GeographicRegion region = GeographicRegion.AUTO, Action<string> onFatalError = null, int relayLifetime = 60, int relayRefreshTime = 30, float allocationResendTimeout = .1f, int maxAllocationResends = 8)
        {
            var settings = (NobleConnectSettings)Resources.Load("NobleConnectSettings", typeof(NobleConnectSettings));

            this.onFatalError = onFatalError;
            nobleConfig = new IceConfig
            {
                iceServerAddress = RegionURL.FromRegion(region),
                icePort = settings.relayServerPort,
                maxAllocationRetransmissionCount = maxAllocationResends,
                allocationRetransmissionTimeout = (int)(allocationResendTimeout * 1000),
                allocationLifetime = relayLifetime,
                refreshTime = relayRefreshTime
            };

            if (!string.IsNullOrEmpty(settings.gameID))
            {
                string decodedGameID = Encoding.UTF8.GetString(Convert.FromBase64String(settings.gameID));
                string[] parts = decodedGameID.Split('\n');

                if (parts.Length == 3)
                {
                    nobleConfig.username = parts[1];
                    nobleConfig.password = parts[2];
                    nobleConfig.origin = parts[0];
                }
            }

            Init();
        }
Пример #3
0
        private WebRequest CreateWebRequest(string productId)
        {
            var country   = new GeographicRegion().CodeTwoLetter;
            var languages = string.Join(string.Empty, ApplicationLanguages.Languages.Select((x, i) =>
            {
                if (i == 1)
                {
                    return("_" + x);
                }
                if (i > 1)
                {
                    return("." + x);
                }

                return(x);
            }));

            ////https://next-services.apps.microsoft.com/browse/{osVersion}.{osBuild}-{appModel}/{clientVersion}/{chromeLocale}_{localeList}/c/{country}/cp/{channelPartner}/Apps/{appId}

            var url = string.Format("https://next-services.apps.microsoft.com/browse/6.3.9600-0/776/{2}/c/{1}/cp/0/Apps/{0}",
                                    productId.TrimStart('{').TrimEnd('}'),
                                    country,
                                    languages);

            var request = WebRequest.Create(url);

            request.SetNoCacheHeaders();

            return(request);
        }
Пример #4
0
        private static void DetectDutchLanguage()
        {
            bool forceDutch    = false;
            var  userlanguages = GlobalizationPreferences.Languages;

            if (userlanguages.Contains("nl-NL"))
            {
                forceDutch = true;
            }

            GeographicRegion userRegion = new GeographicRegion();

            if (userRegion.CodeTwoLetter.ToLower() == "nl")
            {
                forceDutch = true;
            }

            if (forceDutch)
            {
                Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = "nl";
            }
            else
            {
                Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = string.Empty;
            }
        }
Пример #5
0
        public SettingsModel()
        {
            this.IsFirstLaunch = true;
            this.FirstLaunch   = DateTime.Now;
            this.HasUserBeenPromptedForPush = false;
            this.LastRatingsPromptDate      = DateTime.Now;
            this.UserId   = Guid.NewGuid().ToString();
            this.Language = new LanguageModel();
            CultureInfo currentCulture = CultureInfo.CurrentCulture;

            this.Language.Id             = SettingsModel.GetLanguageIdFromIsoCode(currentCulture, false);
            this.Language.IsoCode        = SettingsModel.GetIsoCodeFromLanguageId(this.Language.Id);
            this.PartnerCode             = "windows8-v3";
            this.IsEulaAgreed            = false;
            this.PreferredForecastType   = ForecastType.Daily;
            this.PreferredLifestyleIndex = 100;
            this.IsWeatherAnimationsOn   = true;
            this.DataDensity             = DataDensityType.High;
            this.IsToastEnabled          = false;
            this.IsGpsEnabled            = false;
            this.MapTileOpacity          = 0.6;
            GeographicRegion geographicRegion = new GeographicRegion();
            string           codeTwoLetter    = geographicRegion.CodeTwoLetter;

            this.UnitType = ((codeTwoLetter.ToLower() == "us") ? UnitsType.Imperial : UnitsType.Metric);
        }
Пример #6
0
        public static string GetLocale()
        {
            GeographicRegion userRegion = new GeographicRegion();
            string           regionCode = userRegion.CodeTwoLetter;

            return(regionCode);
        }
Пример #7
0
        /// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.GeographicRegion class to
            // obtain the geographic region characteristics.

            // Stores results of the scenario
            StringBuilder results = new StringBuilder();

            // Display characteristics of user's geographic region.
            GeographicRegion userRegion = new GeographicRegion();

            results.AppendLine("User's region display name: " + userRegion.DisplayName);
            results.AppendLine("User's region native name: " + userRegion.NativeName);
            results.AppendLine("User's region currencies in use: " + string.Join(",", userRegion.CurrenciesInUse));
            results.AppendLine("User's region codes: " + userRegion.CodeTwoLetter + "," + userRegion.CodeThreeLetter + "," + userRegion.CodeThreeDigit);
            results.AppendLine();

            // Display characteristics of example region.
            GeographicRegion ruRegion = new GeographicRegion("RU");

            results.AppendLine("RU region display name: " + ruRegion.DisplayName);
            results.AppendLine("RU region native name: " + ruRegion.NativeName);
            results.AppendLine("RU region currencies in use: " + string.Join(",", ruRegion.CurrenciesInUse));
            results.AppendLine("RU region codes: " + ruRegion.CodeTwoLetter + "," + ruRegion.CodeThreeLetter + "," + ruRegion.CodeThreeDigit);

            // Display the results
            rootPage.NotifyUser(results.ToString(), NotifyType.StatusMessage);
        }
Пример #8
0
 public EditRegionViewModel(IEnumerable <Variety> varieties, Variety variety, GeographicRegion region)
 {
     _title           = "Edit Region";
     _varieties       = new ReadOnlyList <VarietyViewModel>(varieties.Select(v => new VarietyViewModel(v)).OrderBy(vm => vm.Name).ToArray());
     _selectedVariety = _varieties.First(vm => vm.DomainVariety == variety);
     _description     = region.Description;
 }
Пример #9
0
        static Country()
        {
            foreach (Country c in Countries)
            {
                if (GeographicRegion.IsSupported(c.Code))
                {
                    c.DisplayName = new GeographicRegion(c.Code).DisplayName;
                }
                else
                {
                    c.DisplayName = c.Name;
                }
            }

            var alphabet   = "abcdefghijklmnopqrstuvwxyz";
            var list       = new List <KeyedList <string, Country> >(alphabet.Length);
            var dictionary = new Dictionary <string, KeyedList <string, Country> >();

            for (int i = 0; i < alphabet.Length; i++)
            {
                var key   = alphabet[i].ToString();
                var group = new KeyedList <string, Country>(key);

                list.Add(group);
                dictionary[key] = group;
            }

            foreach (var country in Countries)
            {
                dictionary[country.GetKey()].Add(country);
            }

            GroupedCountries = list;
        }
Пример #10
0
 static public String ToShortDate(DateTime d)
 {
     if (userRegion == null)
     {
         userRegion     = new GeographicRegion();
         userDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate", new[] { userRegion.Code });
     }
     return(userDateFormat.Format(d));
 }
Пример #11
0
 public SubRegion(
     string code,
     string name,
     GeographicRegion region
     ) : base(
         code,
         name,
         region)
 {
 }
 public IntermediateRegion(
     string code,
     string name,
     GeographicRegion region
     ) : base(
         code,
         name,
         region)
 {
 }
Пример #13
0
 protected GeographicSubregion(
     string id,
     string name,
     GeographicRegion region
     ) : base(
         id,
         name)
 {
     Region = region;
     Region?.Add(this);
 }
Пример #14
0
        /// <summary>
        ///     Initializes the singleton application object.  This is the first line of authored code
        ///     executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            // Set the country before initialization occurs so App Center can send the field to the backend
            // Note that the country code provided does not reflect the physical device location, but rather the
            // country that corresponds to the culture it uses. You may wish to retrieve the country code using
            // a different means, such as device location.
            var geographicRegion = new GeographicRegion();

            AppCenter.SetCountryCode(geographicRegion.CodeTwoLetter);
            InitializeComponent();
            Suspending += OnSuspending;
        }
Пример #15
0
        private static XElement SaveRegion(GeographicRegion region)
        {
            var regionElem = new XElement(Cog + "Region");

            if (!string.IsNullOrEmpty(region.Description))
            {
                regionElem.Add(new XElement(Cog + "Description", region.Description));
            }
            regionElem.Add(new XElement(Cog + "Coordinates",
                                        region.Coordinates.Select(coord => new XElement(Cog + "Coordinate", new XElement(Cog + "Latitude", coord.Latitude), new XElement(Cog + "Longitude", coord.Longitude)))));
            return(regionElem);
        }
Пример #16
0
        private static async Task SetCountryCode()
        {
            // The following country code is used only as a fallback for the main implementation.
            // This fallback country code does not reflect the physical device location, but rather the
            // country that corresponds to the culture it uses.
            var countryCode  = new GeographicRegion().CodeTwoLetter;
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                var geoLocator = new Geolocator
                {
                    DesiredAccuracyInMeters = 100
                };
                var position = await geoLocator.GetGeopositionAsync();

                var myLocation = new BasicGeoposition
                {
                    Longitude = position.Coordinate.Point.Position.Longitude,
                    Latitude  = position.Coordinate.Point.Position.Latitude
                };
                var pointToReverseGeocode = new Geopoint(myLocation);
                try
                {
                    MapService.ServiceToken = Constants.BingMapsAuthKey;
                }
                catch (SEHException)
                {
                    AppCenterLog.Info(LogTag, "Please provide a valid Bing Maps authentication key. For more info see: https://docs.microsoft.com/en-us/windows/uwp/maps-and-location/authentication-key");
                }
                var result = await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);

                if (result.Status != MapLocationFinderStatus.Success || result.Locations == null || result.Locations.Count == 0)
                {
                    break;
                }

                // The returned country code is in 3-letter format (ISO 3166-1 alpha-3).
                // Below we convert it to ISO 3166-1 alpha-2 (two letter).
                var country = result.Locations[0].Address.CountryCode;
                countryCode = new GeographicRegion(country).CodeTwoLetter;
                break;

            case GeolocationAccessStatus.Denied:
                AppCenterLog.Info(LogTag, "Geolocation access denied. In order to set country code in App Center, enable location service in Windows 10.");
                break;

            case GeolocationAccessStatus.Unspecified:
                break;
            }
            AppCenter.SetCountryCode(countryCode);
        }
Пример #17
0
        public GeographicalRegionViewModel(IProjectService projectService, IDialogService dialogService, GeographicalVarietyViewModel variety, GeographicRegion region)
            : base(region)
        {
            _projectService = projectService;
            _dialogService  = dialogService;

            _variety     = variety;
            _region      = region;
            _coordinates = new BindableList <Tuple <double, double> >(_region.Coordinates.Select(coord => Tuple.Create(coord.Latitude, coord.Longitude)));
            _coordinates.CollectionChanged += CoordinatesChanged;
            _editCommand   = new RelayCommand(EditRegion);
            _removeCommand = new RelayCommand(RemoveRegion);
        }
Пример #18
0
        private void ShowResults()
        {
            // This scenario uses the Windows.Globalization.GeographicRegion class to
            // obtain the geographic region characteristics.
            var userGeoRegion = new GeographicRegion();

            // This obtains the geographic region characteristics by providing a country or region code.
            var exampleGeoRegion = new GeographicRegion("JP");

            // Display the results
            OutputTextBlock.Text = "User's Preferred Geographic Region\n" + ReportRegionData(userGeoRegion) +
                                   "Example Geographic Region by region/country code (JP)\n" + ReportRegionData(exampleGeoRegion);
        }
Пример #19
0
        private void AddNewRegion(IEnumerable <Tuple <double, double> > coordinates)
        {
            var vm = new EditRegionViewModel(_projectService.Project.Varieties);

            if (_dialogService.ShowModalDialog(this, vm) == true)
            {
                var region = new GeographicRegion(coordinates.Select(coord => new GeographicCoordinate(coord.Item1, coord.Item2)))
                {
                    Description = vm.Description
                };
                vm.SelectedVariety.DomainVariety.Regions.Add(region);
                SelectedRegion = _varieties[vm.SelectedVariety.DomainVariety].Regions.Single(r => r.DomainRegion == region);
                Messenger.Default.Send(new DomainModelChangedMessage(false));
            }
        }
Пример #20
0
		private GeographicRegion LoadRegion(XElement polygon, string desc)
		{
			XElement coords = polygon.Elements(Kml + "outerBoundaryIs").Elements(Kml + "LinearRing").Elements(Kml + "coordinates").FirstOrDefault();
			if (coords == null || string.IsNullOrEmpty((string) coords))
				throw new ImportException(string.Format("A Polygon element does not contain coordinates. Line: {0}", ((IXmlLineInfo) polygon).LineNumber));

			var region = new GeographicRegion {Description = desc};
			string[] coordsArray = ((string) coords).Split().Where(coord => !string.IsNullOrEmpty(coord)).ToArray();
			for (int i = 0; i < coordsArray.Length - 1; i++)
			{
				string[] coordArray = coordsArray[i].Split(',');
				region.Coordinates.Add(new GeographicCoordinate(double.Parse(coordArray[1], CultureInfo.InvariantCulture), double.Parse(coordArray[0], CultureInfo.InvariantCulture)));
			}
			return region;
		}
        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;
        }
Пример #22
0
        public MainPage()
        {
            this.InitializeComponent();

            var loader = new Windows.ApplicationModel.Resources.ResourceLoader();

            //Globalization Preferences

            //<user's top chosen language>
            var chosenLang = loader.GetString("chosen lang");
            var languages  = GlobalizationPreferences.Languages;

            chosen_lang.Text += chosenLang + ": " + languages[0] + " \n";
            //<user's set home geopgraphic region>
            var homeRegion = loader.GetString("home region");
            var region     = GlobalizationPreferences.HomeGeographicRegion;

            home_region.Text += homeRegion + ": " + region + " \n";
            //<user's calendar setting>
            var calendarSystem = loader.GetString("calendar system");
            var calendars      = GlobalizationPreferences.Calendars;

            calendar_setting.Text += calendarSystem + ": " + calendars[0] + " \n";
            //<user's time setting>
            var clockSetting = loader.GetString("clock setting");
            var clocks       = GlobalizationPreferences.Clocks;

            clock_setting.Text += clockSetting + ": " + clocks[0] + " \n";
            //<user's setting for first day of the week>
            var weekStart = loader.GetString("week start");
            var firstDay  = GlobalizationPreferences.WeekStartsOn;

            week_start.Text += weekStart + ": " + firstDay + " \n";

            //Language Specifics
            var langDetails = loader.GetString("lang details");
            var language    = new Language(languages[0]);

            //<user top language display name> <user top language details>
            lang_details.Text = langDetails + ": " + language.DisplayName + ": " + language.Script + " \n";

            //Geo Region Specifics
            var geoDetails = loader.GetString("geo details");
            var reg        = new GeographicRegion(region);

            //<geographic region display name> <geographic region details>
            geo_details.Text = geoDetails + ": " + reg.DisplayName + ": " + reg.Code + " \n";
        }
Пример #23
0
        public UserViewModel(UserModel user = null)
        {
            if (user == null)
            {
                this.user = new UserModel();
            }
            else
            {
                this.user     = user;
                copyUser      = this.user.GetCopy();
                connectedToFb = AppInfo.AppUser?.FbId != null && AppInfo.AppUser?.FbId != "no_email_accept" && AppInfo.AppUser?.FbId != "no_facebook";
                UserDataUpdated();
            }

            this.Image = new BitmapImage(new Uri(@"ms-appx:///Assets/Graphics/btn_owl.png"));
            LogicHelper.DownloadPhoto(LogicHelper.CreateImageUrl(ImageTypeToDownload.ProfilePhotoBig, this.user.UserId), PhotoDownloaded);

            countryCodes = Task.Run(async() => await LogicHelper.GetCountriesCodes()).Result;

            if (string.IsNullOrWhiteSpace(this.user.CountryCode))
            {
                var region = new GeographicRegion().CodeThreeLetter;
                var item   = countryCodes.FirstOrDefault(r => r.ContryCode == region);
                if (item != null)
                {
                    selectedCountry = item;
                }
                else
                {
                    selectedCountry = countryCodes.FirstOrDefault();
                }
                this.user.CountryCode = selectedCountry.PhoneCodeDigitOnly;
            }
            else
            {
                var item = countryCodes.FirstOrDefault(r => r.PhoneCodeDigitOnly == this.user.CountryCode);
                if (item != null)
                {
                    selectedCountry = item;
                }
                else
                {
                    selectedCountry = countryCodes.FirstOrDefault();
                }
            }
        }
Пример #24
0
        public Country(string code, string phoneCode, string name)
        {
            Code      = code;
            PhoneCode = phoneCode;
            Name      = name;

            if (GeographicRegion.IsSupported(code))
            {
                DisplayName = new GeographicRegion(code).DisplayName;
            }
            else
            {
                DisplayName = name;
            }

            Emoji = char.ConvertFromUtf32(127462 + (code[0] - 'A'))
                    + char.ConvertFromUtf32(127462 + (code[1] - 'A'));
        }
Пример #25
0
        /// <summary>Start listening for incoming connections</summary>
        /// <param name="maxPlayers">The maximum number of players</param>
        /// <param name="port">The port to listen on. Defaults to 0 which will use a random port</param>
        /// <param name="onPrepared">A method to call when the host has received their HostEndPoint from the relay server.</param>
        static public void Listen(int port = 0, GeographicRegion region = GeographicRegion.AUTO, Action <string, ushort> onPrepared = null, Action <string> onFatalError = null, bool forceRelayOnly = false)
        {
            // Store or generate the server port
            if (port == 0)
            {
                // Use a randomly generated endpoint
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    port = (ushort)((IPEndPoint)socket.LocalEndPoint).Port;
                }
            }

            InitializeHosting(port, region, onPrepared, onFatalError, forceRelayOnly);

            SetListenPort((ushort)port);
            // Server Go!
            NetworkServer.Listen(10);
        }
Пример #26
0
        /// <summary>
        /// Creates a new instance with the specified parameters.
        /// </summary>
        public Sale(
            DateTime date,
            HoodieStyle style, decimal price,
            string zipCode, string city, string state)
        {
            GeographicRegion region = GeoData.RegionFromState(state);

            if (region == GeographicRegion.Undefined)
            {
                throw new ArgumentException(string.Format("Unrecognized state '{0}'.", state));
            }

            this.Date    = date;
            this.Style   = style;
            this.Price   = price;
            this.ZipCode = zipCode;
            this.State   = state;
            this.City    = city == null ? string.Empty : city;
            this.Region  = region;
        }
Пример #27
0
        public static Model.GeographicRegionType GetGeographicRegionType(
            this GeographicRegion geographicRegion
            )
        {
            switch (geographicRegion.Object)
            {
            case Iso3166._1.Country country: return(Model.GeographicRegionType.Iso3166_1Country);

            case Iso3166._2.Subdivision subdivision: return(Model.GeographicRegionType.Iso3166_2Subdivision);

            case UnsdM49.Global global: return(Model.GeographicRegionType.UnsdM49Global);

            case UnsdM49.Region region: return(Model.GeographicRegionType.UnsdM49Region);

            case UnsdM49.SubRegion subRegion: return(Model.GeographicRegionType.UnsdM49SubRegion);

            case UnsdM49.IntermediateRegion intermediateRegion: return(Model.GeographicRegionType.UnsdM49IntermediateRegion);

            default: return(default);
            }
        }
Пример #28
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));
        }
        /*
         * private async Task RefreshTodoItems()
         * {
         *  MobileServiceInvalidOperationException exception = null;
         *  try
         *  {
         *      // This code refreshes the entries in the list view by querying the TodoItems table.
         *      // The query excludes completed TodoItems.
         *      items = await todoTable
         *          .Where(todoItem => todoItem.Complete == false)
         *          .ToCollectionAsync();
         *
         *      natanItems = await natanTable
         *          .Where(natanItem => natanItem.Complete == false)
         *          .ToCollectionAsync();
         *  }
         *  catch (MobileServiceInvalidOperationException e)
         *  {
         *      exception = e;
         *  }
         *
         *  if (exception != null)
         *  {
         *      await new MessageDialog(exception.Message, "Error loading items").ShowAsync();
         *  }
         *  else
         *  {
         *      this.ButtonSave.IsEnabled = true;
         *  }
         * }
         */

        /*private async Task UpdateCheckedTodoItem(TodoItem item)
         * {
         *  // This code takes a freshly completed TodoItem and updates the database.
         *              // After the MobileService client responds, the item is removed from the list.
         *  await todoTable.UpdateAsync(item);
         *  items.Remove(item);
         *
         #if OFFLINE_SYNC_ENABLED
         *  await App.MobileService.SyncContext.PushAsync(); // offline sync
         #endif
         * }*/

        /*private async void ButtonRefresh_Click(object sender, RoutedEventArgs e)
         * {
         *
         #if OFFLINE_SYNC_ENABLED
         *  await SyncAsync(); // offline sync
         #endif
         *  await RefreshTodoItems();
         * }*/

        private async void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            //var todoItem = new TodoItem { Text = TextInput.Text };
            ButtonSave.IsEnabled = false;

            if (this.NickNameInput.Text == "" || this.TextInput.Text == "")
            {
                ContentDialog deleteFileDialog = new ContentDialog
                {
                    FontSize            = 10,
                    Title               = "Create game with blank name?",
                    PrimaryButtonText   = "Create",
                    SecondaryButtonText = "Cancel"
                };

                ContentDialogResult result = await deleteFileDialog.ShowAsync();

                // Delete the file if the user clicked the primary button.
                /// Otherwise, do nothing.
                if (result == ContentDialogResult.Primary)
                {
                    App.game = new RunningGameItem();
                    if (TextInput.Text == "")
                    {
                        GeographicRegion userRegion = new GeographicRegion();
                        //App.game = game;
                        string            regionCode    = userRegion.CodeTwoLetter;
                        DateTimeFormatter timeFormatter = new DateTimeFormatter("hour minute", new[] { regionCode });
                        string            time          = timeFormatter.Format(DateTime.Now);
                        Debug.WriteLine("time= " + time);

                        /*
                         * if (String.Compare(App.dataServiceDevice.Name,"LedP1")==0)
                         * {
                         *  App.game.GameName = "LedP1 " + time;
                         * }
                         * if (String.Compare(App.dataServiceDevice.Name, "LedP4") == 0)
                         * {
                         *  App.game.GameName = "LedP4 " + time;
                         * }
                         */
                        switch (App.dataServiceDevice.Name)
                        {
                        case "LedP1":
                            App.game.GameName = "LedP1 " + time;
                            App.game.Player1  = this.NickNameInput.Text == "" ? "LedP1" : this.NickNameInput.Text;
                            App.game.Player2  = App.game.Player3 = App.game.Player4 = "";
                            break;

                        case "LedP2":
                            App.game.GameName = "LedP2 " + time;
                            App.game.Player2  = this.NickNameInput.Text == "" ? "LedP2" : this.NickNameInput.Text;
                            App.game.Player1  = App.game.Player3 = App.game.Player4 = "";
                            break;

                        case "LedP3":
                            App.game.GameName = "LedP3 " + time;
                            App.game.Player3  = this.NickNameInput.Text == "" ? "LedP3" : this.NickNameInput.Text;
                            App.game.Player1  = App.game.Player2 = App.game.Player4 = "";
                            break;

                        case "LedP4":
                            App.game.GameName = "LedP4 " + time;
                            App.game.Player4  = this.NickNameInput.Text == "" ? "LedP4" : this.NickNameInput.Text;
                            App.game.Player1  = App.game.Player2 = App.game.Player3 = "";
                            break;
                        }
                    }
                    if (NickNameInput.Text == "")
                    {
                        switch (App.dataServiceDevice.Name)
                        {
                        case "LedP1":
                            App.game.Player1 = this.NickNameInput.Text == "" ? "LedP1" : this.NickNameInput.Text;
                            App.game.Player2 = App.game.Player3 = App.game.Player4 = "";
                            break;

                        case "LedP2":
                            App.game.Player2 = this.NickNameInput.Text == "" ? "LedP2" : this.NickNameInput.Text;
                            App.game.Player1 = App.game.Player3 = App.game.Player4 = "";
                            break;

                        case "LedP3":
                            App.game.Player3 = this.NickNameInput.Text == "" ? "LedP3" : this.NickNameInput.Text;
                            App.game.Player1 = App.game.Player2 = App.game.Player4 = "";
                            break;

                        case "LedP4":
                            App.game.Player4 = this.NickNameInput.Text == "" ? "LedP4" : this.NickNameInput.Text;
                            App.game.Player1 = App.game.Player2 = App.game.Player3 = "";
                            break;
                        }
                    }

                    App.game.PlayersNum    = 1;
                    App.game.PointsPlayer1 = 0;
                    App.game.PointsPlayer2 = 0;
                    App.game.PointsPlayer3 = 0;
                    App.game.PointsPlayer4 = 0;
                    App.game.GameStarted   = false;
                    App.game.Complete      = false;

                    try
                    {
                        await InsertGameItem(App.game);
                    }
                    catch (System.Net.Http.HttpRequestException ex)
                    {
                        ContentDialog deleteFileDialog2 = new ContentDialog
                        {
                            FontSize          = 10,
                            Title             = "Network Error",
                            PrimaryButtonText = "Home"
                        };

                        ContentDialogResult result2 = await deleteFileDialog.ShowAsync();

                        this.Frame.Navigate(typeof(ServerMenuPage));
                    }

                    App.gameID = App.game.Id;
                    switch (App.dataServiceDevice.Name)
                    {
                    case "LedP1":
                        App.playerNum = 1;
                        break;

                    case "LedP2":
                        App.playerNum = 2;
                        break;

                    case "LedP3":
                        App.playerNum = 3;
                        break;

                    case "LedP4":
                        App.playerNum = 4;
                        break;
                    }
                    GameCreatedText.Text = "Game Created";

                    var n = App._btWriter.WriteString("c33\n");
                    await App._btWriter.StoreAsync();

                    App.playing = true;
                    this.Frame.Navigate(typeof(ControllerPage));
                }
                else
                {
                    createGame = false;
                }
            }
            else
            {
                var game = new RunningGameItem {
                    GameName = TextInput.Text
                };
                App.game = game;

                switch (App.dataServiceDevice.Name)
                {
                case "LedP1":
                    App.game.Player1 = this.NickNameInput.Text == "" ? "LedP1" : this.NickNameInput.Text;
                    App.game.Player2 = App.game.Player3 = App.game.Player4 = "";
                    break;

                case "LedP2":
                    App.game.Player2 = this.NickNameInput.Text == "" ? "LedP2" : this.NickNameInput.Text;
                    App.game.Player1 = App.game.Player3 = App.game.Player4 = "";
                    break;

                case "LedP3":
                    App.game.Player3 = this.NickNameInput.Text == "" ? "LedP3" : this.NickNameInput.Text;
                    App.game.Player1 = App.game.Player2 = App.game.Player4 = "";
                    break;

                case "LedP4":
                    App.game.Player4 = this.NickNameInput.Text == "" ? "LedP4" : this.NickNameInput.Text;
                    App.game.Player1 = App.game.Player2 = App.game.Player3 = "";
                    break;
                }

                App.game.PlayersNum = 1;

                App.game.PointsPlayer1 = 0;
                App.game.PointsPlayer2 = 0;
                App.game.PointsPlayer3 = 0;
                App.game.PointsPlayer4 = 0;
                App.game.GameStarted   = false;
                App.game.Complete      = false;

                await InsertGameItem(App.game);

                App.gameID = App.game.Id;
                switch (App.dataServiceDevice.Name)
                {
                case "LedP1":
                    App.playerNum = 1;
                    break;

                case "LedP2":
                    App.playerNum = 2;
                    break;

                case "LedP3":
                    App.playerNum = 3;
                    break;

                case "LedP4":
                    App.playerNum = 4;
                    break;
                }
                GameCreatedText.Text = "Game Created";

                var n = App._btWriter.WriteString("c33\n");
                await App._btWriter.StoreAsync();

                App.playing = true;
                this.Frame.Navigate(typeof(ControllerPage));

                /*await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                 * {
                 *  Frame.Navigate(typeof(ControllerPage));
                 * });*/

                //var natanItem = new NatanTest { GameName = "NatiGame" };
                //await InsertNatanItem(natanItem);
            }

            ButtonSave.IsEnabled = true;
        }
Пример #30
0
 /// <summary>Initialize the server using NobleConnectSettings. The region used is determined by the Relay Server Address in the NobleConnectSettings.</summary>
 /// <remarks>\copydetails NobleClient::NobleClient(HostTopology,Action)</remarks>
 /// <param name="topo">The HostTopology to use for the NetworkClient. Must be the same on host and client.</param>
 /// <param name="onFatalError">A method to call if something goes horribly wrong.</param>
 public static void InitializeHosting(int listenPort, GeographicRegion region = GeographicRegion.AUTO, Action <string, ushort> onPrepared = null, Action <string> onFatalError = null, bool forceRelayOnly = false)
 {
     _Init(listenPort, RegionURL.FromRegion(region), onPrepared, onFatalError, forceRelayOnly);
 }