Пример #1
0
        public override Transform Step(double time, LocationOptions options)
        {
            var dt = (float)(time - _time);
            var v  = _vel * dt + 0.5f * _acc * dt * dt;

            if (Vec3.Dot(v, v) == 0.0)
            {
                return(base.Step(time, options));
            }

            position = _pos + v;

            if (!options.RotationOptions.HasFlag(RotationOptions.AlignToVelocity))
            {
                return(base.Step(time, options));
            }

            v = _vel + _acc * dt;
            v.Normalize();

            var n = new Vector3(local_orientation.v13, local_orientation.v23, local_orientation.v33);
            var u = new Vector3(v.x, v.y, v.z);

            var proj = u - Vector3.Dot(u, n) * n;

            var north = new Vector3(local_orientation.v12, local_orientation.v22, local_orientation.v32);
            var dot   = Vector3.Dot(proj, north);
            var det   = Vector3.Dot(n, Vector3.Cross(north, proj));

            _euler.y = -(float)Math.Atan2(det, dot);

            return(base.Step(time, options));
        }
Пример #2
0
        private LocationRequest CreateRequest(LocationOptions options)
        {
            var request = LocationRequest.Create();

            request.SetSmallestDisplacement(options.MovementThreshold);
            request.SetPriority(GetPriority(options.Accuracy));
            request.SetInterval((long)options.ReportInterval.TotalMilliseconds);

            if (options.FastestInterval.HasValue)
            {
                request.SetFastestInterval((long)options.FastestInterval.Value.TotalMilliseconds);
            }


            if (options.NumberOfUpdates > 0 && options.NumberOfUpdates < int.MaxValue)
            {
                request.SetNumUpdates(options.NumberOfUpdates);
            }

            if (options.Duration != TimeSpan.MaxValue)
            {
                request.SetExpirationDuration((long)options.Duration.TotalMilliseconds);
            }

            return(request);
        }
Пример #3
0
        public async Task <Location> EditLocationAsync(int id, LocationOptions options, CancellationToken token = default)
        {
            var request = new RestRequest($"/api/application/users/{id}", Method.PATCH)
                          .AddJsonBody(options);

            var response = await HandleRequest <Location>(request, token);

            return(response);
        }
Пример #4
0
        public async Task <Location> CreateLocationAsync(LocationOptions options, CancellationToken token = default)
        {
            var request = new RestRequest($"/api/application/users", Method.POST)
                          .AddJsonBody(options);

            var response = await HandleRequest <Location>(request, token);

            return(response);
        }
 internal LocationRetrieverDialogBase(
     IGeoSpatialService geoSpatialService,
     LocationOptions options,
     LocationRequiredFields requiredFields,
     LocationResourceManager resourceManager) : base(resourceManager)
 {
     SetField.NotNull(out this.geoSpatialService, nameof(geoSpatialService), geoSpatialService);
     this.options        = options;
     this.requiredFields = requiredFields;
 }
Пример #6
0
 public FacebookNativeLocationRetrieverDialog(
     string prompt,
     IGeoSpatialService geoSpatialService,
     LocationOptions options,
     LocationRequiredFields requiredFields,
     LocationResourceManager resourceManager)
     : base(geoSpatialService, options, requiredFields, resourceManager)
 {
     SetField.NotNull(out this.prompt, nameof(prompt), prompt);
 }
Пример #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="apiKey">The geo spatial API key.</param>
 /// <param name="channelId">The channel identifier.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The location resource manager.</param>
 public LocationDialog(
     string apiKey,
     string channelId,
     string prompt,
     LocationOptions options = LocationOptions.None,
     LocationRequiredFields requiredFields   = LocationRequiredFields.None,
     LocationResourceManager resourceManager = null)
     : this(apiKey, channelId, prompt, new BingGeoSpatialService(), options, requiredFields, resourceManager)
 {
 }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="apiKey">The geo spatial API key.</param>
 /// <param name="channelId">The channel identifier.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The location resource manager.</param>
 public LocationDialog(
     string apiKey,
     string channelId,
     string prompt,
     LocationOptions options = LocationOptions.None,
     LocationRequiredFields requiredFields   = LocationRequiredFields.None,
     LocationResourceManager resourceManager = null)
     : this(new LocationDialogFactory(apiKey, channelId, prompt, ((!string.IsNullOrEmpty(apiKey) && apiKey.Length <= 60) ? (IGeoSpatialService) new AzureMapsSpatialService(apiKey) : new BingGeoSpatialService(apiKey)), options, requiredFields, resourceManager), new FavoritesManager(), resourceManager)
 {
     this.options = options;
 }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="apiKey">The geo spatial API key.</param>
 /// <param name="channelId">The channel identifier.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The location resource manager.</param>
 public LocationDialog(
     string apiKey,
     string channelId,
     string prompt,
     LocationOptions options = LocationOptions.None,
     LocationRequiredFields requiredFields   = LocationRequiredFields.None,
     LocationResourceManager resourceManager = null)
     : this(new LocationDialogFactory(apiKey, channelId, prompt, new GoogleGeocodingService(apiKey), options, requiredFields, resourceManager), new FavoritesManager(), resourceManager)
 {
     this.options = options;
 }
 public PathBuilding()
 {
     InitializeComponent();
     _ConnectorLine               = new Line();
     _ConnectorLine.Stroke        = new SolidColorBrush(Colors.DarkBlue);
     _ConnectorLine.Visibility    = System.Windows.Visibility.Hidden;
     _locationSelector            = new LocationOptions();
     _locationSelector.Visibility = System.Windows.Visibility.Hidden;
     DrawCanvas.Children.Add(_ConnectorLine);
     DrawCanvas.Children.Add(_locationSelector);
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="apiKey">The geo spatial API key.</param>
 /// <param name="channelId">The channel identifier.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The location resource manager.</param>
 /// <param name="announceDirectionsToUser">Flag to announce directions for the captured address.</param>
 /// <param name="destination">The destination address to use for turn by turn directions</param>
 public LocationDialog(
     string apiKey,
     string channelId,
     string prompt,
     LocationOptions options = LocationOptions.None,
     LocationRequiredFields requiredFields   = LocationRequiredFields.None,
     LocationResourceManager resourceManager = null, bool announceDirectionsToUser = false, string destination = "")
     : this(apiKey, channelId, prompt, new BingGeoSpatialService(), options, requiredFields, resourceManager)
 {
     announceDirections = announceDirectionsToUser;
     addressDestination = destination;
 }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="geoSpatialService">The Geo-Special Service.</param>
 /// <param name="cardBuilder">The card builder service.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="supportsKeyboard">Indicates whether channel supports keyboard buttons or not.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The resource manager.</param>
 internal RichLocationRetrieverDialog(
     string prompt,
     bool supportsKeyboard,
     ILocationCardBuilder cardBuilder,
     IGeoSpatialService geoSpatialService,
     LocationOptions options,
     LocationRequiredFields requiredFields,
     LocationResourceManager resourceManager,
     bool skipPrompt = false)
     : base(geoSpatialService, options, requiredFields, resourceManager)
 {
     SetField.NotNull(out this.cardBuilder, nameof(cardBuilder), cardBuilder);
     SetField.NotNull(out this.prompt, nameof(prompt), prompt);
     this.supportsKeyboard = supportsKeyboard;
     this.skipPrompt       = skipPrompt;
 }
Пример #13
0
 public FavoriteLocationRetrieverDialog(
     bool supportsKeyboard,
     IFavoritesManager favoritesManager,
     ILocationDialogFactory locationDialogFactory,
     ILocationCardBuilder cardBuilder,
     IGeoSpatialService geoSpatialService,
     LocationOptions options,
     LocationRequiredFields requiredFields,
     LocationResourceManager resourceManager)
     : base(geoSpatialService, options, requiredFields, resourceManager)
 {
     SetField.NotNull(out this.favoritesManager, nameof(favoritesManager), favoritesManager);
     SetField.NotNull(out this.locationDialogFactory, nameof(locationDialogFactory), locationDialogFactory);
     SetField.NotNull(out this.cardBuilder, nameof(cardBuilder), cardBuilder);
     this.supportsKeyboard = supportsKeyboard;
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LocationDialog"/> class.
 /// </summary>
 /// <param name="apiKey">The geo spatial API key.</param>
 /// <param name="channelId">The channel identifier.</param>
 /// <param name="prompt">The prompt posted to the user when dialog starts.</param>
 /// <param name="geoSpatialService">The geo spatial location service.</param>
 /// <param name="options">The location options used to customize the experience.</param>
 /// <param name="requiredFields">The location required fields.</param>
 /// <param name="resourceManager">The location resource manager.</param>
 internal LocationDialog(
     string apiKey,
     string channelId,
     string prompt,
     IGeoSpatialService geoSpatialService,
     LocationOptions options = LocationOptions.None,
     LocationRequiredFields requiredFields   = LocationRequiredFields.None,
     LocationResourceManager resourceManager = null) : base(resourceManager)
 {
     SetField.NotNull(out this.apiKey, nameof(apiKey), apiKey);
     SetField.NotNull(out this.prompt, nameof(prompt), prompt);
     SetField.NotNull(out this.channelId, nameof(channelId), channelId);
     SetField.NotNull(out this.geoSpatialService, nameof(geoSpatialService), geoSpatialService);
     this.options        = options;
     this.requiredFields = requiredFields;
 }
 internal LocationDialogFactory(
     string apiKey,
     string channelId,
     string prompt,
     IGeoSpatialService geoSpatialService,
     LocationOptions options,
     LocationRequiredFields requiredFields,
     LocationResourceManager resourceManager)
 {
     SetField.NotNull(out this.apiKey, nameof(apiKey), apiKey);
     SetField.NotNull(out this.channelId, nameof(channelId), channelId);
     SetField.NotNull(out this.prompt, nameof(prompt), prompt);
     this.geoSpatialService = geoSpatialService;
     this.options           = options;
     this.requiredFields    = requiredFields;
     this.resourceManager   = resourceManager ?? new LocationResourceManager();
 }
 public LocationInfoManager(IPublisherService publisherService,
                            IMapper mapper,
                            ILocationInfoDal locationInfoDal,
                            ICacheManager cacheManager,
                            IObjectDataConverter objectDataConverter,
                            IDistributedCache distributedCache,
                            IOptions <LocationOptions> locationOptions,
                            IOptions <RedisOptions> redisOptions)
 {
     _locationInfoDal     = locationInfoDal;
     _mapper              = mapper;
     _publisherService    = publisherService;
     _cacheManager        = cacheManager;
     _objectDataConverter = objectDataConverter;
     _distributedCache    = distributedCache;
     _locationOptions     = locationOptions.Value;
     _redisOptions        = redisOptions.Value;
 }
Пример #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped <ILocationOptions, LocationOptions>(x =>
            {
                var locationOptions = new LocationOptions();
                Configuration.Bind("Location", locationOptions);

                return(locationOptions);
            });

            // Services
            services.AddScoped <IMediaService, MediaService>();

            // Features
            services.AddScoped <IFeature <CreateMediaRequest, CreateMediaResponse>, CreateMediaFeature>();
        }
Пример #18
0
        protected bool Clamp(LocationOptions options)
        {
            var mapControl = MapControl.SystemMap;

            if (mapControl == null)
            {
                return(false);
            }

            var clampType = GroundClampType.NONE;

            if (options.PositionOptions == PositionOptions.Surface)
            {
                if (options.RotationOptions.HasFlag(RotationOptions.AlignToSurface))
                {
                    clampType = GroundClampType.GROUND_NORMAL_TO_SURFACE;
                }
                else
                {
                    clampType = GroundClampType.GROUND;
                }
            }

            var clampFlags = ClampFlags.DEFAULT;

            if (options.LoadOptions == LoadOptions.Load)
            {
                clampFlags = ClampFlags.WAIT_FOR_DATA;
            }

            if (options.QualityOptions == QualityOptions.Highest)
            {
                clampFlags |= ClampFlags.ISECT_LOD_QUALITY;
            }

            mapControl.UpdatePosition(this, clampType, clampFlags);

            return(true);
        }
Пример #19
0
        internal LocationDialogFactory(
            string apiKey,
            string channelId,
            string prompt,
            IGeoSpatialService geoSpatialService,
            LocationOptions options,
            LocationRequiredFields requiredFields,
            LocationResourceManager resourceManager)
        {
            SetField.NotNull(out this.apiKey, nameof(apiKey), apiKey);
            SetField.NotNull(out this.channelId, nameof(channelId), channelId);
            SetField.NotNull(out this.prompt, nameof(prompt), prompt);
            this.geoSpatialService = geoSpatialService;
            this.options           = options;
            this.requiredFields    = requiredFields;
            this.resourceManager   = resourceManager ?? new LocationResourceManager();

            if (!string.IsNullOrEmpty(this.apiKey) && this.apiKey.Length > 60)
            {
                useAzureMaps = false;
            }
        }
        public async void getCurrentPosition(
            JObject options,
            ICallback success,
            ICallback error)
        {
            var locationOptions = LocationOptions.FromJson(options);

            var geolocator = new Geolocator
            {
                DesiredAccuracy   = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default,
                MovementThreshold = locationOptions.DistanceFilter,
            };

            try
            {
                // TODO: Enable retrieval from position history using `MaximumAge` filter

                var task          = geolocator.GetGeopositionAsync().AsTask();
                var completedTask = await Task.WhenAny(
                    task,
                    Task.Delay(TimeSpan.FromMilliseconds(locationOptions.Timeout))).ConfigureAwait(false);

                if (completedTask == task)
                {
                    var geoposition = await task.ConfigureAwait(false);

                    success.Invoke(ConvertGeoposition(geoposition));
                }
                else
                {
                    error.Invoke("Location request timed out");
                }
            }
            catch (Exception ex)
            {
                error.Invoke($"Location request failed with exception: {ex}");
            }
        }
Пример #21
0
        virtual public Transform Step(double time, LocationOptions options)
        {
            Clamp(options);


            var up = new Vector3(normal.x, normal.y, -normal.z);


            Vector3 east = new Vector3(local_orientation.v11, local_orientation.v21, local_orientation.v31);;
            Vector3 north;

            if (options.RotationOptions.HasFlag(RotationOptions.AlignToSurface))
            {
                east  = Vector3.Normalize(east - (Vector3.Dot(east, up) * up));
                north = Vector3.Cross(east, up);
            }
            else
            {
                north = new Vector3(-local_orientation.v12, -local_orientation.v22, -local_orientation.v32);
            }

            var m = new Matrix4x4(east.X, east.Y, east.Z, 0,
                                  up.X, up.Y, up.Z, 0,
                                  north.X, north.Y, north.Z, 0,
                                  0, 0, 0, 1);

            var qm = Quaternion.CreateFromRotationMatrix(m);

            var r = qm * Rotation;

            return(new Transform
            {
                Pos = { X = (float)position.x, Y = (float)position.y, Z = (float)position.z },
                Rot = r
            });
        }
Пример #22
0
        /// <summary>
        /// Create a location observable using the specified options.
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public IObservable <LocationEvent> CreateObservable(LocationOptions options)
        {
            var rootObservable = CreateLocationObservable(options).Do(e => _lastEvent.OnNext(e));

            if (options.Duration < TimeSpan.MaxValue)
            {
                rootObservable = rootObservable.Timeout(DateTimeOffset.Now + options.Duration).
                                 Catch(Observable.Empty <LocationEvent>());
            }

            // if number of requests is limited then restrict lifetime of this observable
            if (options.NumberOfUpdates > 0 && options.NumberOfUpdates < int.MaxValue)
            {
                return(rootObservable.Take(options.NumberOfUpdates).
                       Publish().
                       RefCount());
            }
            else
            {
                return(rootObservable.
                       Publish().
                       RefCount());
            }
        }
        public void startObserving(JObject options)
        {
            var locationOptions = LocationOptions.FromJson(options);
            var geolocator      = new Geolocator
            {
                DesiredAccuracy   = locationOptions.HighAccuracy ? PositionAccuracy.High : PositionAccuracy.Default,
                MovementThreshold = locationOptions.DistanceFilter,
            };

            var positionObservable =
                Observable.FromEventPattern <
                    TypedEventHandler <Geolocator, PositionChangedEventArgs>,
                    Geolocator,
                    PositionChangedEventArgs>(
                    h => geolocator.PositionChanged += h,
                    h => geolocator.PositionChanged -= h);

            var positionQuery = from e in positionObservable
                                select e.EventArgs.Position;

            var positionSubscription = positionQuery.Subscribe(position =>
                                                               Context.GetJavaScriptModule <RCTDeviceEventEmitter>()
                                                               .emit("geolocationDidChange", ConvertGeoposition(position)));

            var statusObservable =
                Observable.FromEventPattern <
                    TypedEventHandler <Geolocator, StatusChangedEventArgs>,
                    Geolocator,
                    StatusChangedEventArgs>(
                    h => geolocator.StatusChanged += h,
                    h => geolocator.StatusChanged -= h);

            var statusQuery = from e in statusObservable
                              select e.EventArgs.Status;

            var statusSubscription = statusQuery.Subscribe(status =>
            {
                if (status == PositionStatus.Disabled)
                {
                    Context.GetJavaScriptModule <RCTDeviceEventEmitter>()
                    .emit("geolocationError", "Location settings are turned off.");
                }
                else if (status == PositionStatus.NotAvailable)
                {
                    Context.GetJavaScriptModule <RCTDeviceEventEmitter>()
                    .emit("geolocationError", "Location services is not available.");
                }
                else if (status == PositionStatus.NoData || status == PositionStatus.Initializing)
                {
                    Context.GetJavaScriptModule <RCTDeviceEventEmitter>()
                    .emit("geolocationError", "Location services is temporarily unavailable.");
                }
            });

            _currentSubscription.Disposable =
                new CompositeDisposable(2)
            {
                positionSubscription,
                statusSubscription,
            };
        }
        public LocationDialog(
            string apiKey,
            string prompt,
            BotState state,
            string dialogId         = DefaultLocationDialogId,
            bool skipPrompt         = false,
            bool useAzureMaps       = true,
            LocationOptions options = LocationOptions.None,
            LocationRequiredFields requiredFields   = LocationRequiredFields.None,
            LocationResourceManager resourceManager = null) : base(dialogId)
        {
            resourceManager = resourceManager ?? new LocationResourceManager();

            if (!options.HasFlag(LocationOptions.SkipFavorites) && state == null)
            {
                throw new ArgumentNullException(nameof(state),
                                                "If LocationOptions.SkipFavorites is not used then BotState object must be " +
                                                "provided to allow for storing / retrieval of favorites");
            }

            var favoriteLocations = state.CreateProperty <List <FavoriteLocation> >($"{nameof(LocationDialog)}.Favorites");
            var favoritesManager  = new FavoritesManager(favoriteLocations);

            IGeoSpatialService geoSpatialService;

            if (useAzureMaps)
            {
                geoSpatialService = new AzureMapsSpatialService(apiKey);
            }
            else
            {
                geoSpatialService = new BingGeoSpatialService(apiKey);
            }

            InitialDialogId = dialogId;

            AddDialog(new ChoicePrompt(PromptDialogIds.Choice));
            AddDialog(new TextPrompt(PromptDialogIds.Text));
            AddDialog(new ConfirmPrompt(PromptDialogIds.Confirm));

            AddDialog(new WaterfallDialog(InitialDialogId, new WaterfallStep[]
            {
                async(dc, cancellationToken) =>
                {
                    if (options.HasFlag(LocationOptions.SkipFavorites) ||
                        !favoritesManager.GetFavorites(dc.Context).Result.Any())
                    {
                        var isFacebookChannel = StringComparer.OrdinalIgnoreCase.Equals(
                            dc.Context.Activity.ChannelId, "facebook");

                        if (options.HasFlag(LocationOptions.UseNativeControl) && isFacebookChannel)
                        {
                            return(await dc.BeginDialogAsync(DialogIds.LocationRetrieverFacebookDialog));
                        }

                        return(await dc.BeginDialogAsync(DialogIds.LocationRetrieverRichDialog));
                    }

                    return(await dc.BeginDialogAsync(DialogIds.HeroStartCardDialog));
                },
                async(dc, cancellationToken) =>
                {
                    var selectedLocation = (Bing.Location)dc.Result;
                    dc.Values[StepContextKeys.SelectedLocation] = selectedLocation;

                    if (options.HasFlag(LocationOptions.SkipFinalConfirmation))
                    {
                        return(await dc.NextAsync());
                    }

                    await dc.PromptAsync(PromptDialogIds.Confirm,
                                         new PromptOptions()
                    {
                        Prompt = new Activity
                        {
                            Type = ActivityTypes.Message,
                            Text = string.Format(resourceManager.ConfirmationAsk,
                                                 selectedLocation.GetFormattedAddress(resourceManager.AddressSeparator))
                        },
                        RetryPrompt = new Activity
                        {
                            Type = ActivityTypes.Message,
                            Text = resourceManager.ConfirmationInvalidResponse
                        }
                    });

                    return(EndOfTurn);
                },
                async(dc, cancellationToken) =>
                {
                    if (dc.Result is bool result && !result)
                    {
                        await dc.Context.SendActivityAsync(resourceManager.ResetPrompt);
                        return(await dc.ReplaceDialogAsync(InitialDialogId));
                    }

                    if (!options.HasFlag(LocationOptions.SkipFavorites))
                    {
                        return(await dc.BeginDialogAsync(DialogIds.AddToFavoritesDialog,
                                                         new AddToFavoritesDialogOptions()
                        {
                            Location = (Bing.Location)dc.Values[StepContextKeys.SelectedLocation]
                        }
                                                         ));
                    }
                    else
                    {
                        await dc.NextAsync();
                    }

                    return(EndOfTurn);
                },
                async(dc, cancellationToken) =>
                {
                    var selectedLocation = (Bing.Location)dc.Values[StepContextKeys.SelectedLocation];
                    return(await dc.EndDialogAsync(CreatePlace(selectedLocation)));
                }
            }));
Пример #25
0
 public async Task <Location> EditLocationAsync(Location location, LocationOptions options, CancellationToken token = default)
 {
     return(await EditLocationAsync(location.Id, options, token));
 }
Пример #26
0
 internal LocationOptionsResponse(LocationOptions locationOptions)
 {
     LocationOptions = locationOptions;
 }
        public LocationDialog(
            string apiKey,
            string prompt,
            bool skipPrompt         = false,
            bool useAzureMaps       = true,
            LocationOptions options = LocationOptions.None,
            LocationRequiredFields requiredFields   = LocationRequiredFields.None,
            LocationResourceManager resourceManager = null) : base(MainDialogId)
        {
            resourceManager = resourceManager ?? new LocationResourceManager();
            var favoritesManager = new FavoritesManager();

            IGeoSpatialService geoSpatialService;

            if (useAzureMaps)
            {
                geoSpatialService = new AzureMapsSpatialService(apiKey);
            }
            else
            {
                geoSpatialService = new BingGeoSpatialService(apiKey);
            }

            Dialogs.Add(Inputs.Choice, new ChoicePrompt(Culture.English));
            Dialogs.Add(Inputs.Text, new TextPrompt());
            Dialogs.Add(Inputs.Confirm, new ConfirmPrompt(Culture.English));

            Dialogs.Add(MainDialogId, new WaterfallStep[]
            {
                async(dc, args, next) =>
                {
                    if (options.HasFlag(LocationOptions.SkipFavorites) ||
                        !favoritesManager.GetFavorites(dc.Context).Result.Any())
                    {
                        var isFacebookChannel = StringComparer.OrdinalIgnoreCase.Equals(
                            dc.Context.Activity.ChannelId, "facebook");

                        if (options.HasFlag(LocationOptions.UseNativeControl) && isFacebookChannel)
                        {
                            await dc.Begin(DialogIds.LocationRetrieverFacebookDialog);
                        }
                        else
                        {
                            await dc.Begin(DialogIds.LocationRetrieverRichDialog);
                        }
                    }
                    else
                    {
                        await dc.Begin(DialogIds.HeroStartCardDialog);
                    }
                },
                async(dc, args, next) =>
                {
                    Bing.Location selectedLocation = (Bing.Location)args[Outputs.SelectedLocation];
                    dc.ActiveDialog.State[Outputs.SelectedLocation] = selectedLocation;

                    if (options.HasFlag(LocationOptions.SkipFinalConfirmation))
                    {
                        await next();
                    }
                    else
                    {
                        await dc.Prompt(Inputs.Confirm,
                                        string.Format(resourceManager.ConfirmationAsk,
                                                      selectedLocation.GetFormattedAddress(resourceManager.AddressSeparator)),
                                        new PromptOptions()
                        {
                            RetryPromptString = resourceManager.ConfirmationInvalidResponse
                        });
                    }
                },
                async(dc, args, next) =>
                {
                    if (args is ConfirmResult result && !result.Confirmation)
                    {
                        await dc.Context.SendActivity(resourceManager.ResetPrompt);
                        await dc.Replace(MainDialogId);
                    }
Пример #28
0
        private IObservable <LocationEvent> CreateLocationObservable(LocationOptions options)
        {
            return(Observable.Create <LocationEvent>(async(o) =>
            {
                var lc = new MyLocationCallback((lr) =>
                {
                    foreach (var item in lr.Locations)
                    {
                        double?verticalAccuracy = null;

                        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                        {
                            if (item.HasVerticalAccuracy)
                            {
                                verticalAccuracy = item.VerticalAccuracyMeters;
                            }
                        }

                        var location = new Location(item.Latitude, item.Longitude,
                                                    item.HasAccuracy ? item.Accuracy : (double?)null,
                                                    item.HasAltitude ? item.Altitude : (double?)null,
                                                    verticalAccuracy,
                                                    item.HasBearing ? item.Bearing : (double?)null,
                                                    item.HasSpeed ? item.Speed : (double?)null);

                        DateTimeOffset dto;

                        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr1)
                        {
                            var en = item.ElapsedRealtimeNanos;

                            var sn = SystemClock.ElapsedRealtimeNanos();

                            var age = (sn - en) / 1000000;

                            dto = DateTimeOffset.FromUnixTimeMilliseconds(
                                DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - age);
                        }
                        else
                        {
                            dto = DateTimeOffset.Now;
                        }

                        var locationEvent = new LocationEvent(dto, location);

                        o.OnNext(locationEvent);
                    }
                });


                var request = CreateRequest(options);

                await _fusedLocationProviderClient.RequestLocationUpdatesAsync(request, lc, _context.MainLooper).ConfigureAwait(false);

                Interlocked.Increment(ref NoActiveObservables);

                return Disposable.Create(() =>
                {
                    Interlocked.Decrement(ref NoActiveObservables);

                    _fusedLocationProviderClient.RemoveLocationUpdates(lc);
                });
            }));
        }