Exemplo n.º 1
0
        public async Task <Point> GetAddressCoordinates(string address)
        {
            var mapsKey = Environment.GetEnvironmentVariable("AZURE_MAPS_KEY");
            var amSvc   = new AzureMapsServices(mapsKey);
            var request = new SearchAddressRequest {
                Query = address, Limit = 10
            };
            var response = await amSvc.GetSearchAddress(request);

            if (response.Error != null)
            {
                throw new Exception(response.Error.Error.Message);
            }

            if (response.Result.Results?.Length > 0)
            {
                var bestResult = response.Result.Results
                                 .OrderByDescending(r => r.Score)
                                 .First();

                return(new Point(bestResult.Position.Lon, bestResult.Position.Lat));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 2
0
        public static int FindRange(string area, FilterDeal filterDeal)
        {
            string[] result = null;
            PostPointInPolygonRequest req = new PostPointInPolygonRequest
            {
                ApiVersion = "1.0",
                Lon        = filterDeal.LocationDto.Longitude,
                Lat        = filterDeal.LocationDto.Latitude,
            };
            var am = new AzureMapsServices(Constants.AZUREMAPKEY);

            try
            {
                var response = am.PostPointInPolygon(req, area);



                result = response.Result.Result.Result.IntersectingGeometries;
            }
            catch (Exception ex)
            {
                throw new Exception(nameof(FindRange), ex);
            }
            if (result == null || result.Length == 0)
            {
                return(0);
            }

            return(1);
        }
Exemplo n.º 3
0
        private static async Task <Response <BufferResponse> > FetchBuffer(string body)
        {
            try
            {
                AzureMapsServices am = new AzureMapsServices(Constants.AZUREMAPKEY);
                var buffer           = await am.PostBuffer(body);

                return(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception(nameof(FetchBuffer), ex);
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            rand = new Random();
            colorMessage($"Starting {truckIdentification}", ConsoleColor.Yellow);
            currentLat = baseLat;
            currentLon = baseLon;

            // Connect to Azure Maps.
            azureMapsServices = new AzureMapsServices(AzureMapsKey);

            try
            {
                using (var security = new SecurityProviderSymmetricKey(DeviceID, PrimaryKey, null))
                {
                    DeviceRegistrationResult result = RegisterDeviceAsync(security).GetAwaiter().GetResult();
                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        Console.WriteLine("Failed to register device");
                        return;
                    }
                    IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());
                    s_deviceClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                }
                greenMessage("Device successfully connected to Azure IoT Central");

                SendDevicePropertiesAsync().GetAwaiter().GetResult();

                Console.Write("Register settings changed handler...");
                s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(HandleSettingChanged, null).GetAwaiter().GetResult();
                Console.WriteLine("Done");

                cts = new CancellationTokenSource();

                // Create a handler for the direct method calls.
                s_deviceClient.SetMethodHandlerAsync("GoToCustomer", CmdGoToCustomer, null).Wait();
                s_deviceClient.SetMethodHandlerAsync("Recall", CmdRecall, null).Wait();

                SendTruckTelemetryAsync(rand, cts.Token);

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                cts.Cancel();
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 5
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            string coordinates = (string)value;

            if (!CoordinatesRegex.IsMatch(coordinates))
            {
                return(new ValidationResult("The coordinates format isn't valid."));
            }

            // Check that the coordinates correspond to a valid location
            AzureMapsServices mapsClient = validationContext.GetService <AzureMapsServices>();
            Response <SearchAddressReverseResponse> searchAddressReverseResponse =
                mapsClient.GetSearchAddressReverse(new SearchAddressReverseRequest {
                Query = coordinates, Language = "en-US"
            }).Result;

            if (searchAddressReverseResponse.Error != null)
            {
                return(new ValidationResult("Unable to perform location validation with Azure Maps."));
            }

            SearchResultAddress searchResultAddress =
                searchAddressReverseResponse.Result.Addresses[0].Address;

            if (searchResultAddress.Municipality == null || searchResultAddress.Municipality == string.Empty)
            {
                return(new ValidationResult("These coordinates do not match any city."));
            }

            // Set the additional info about the location
            PropertyInfo cityFieldInfo = validationContext.ObjectType.GetProperty(_cityField);

            cityFieldInfo.SetValue(validationContext.ObjectInstance, searchResultAddress.Municipality);

            PropertyInfo stateFieldInfo = validationContext.ObjectType.GetProperty(_stateField);

            stateFieldInfo.SetValue(validationContext.ObjectInstance, searchResultAddress.Country);

            return(ValidationResult.Success);
        }
        //public async Task<IActionResult> OnPostAsyncOFF()
        //{
        //    return Page();
        //}
        public async Task <IActionResult> OnPostAsync()
        {
            billingloginS = _BillingData.GetSubscriber_IDlogin(User.Identity.Name);
            if (billingloginS == null)
            {
                return(RedirectToPage("/identity/account/login"));
            }
            int Subscriber_ID = 0;


            Subscriber_ID = billingloginS.Subscriber_ID;


            if (Subscriber_ID > 0)
            {
                IOTDEviceDetail = _DeviceData.GetIOTDEviceDetailsBySubscriberId(Subscriber_ID);
            }
            if (IOTDEviceDetail == null)
            {
                return(RedirectToPage("/Error"));
            }

            rand = new Random();
            colorMessage($"Starting {truckIdentification}", ConsoleColor.Yellow);
            currentLat = baseLat;
            currentLon = baseLon;

            // Connect to Azure Maps.
            azureMapsServices = new AzureMapsServices(AzureMapsKey);

            try
            {
                //using (var security = new SecurityProviderSymmetricKey(DeviceID, PrimaryKey, null))
                using (var security = new SecurityProviderSymmetricKey(IOTDEviceDetail.IOTDEviceId, IOTDEviceDetail.PrimaryKey, null))
                {
                    DeviceRegistrationResult result = RegisterDeviceAsync(security).GetAwaiter().GetResult();
                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        //Console.WriteLine("Failed to register device");
                        Message = "Failed to register device";
                        return(Page());
                    }
                    IAuthenticationMethod auth = new DeviceAuthenticationWithRegistrySymmetricKey(result.DeviceId, (security as SecurityProviderSymmetricKey).GetPrimaryKey());
                    s_deviceClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt_WebSocket_Only);
                }
                Message = "Failed to register device";
                greenMessage("Device connected successfully");

                SendDevicePropertiesAsync().GetAwaiter().GetResult();

                //Console.Write("Register settings changed handler...");
                Message = "Register settings changed handler...";
                s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(HandleSettingChanged, null).GetAwaiter().GetResult();
                //Console.WriteLine("Done");
                Message = "Done Successful";

                cts = new CancellationTokenSource();

                // Create a handler for the direct method calls.
                s_deviceClient.SetMethodHandlerAsync("GoToCustomer", CmdGoToCustomer, null).Wait();
                s_deviceClient.SetMethodHandlerAsync("Recall", CmdRecall, null).Wait();

                SendTruckTelemetryAsync(rand, cts.Token);

                //Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                cts.Cancel();
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine(ex.Message);
            }

            TempData["msg"] = Message;
            return(Page());
        }
Exemplo n.º 7
0
 public StoreScraper(string azureMapsKey)
 {
     _azureMaps = new AzureMapsServices(azureMapsKey);
 }
Exemplo n.º 8
0
 public AzureMapsGeocodingProvider(IConfiguration config)
 {
     _mapService = new AzureMapsServices(config["AzureMapsKey"]);
 }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Configure Database Context
            services.AddDbContext <DatabaseContext>(options => {
                options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DATABASE_CONNECTION_STRING"));
            });

            // Configure Azure Blob Storage
            BlobServiceClient blobServiceClient =
                new BlobServiceClient(Configuration.GetConnectionString("STORAGE_CONNECTION_STRING"));
            BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("trees");

            if (!containerClient.Exists())
            {
                containerClient.Create();
                containerClient.SetAccessPolicy(PublicAccessType.Blob);
            }

            services.AddSingleton <BlobServiceClient>(blobServiceClient);

            // Configure Azure Content Moderator
            string contentModeratorKey      = Configuration["CONTENT_MODERATOR_KEY"];
            string contentModeratorEndpoint = Configuration["CONTENT_MODERATOR_ENDPOINT"];

            ServiceClientCredentials contentModeratorCredentials =
                new Microsoft.Azure.CognitiveServices.ContentModerator.ApiKeyServiceClientCredentials(contentModeratorKey);

            ContentModeratorClient contentModeratorClient =
                new ContentModeratorClient(contentModeratorCredentials);

            contentModeratorClient.Endpoint = contentModeratorEndpoint;

            services.AddSingleton <ContentModeratorClient>(contentModeratorClient);

            // Configure Computer Vision for Image Recognition
            string computerVisionKey      = Configuration["COMPUTER_VISION_KEY"];
            string computerVisionEndpoint = Configuration["COMPUTER_VISION_ENDPOINT"];

            ServiceClientCredentials computerVisionCredentials =
                new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ApiKeyServiceClientCredentials(computerVisionKey);

            ComputerVisionClient computerVisionClient =
                new ComputerVisionClient(computerVisionCredentials);

            computerVisionClient.Endpoint = computerVisionEndpoint;

            services.AddSingleton <ComputerVisionClient>(computerVisionClient);

            // Configure Azure Maps client
            AzureMapsServices mapsClient = new AzureMapsServices(Configuration["MAPS_KEY"]);

            services.AddSingleton <AzureMapsServices>(mapsClient);

            // Add authentication
            services.AddAuthentication(options =>
            {
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = Configuration["JWT_ISSUER"],
                    ValidAudience    = Configuration["JWT_AUDIENCE"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_SIGN_KEY"]))
                };
            })
            .AddFacebook(options =>
            {
                options.ClientId     = Configuration["FACEBOOK_APP_ID"];
                options.ClientSecret = Configuration["FACEBOOK_APP_SECRET"];
                options.SaveTokens   = true;
            });

            // Add controllers
            services.AddControllers();
        }