Exemple #1
0
        private void DbQuery_with_TVFs_mapped_to_context_instance_methods_involving_spatial_types_works(
            Func <IQueryable <IQueryable <SupplierWithLocation> >, List <IQueryable <SupplierWithLocation> > > toList)
        {
            using (var context = new SpatialNorthwindContext(_connectionString))
            {
                var suppliers = toList(
                    from x in context.Suppliers
                    select
                    context.SuppliersWithinRange(
                        1000,
                        DbGeography.FromText(
                            "POINT(-122.335576 47.610676)",
                            4326)));

                Assert.Equal(16, suppliers.Count);
            }
        }
        public async Task <ActionResult> Create(EventCreateViewModel eventViewModel)
        {
            if (ModelState.IsValid)
            {
                var sportTask     = DbContext.Sports.SingleAsync(s => s.Name == eventViewModel.Sport);
                var eventTypeTask = DbContext.EventTypes.SingleAsync(e => e.Name == eventViewModel.EventType);
                var iconLinkTask  = PictureService.CreateLink(eventViewModel.Icon);
                var picturesTask  = PictureService.CreateLinks(eventViewModel.Picture);
                var organizerTask = DbContext.Users.SingleAsync(e => e.Id == User.Identity.GetUserId());
                await Task.WhenAll(sportTask, eventTypeTask, iconLinkTask, picturesTask);

                var sport     = sportTask.Result;
                var eventType = eventTypeTask.Result;

                var iconLink    = iconLinkTask.Result;
                var pictures    = picturesTask.Result;
                var organizer   = organizerTask.Result;
                var coordinates = DbGeography.FromText(eventViewModel.Latitude?.ToString() + eventViewModel.Longitude?.ToString());
                if (sport == null)
                {
                    sport = new Sport()
                    {
                        Name = eventViewModel.Sport
                    };
                    DbContext.Sports.Add(sport);
                }
                if (eventType == null)
                {
                    eventType = new EventType()
                    {
                        Name = eventViewModel.EventType
                    };
                    DbContext.EventTypes.Add(eventType);
                }
                var @event = new Event()
                {
                    BeginDate = eventViewModel.BeginDate, EndDate = eventViewModel.EndDate, Description = eventViewModel.Description, Details = eventViewModel.Details, Sport = sport, EventType = eventType, ExternalLink = eventViewModel.ExternalLink, Pictures = pictures, StartingPrice = eventViewModel.StartingPrice, VideoLink = eventViewModel.VideoLink, Organizer = organizer, Coordinates = coordinates
                };
                await Repository.Events.AddAsync(@event);

                return(RedirectToAction("Index"));
            }

            return(View(eventViewModel));
        }
Exemple #3
0
        public ActionResult Add(List <Participante> listaparticipante)
        {
            JsonResult jsonResult;

            //Verifica se o registro é inválido e se sim, retorna com erro.
            if (listaparticipante == null)
            {
                jsonResult = Json(new
                {
                    codigo = -1
                }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                MA_PARTICIPANTE participante = new MA_PARTICIPANTE();

                participante.cod_usuario    = listaparticipante[0].CodUsuario;
                participante.cod_campus     = listaparticipante[0].CodParticipante;
                participante.nome           = listaparticipante[0].Nome;
                participante.telefone       = listaparticipante[0].Telefone;
                participante.dt_nascimento  = (DateTime)listaparticipante[0].DtNascimento;
                participante.geolocalizacao = DbGeography.FromText("POINT(" + GestorDeAplicacao.RetornaDadoSemVigurla(listaparticipante[0].Latitude.ToString()) + "  " + GestorDeAplicacao.RetornaDadoSemVigurla(listaparticipante[0].Longitude.ToString()) + ")");

                try
                {
                    Boolean resultado = GestorDeParticipante.InserirParticipanteComRetorno(participante);

                    jsonResult = Json(new
                    {
                        codigo = participante.cod_participante
                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception e)
                {
                    jsonResult = Json(new
                    {
                        erro   = e.InnerException.ToString(),
                        codigo = -1
                    }, JsonRequestBehavior.AllowGet);
                }
            }

            jsonResult.MaxJsonLength = int.MaxValue;
            return(jsonResult);
        }
        public async Task <List <ArmedTrapResult> > ListArmedTraps(float latitude, float longitude, string userId)
        {
            List <ArmedTrapResult> response = new List <ArmedTrapResult>();

            DbGeography searchLocation = DbGeography.FromText(string.Format("POINT({0} {1})", longitude.ToString(CultureInfo.InvariantCulture), latitude.ToString(CultureInfo.InvariantCulture)));

            var armedTraps = await
                                 (from armedTrap in AppRepository.EntitiesContext.ArmedTraps
                                 where
                                 !armedTrap.Disarmed &&
                                 armedTrap.User.Id != new Guid(userId)
                                 select new
            {
                Id        = armedTrap.Id,
                Date      = armedTrap.Date,
                UserId    = armedTrap.User.Id,
                Latitude  = armedTrap.Latitude,
                Longitude = armedTrap.Longitude,
                NameKey   = armedTrap.NameKey,
                Distance  = searchLocation.Distance(
                    DbGeography.FromText("POINT(" + armedTrap.Longitude + " " + armedTrap.Latitude + ")"))
            })
                             .OrderBy(a => a.Distance)
                             .Where(a => a.Distance < 500)
                             .ToListAsync();

            if (armedTraps != null)
            {
                foreach (var armedTrap in armedTraps)
                {
                    ArmedTrapResult armedTrapResponse = new ArmedTrapResult();

                    armedTrapResponse.Date      = armedTrap.Date;
                    armedTrapResponse.Id        = armedTrap.Id.ToString();
                    armedTrapResponse.Latitude  = armedTrap.Latitude;
                    armedTrapResponse.Longitude = armedTrap.Longitude;
                    armedTrapResponse.NameKey   = armedTrap.NameKey;
                    armedTrapResponse.UserId    = armedTrap.UserId.ToString();

                    response.Add(armedTrapResponse);
                }
            }

            return(response);
        }
Exemple #5
0
        public ActionResult ObterUltimosUploads(int?ultimoId, string latitude, string longitude)
        {
            if (string.IsNullOrWhiteSpace(latitude) || string.IsNullOrWhiteSpace(longitude))
            {
                return(Json(new { TemResultado = false }, JsonRequestBehavior.AllowGet));
            }

            int         distanciEmKm = 2 * 1000 * 1000; // 2 mil km
            DbGeography localizacao  = DbGeography.FromText(string.Format("POINT({0} {1})", longitude, latitude));

            IQueryable <Arquivo> consulta = from e in bancoDeDados.Arquivos
                                            let distance = e.Localizacao.Distance(localizacao)
                                                           where distance <= distanciEmKm
                                                           select e;

            if (ultimoId.HasValue)
            {
                consulta = consulta.Where(e => e.Id > ultimoId);
            }

            consulta = consulta.OrderByDescending(e => e.Timestamp).Take(100);

            var resultadoDaConsulta = consulta
                                      .ToList()
                                      .Select(e => new
            {
                UrlFotoDoFacebook = e.ObterUrlDaFotoDoFacebook(16),
                Timestamp         = e.Timestamp.ToString(),
                e.FacebookNome,
                e.Status,
                e.UrlImagem,
                e.Localizacao.Latitude,
                e.Localizacao.Longitude,
                e.Id
            });

            var resultado = new
            {
                Items        = resultadoDaConsulta,
                UltimoId     = resultadoDaConsulta.Any() ? resultadoDaConsulta.Max(e => e.Id) : (int?)null,
                TemResultado = resultadoDaConsulta.Any()
            };

            return(Json(resultado, JsonRequestBehavior.AllowGet));
        }
Exemple #6
0
        public override void LoadFromEntity(Facility entity)
        {
            base.LoadFromEntity(entity);

            Name        = entity.Name;
            Description = entity.Description;
            Images      = entity.Images;

            if (entity.Site != null)
            {
                Site = Mapper.Map <Site, SiteDto>(entity.Site);
            }

            if (entity.Location != null)
            {
                Location = DbGeography.FromText(entity.Location.AsText());
            }
        }
Exemple #7
0
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return(default(DbGeography));
        }

        var jObject = JObject.Load(reader);

        if (!jObject.HasValues || (jObject.Property(LATITUDE_KEY) == null || jObject.Property(LONGITUDE_KEY) == null))
        {
            return(default(DbGeography));
        }

        string wkt = string.Format(CultureInfo.InvariantCulture, "POINT({1} {0})", jObject[LATITUDE_KEY], jObject[LONGITUDE_KEY]);

        return(DbGeography.FromText(wkt, DbGeography.DefaultCoordinateSystemId));
    }
Exemple #8
0
        public void CreateMappings(IMapperConfigurationExpression configuration)
        {
            configuration.CreateMap <JpegMetadata, JpegMetadataDto>()
            .ForMember(dto => dto.Id, bo => bo.MapFrom(s => s.Id))
            .ForMember(dto => dto.PlaceId, bo => bo.MapFrom(s => s.Comments))
            .ForMember(dto => dto.Caption, bo => bo.MapFrom(s => Path.GetFileNameWithoutExtension(s.FileInfo.Name)))
            .ForMember(dto => dto.DateTaken, bo => bo.MapFrom(s => s.DateTaken))
            .ForMember(dto => dto.DateCreated, bo => bo.MapFrom(s => s.FileInfo.LastWriteTime))
            .ForMember(dto => dto.Image, bo => bo.MapFrom(s => s.FileInfo))
            .ForMember(dto => dto.GPSLocation, bo => bo.MapFrom(s => s.Latitude.HasValue && s.Longitude.HasValue ?
                                                                DbGeography.FromText(string.Format(CultureInfo.InvariantCulture, "POINT({1} {0})", s.Latitude.ToString(), s.Longitude.ToString()), DbGeography.DefaultCoordinateSystemId) : default(DbGeography)));

            configuration.CreateMap <JpegMetadataDto, JpegMetadata>()
            .ForMember(bo => bo.Comments, dto => dto.MapFrom(s => s.PlaceId))
            .ForMember(bo => bo.DateTaken, dto => dto.MapFrom(s => s.DateTaken))
            .ForMember(bo => bo.Latitude, dto => dto.MapFrom(s => s.GPSLocation != null ? s.GPSLocation.Latitude : null))
            .ForMember(bo => bo.Longitude, dto => dto.MapFrom(s => s.GPSLocation != null ? s.GPSLocation.Longitude : null));
        }
Exemple #9
0
        private void SarvarInformacoesNoBancoDeDados(string status, string latitude, string longitude, string caminhoDaImagem)
        {
            ClaimsIdentity identidade = (ClaimsIdentity)User.Identity;

            Arquivo arquivo = new Arquivo();

            arquivo.Status    = status;
            arquivo.UrlImagem = caminhoDaImagem;
            arquivo.Timestamp = DateTime.Now;

            arquivo.FacebookId   = identidade.Claims.FirstOrDefault(c => c.Type == "FacebookId").Value;
            arquivo.FacebookNome = identidade.Claims.FirstOrDefault(c => c.Type == "FacebookNome").Value;

            arquivo.Localizacao = DbGeography.FromText(string.Format("POINT({0} {1})", longitude, latitude));

            bancoDeDados.Arquivos.Add(arquivo);
            bancoDeDados.SaveChanges();
        }
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     //Validations code here
     //...............
     //To save in database
     using (var context = new SampleDBEntities()){
         context.PlaceInfoes.Add(new PlaceInfo()
         {
             Name        = txtName.Text,
             Address     = txtAddress.Text,
             City        = txtCity.Text,
             State       = txtState.Text,
             CountryId   = Convert.ToInt32(ddlCountry.SelectedValue),
             Geolocation = DbGeography.FromText("POINT( " + hdnLocation.Value + ")")
         });
         context.SaveChanges();
     }
 }
Exemple #11
0
        public ActionResult GetNearCustomers(string Current)
        {
            using (ApplicationDbContext db_context = new ApplicationDbContext())
            {
                var currentLocation = DbGeography.FromText(Current);

                //var currentLocation = DbGeography.FromText("POINT( 78.3845534 17.4343666 )");



                //var places = (from u in db_context.Locations
                //              orderby u.Geolocation.Distance(currentLocation)
                //              select u).Take(1).Select(x => new TaxiNavigator.Models.Location() { Name = x.Name, lat = x.Geolocation.Latitude, lng = x.Geolocation.Longitude, Distance = x.Geolocation.Distance(currentLocation) });
                var nearschools = GetCustomerLocation(currentLocation, db_context);

                return(Json(nearschools, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #12
0
        public static DbGeography GetNextLoc(string directions)
        {
            OrderDirections obj = JsonConvert.DeserializeObject <OrderDirections>(directions);

            if (obj.last_id == obj.list.Count)
            {
                return(null);
            }
            else
            {
                string      lat   = obj.list.Where(x => x.id == obj.next_id).First().lat;
                string      lon   = obj.list.Where(x => x.id == obj.next_id).First().lon;
                var         point = string.Format("POINT({1} {0})", lat, lon);
                DbGeography loc   = DbGeography.FromText(point);

                return(loc);
            }
        }
Exemple #13
0
        public static void SpatialDataType()
        {
            Console.WriteLine("*** SpatialDataType Starts ***");

            using (var context = new SchoolDBEntities())
            {
                context.Database.Log = Console.Write;
                //Add Location using System.Data.Entity.Spatial.DbGeography
                context.Courses.Add(new Course()
                {
                    CourseName = "New Course from SpatialDataTypeDemo", Location = DbGeography.FromText("POINT(-122.360 47.656)")
                });

                context.SaveChanges();
            }

            Console.WriteLine("*** SpatialDataTypeDemo Ends ***");
        }
Exemple #14
0
        public void Verify_TVFs_returning_complex_values_work()
        {
            DbGeography londonLocation = DbGeography.FromText("POINT(-0.5 51.50)");

            using (var context = new NorthwindEntities())
            {
                var suppliersNearLondon = context.fx_SuppliersWithinRange(500, londonLocation).ToList();

                Assert.Equal(7, suppliersNearLondon.Count);
                Assert.Contains(1, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(12, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(13, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(18, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(22, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(27, suppliersNearLondon.Select(s => s.SupplierID));
                Assert.Contains(28, suppliersNearLondon.Select(s => s.SupplierID));
            }
        }
Exemple #15
0
        public void Generate_can_output_add_column_for_geography_type_with_default_value()
        {
            var generatedMigration
                = new CSharpMigrationCodeGenerator().Generate(
                      "Migration",
                      new[]
            {
                new AddColumnOperation(
                    "T",
                    new ColumnModel(PrimitiveTypeKind.Geography)
                {
                    IsNullable   = false,
                    Name         = "C",
                    DefaultValue = DbGeography.FromText("POINT (6 7)")
                })
            },
                      "Source",
                      "Target",
                      "Foo",
                      "Bar");

            Assert.Equal(
                @"namespace Foo
{
    using System;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Spatial;
    
    public partial class Bar : DbMigration
    {
        public override void Up()
        {
            AddColumn(""T"", ""C"", c => c.Geography(nullable: false, defaultValue: DbGeography.FromText(""POINT (6 7)"", 4326)));
        }
        
        public override void Down()
        {
            DropColumn(""T"", ""C"");
        }
    }
}
",
                generatedMigration.UserCode);
        }
Exemple #16
0
        public static void SpatialDataTypeDemo()
        {
            Console.WriteLine("*** SpatialDataTypeDemo Start ***");
            using (var ctx = new SchoolDBEntities())
            {
                Debug.WriteLine("*** SpatialDataTypeDemo Start ***");
                ctx.Database.Log = s => Debug.WriteLine(s);
                //Add Location using System.Data.Entity.Spatial.DbGeography
                ctx.Courses.Add(new Course()
                {
                    CourseName = "New Course from SpatialDataTypeDemo",
                    Location   = DbGeography.FromText("POINT(-122.360 47.656)")
                });

                ctx.SaveChanges();
            }

            Console.WriteLine("*** SpatialDataTypeDemo Finished ***");
        }
Exemple #17
0
        /// <summary>
        /// Ajax call to retrive the nearest locations for the given location
        /// </summary>
        /// <param name="lat">latitude</param>
        /// <param name="lng">longitude</param>
        /// <returns>json data of the nearest locations</returns>
        public ActionResult GetNearByLocations(string Currentlat, string Currentlng)
        {
            using (var context = new POC_gmapsEntities())
            {
                var currentLocation = DbGeography.FromText("POINT( " + Currentlng + " " + Currentlat + " )");

                //var currentLocation = DbGeography.FromText("POINT( 78.3845534 17.4343666 )");

                var places = (from u in context.SchoolInfoes
                              orderby u.GeoLocation.Distance(currentLocation)
                              select u).Take(4).Select(x => new Googlemaps.Models.SchoolInfo()
                {
                    Name = x.SchoolName, lat = x.GeoLocation.Latitude, lng = x.GeoLocation.Longitude, Distance = x.GeoLocation.Distance(currentLocation)
                });
                var nearschools = places.ToList();

                return(Json(nearschools, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #18
0
        public List <PatrolLastLocationDTO> GetNearByPatrolsByLatLon(double Longitude, double Latitude, double Radius, int patrolsCount)
        {
            try
            {
                var         strPoint       = string.Format("POINT({0} {1})", Longitude, Latitude);
                DbGeography pointGeography = DbGeography.FromText(strPoint);
                DbGeography dbGeography    = DbGeography.FromText(strPoint).Buffer(Radius);

                var lstPatrols = (from patrol in operationalDataContext.PatrolLastLocationViews
                                  where ((!patrol.IsInTFM.HasValue) || patrol.IsInTFM.Value)
                                  // where patrol.GeoLocation.Intersects(dbGeography)
                                  orderby patrol.GeoLocation.Distance(pointGeography)
                                  select new PatrolLastLocationDTO
                {
                    Altitude = patrol.Altitude,
                    Latitude = patrol.Latitude,
                    LocationDate = patrol.LocationDate,
                    Longitude = patrol.Longitude,
                    PatrolCode = patrol.PatrolCode,
                    PatrolId = patrol.PatrolId,
                    PatrolLatLocationId = patrol.PatrolLatLocationId,
                    Speed = patrol.Speed,
                    IsNoticed = patrol.IsNoticed,
                    StatusId = patrol.StatusId,
                    StatusName = patrol.StatusName,
                    PatrolOriginalId = patrol.PatrolOriginalId,
                    PatrolPlateNo = patrol.PatrolPlateNo,
                    isPatrol = patrol.IsPatrol.HasValue ? patrol.IsPatrol.Value : true,
                    OfficerName = patrol.OfficerName,
                    PatrolImage = patrol.PatrolImage,
                    CurrentTaskId = patrol.CurrentTaskId.HasValue ? patrol.CurrentTaskId.Value : 0
                }).Take(patrolsCount).ToList();


                return(lstPatrols);
            }
            catch (Exception ex)
            {
                Utility.WriteLog(ex, @"C:\STC\Websites\Server\WCF\");
            }

            return(null);
        }
Exemple #19
0
        private static string approach_two(string wkt)
        {
            //First, get the area defined by the well-known text using left-hand rule
            var sqlGeography =
                SqlGeography.STGeomFromText(new SqlChars(wkt), DbGeography.DefaultCoordinateSystemId).MakeValid();

            //Now get the inversion of the above area
            var invertedSqlGeography = sqlGeography.ReorientObject();

            //Whichever of these is smaller is the enclosed polygon, so we use that one.
            if (sqlGeography.STArea() > invertedSqlGeography.STArea())
            {
                sqlGeography = invertedSqlGeography;
            }
            var sqlGeographyAsString = sqlGeography.ToString();
            var returnValue          = DbGeography.FromText(sqlGeographyAsString).AsText();

            return(returnValue);
        }
        public void Generate_can_output_alter_geography_column_operation_with_default_value()
        {
            var operation
                = new AlterColumnOperation(
                      "T",
                      new ColumnModel(PrimitiveTypeKind.Geography)
            {
                IsNullable   = false,
                Name         = "C",
                DefaultValue = DbGeography.FromText("POINT (6 7)")
            },
                      isDestructiveChange: false);

            var sql = new SqlServerMigrationSqlGenerator().Generate(new[] { operation }, "2008").Join(s => s.Sql, Environment.NewLine);

            Assert.Equal(
                @"ALTER TABLE [T] ADD CONSTRAINT DF_C DEFAULT 'SRID=4326;POINT (6 7)' FOR [C]
ALTER TABLE [T] ALTER COLUMN [C] [geography] NOT NULL", sql);
        }
        public void Generate_can_output_add_column_for_geography_type_with_default_value()
        {
            var generatedMigration
                = new VisualBasicMigrationCodeGenerator().Generate(
                      "Migration",
                      new[]
            {
                new AddColumnOperation(
                    "T",
                    new ColumnModel(PrimitiveTypeKind.Geography)
                {
                    IsNullable   = false,
                    Name         = "C",
                    DefaultValue = DbGeography.FromText("POINT (6 7)")
                })
            },
                      "Source",
                      "Target",
                      "Foo",
                      "Bar");

            Assert.Equal(
                @"Imports System
Imports System.Data.Entity.Migrations
Imports System.Data.Entity.Spatial
Imports Microsoft.VisualBasic

Namespace Foo
    Public Partial Class Bar
        Inherits DbMigration
    
        Public Overrides Sub Up()
            AddColumn(""T"", ""C"", Function(c) c.Geography(nullable := False, defaultValue := DbGeography.FromText(""POINT (6 7)"", 4326)))
        End Sub
        
        Public Overrides Sub Down()
            DropColumn(""T"", ""C"")
        End Sub
    End Class
End Namespace
",
                generatedMigration.UserCode);
        }
Exemple #22
0
        public void DbQuery_SelectMany_with_TVFs_and_spatial_types_works()
        {
            using (var context = new SpatialNorthwindContext(_connectionString))
            {
                var results =
                    (from s1 in
                     context.SuppliersWithinRange(1000, DbGeography.FromText("POINT(-122.335576 47.610676)", 4326))
                     from s2 in
                     context.SuppliersWithinRange(1000, DbGeography.FromText("POINT(-122.335576 47.610676)", 4326))
                     where s1.Name == s2.Name
                     select new
                {
                    s1,
                    s2
                }).ToList();

                Assert.Equal(16, results.Count);
            }
        }
        public void Import()
        {
            var context = new MovesAppEntities();

            var user   = Client.Profile.GetUser();
            var start  = DateTime.ParseExact(user.Data.Profile.FirstDate, "yyyyMMdd", CultureInfo.InvariantCulture);
            var months = start.MonthsInRange(DateTime.Today);

            foreach (var month in months)
            {
                var days = Client.Places.GetByMonth(month.Year, month.Month);
                if (days != null)
                {
                    var places = days.Data
                                 .SelectMany(d => d.Segments)
                                 .Select(s => s.Place)
                                 .Where(p => p.Name != null && p.Location != null)
                                 .GroupBy(p => p.Name)
                                 .Select(p => p.First())
                                 .Distinct()
                    ;
                    if (places != null)
                    {
                        foreach (var place in places)
                        {
                            var placeId = Int32.Parse(place.Id);
                            if (!context.Places.Any(p => p.PlaceId == placeId))
                            {
                                context.Places.Add(new Place
                                {
                                    PlaceId   = placeId,
                                    Name      = place.Name,
                                    Latitude  = place.Location.Latitude,
                                    Longitude = place.Location.Longitude,
                                    Location  = DbGeography.FromText(string.Format(CultureInfo.InvariantCulture, "POINT({0} {1})", place.Location.Latitude, place.Location.Longitude))
                                });
                                context.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
        public async Task <PagingResultDto <BookingDto> > GetForClinicianAsync(PagingDto pagingDto, int clinicianId)
        {
            DbGeography g      = DbGeography.FromText($"POINT({10} {10})");
            var         result = await _context.Bookings
                                 .BookingInclude()
                                 .Include(b => b.Patient)
                                 .Where(b => b.ClinicClinician.ClinicianId == clinicianId)
                                 .Paging(pagingDto)
                                 .ToListAsync();

            var totalCount = _context.Bookings
                             .Include(b => b.ClinicClinician)
                             .Where(b => b.ClinicClinician.ClinicianId == clinicianId).Count();

            return(new PagingResultDto <BookingDto>
            {
                DataColection = _mapper.Mapper.Map <List <BookingDto> >(result),
                TotalCount = totalCount
            });
        }
        public IHttpActionResult PostJobDetail(JobDetail jobDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var geocoder = new Geocoder.GeocodeService();

            var fromLocation = geocoder.GeocodeLocation($"{jobDetail.FromStreetAddress} {jobDetail.FromCity} {jobDetail.FromState} {jobDetail.FromZip}");
            var toLocation   = geocoder.GeocodeLocation($"{jobDetail.ToStreetAddress} {jobDetail.ToCity} {jobDetail.ToState} {jobDetail.ToZip}");

            jobDetail.FromLocation = DbGeography.FromText($"POINT({fromLocation.Longitude} {fromLocation.Latitude})");
            jobDetail.ToLocation   = DbGeography.FromText($"POINT({toLocation.Longitude} {toLocation.Latitude})");

            db.JobDetails.Add(jobDetail);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = jobDetail.JobDetailId }, jobDetail));
        }
        public ActionResult Create([Bind(Include = "Id,Description,Name,Score,Category,Address")] Objective objective, List <String> photo, string lon, string lat)
        {
            objective.Photos   = new List <Photo>();
            objective.Location = DbGeography.FromText("POINT(" + lat + " " + lon + ")");
            foreach (var p in photo)
            {
                objective.Photos.Add(new Photo()
                {
                    Url = p
                });
            }
            if (ModelState.IsValid)
            {
                ctx.Objectives.Add(objective);
                ctx.SaveChanges();
                return(RedirectToAction("Details/" + objective.Category, "Category", null));
            }

            return(View(objective));
        }
Exemple #27
0
        /// <summary>
        /// Obtiene los domicilios desde la grilla
        /// </summary>
        /// <returns>Lista de direcciones</returns>
        private IList <Direccion> ObtenerDomiciliosDesdeGrilla()
        {
            IList <Direccion> domicilios = new List <Direccion>();

            foreach (GridViewRow row in gvDomicilios.Rows)
            {
                var direccion = new Direccion();

                direccion.Id     = int.Parse(gvDomicilios.DataKeys[row.RowIndex].Values[0].ToString());
                direccion.Calle  = row.Cells[0].Text;
                direccion.Numero = int.Parse(row.Cells[1].Text);
                //direccion.CiudadId = int.Parse(gvDomicilios.DataKeys[row.RowIndex].Values[1].ToString());
                direccion.Posicion = DbGeography.FromText(string.Format("POINT({0} {1})", row.Cells[6].Text, row.Cells[5].Text));
                //direccion.Ciudad = gestor.BuscarCiudadPorId(direccion.CiudadId);
                // direccion.Departamento = gestor.BuscarDepartamentoPorCiudadId(direccion.CiudadId);
                //direccion.Provincia = gestor.BuscarProvinciaPorDepartamentoId(direccion.Departamento.Id);
                domicilios.Add(direccion);
            }
            return(domicilios);
        }
Exemple #28
0
 private object CreateDefaultValue()
 {
     if (this._clrType.IsValueType())
     {
         return(Activator.CreateInstance(this._clrType));
     }
     if (this._clrType == typeof(string))
     {
         return((object)string.Empty);
     }
     if (this._clrType == typeof(DbGeography))
     {
         return((object)DbGeography.FromText("POINT(0 0)"));
     }
     if (this._clrType == typeof(DbGeometry))
     {
         return((object)DbGeometry.FromText("POINT(0 0)"));
     }
     return((object)new byte[0]);
 }
        public void Update_GearsOfWar_entities_using_stored_procedures()
        {
            using (var context = new GearsOfWarStoredProceduresContext())
            {
                var city = context.Cities.OrderBy(c => c.Name).First();
                city.Location = DbGeography.FromText("POINT(12 23)", DbGeography.DefaultCoordinateSystemId);
                context.SaveChanges();

                var tag = context.Tags.OrderBy(t => t.Id).First();
                tag.Note = "Modified Note";
                context.SaveChanges();

                var gear = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).First();
                gear.Rank = MilitaryRank.General;
                context.SaveChanges();

                var squad = context.Squads.OrderBy(s => s.Id).First();
                squad.Name = "Modified Name";
                context.SaveChanges();

                var weapon = context.Weapons.OrderBy(w => w.Id).First();
                weapon.Name = "Modified Name";
                context.SaveChanges();
            }

            using (var context = new GearsOfWarStoredProceduresContext())
            {
                var city   = context.Cities.OrderBy(c => c.Name).First();
                var tag    = context.Tags.OrderBy(t => t.Id).First();
                var gear   = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).First();
                var squad  = context.Squads.OrderBy(s => s.Id).First();
                var weapon = context.Weapons.OrderBy(w => w.Id).First();

                Assert.Equal(12, city.Location.Longitude);
                Assert.Equal(23, city.Location.Latitude);
                Assert.Equal("Modified Note", tag.Note);
                Assert.Equal(MilitaryRank.General, gear.Rank);
                Assert.Equal("Modified Name", squad.Name);
                Assert.Equal("Modified Name", weapon.Name);
            }
        }
        /// <summary>
        /// Convert a Edm GeographyLineString to DbGeography
        /// </summary>
        /// <param name="lineString">The Edm GeographyLineString to be converted</param>
        /// <returns>A DbGeography</returns>
        public static DbGeography ToDbGeography(this GeographyLineString lineString)
        {
            if (lineString == null)
            {
                return(null);
            }

            StringBuilder sb = new StringBuilder("LINESTRING(");
            int           n  = 0;

            foreach (var pt in lineString.Points)
            {
                double lat = pt.Latitude;
                double lon = pt.Longitude;
                double?alt = pt.Z;
                double?m   = pt.M;

                string pointStr = lat.ToString(DefaultCulture) + " " + lon.ToString(DefaultCulture);

                if (alt != null)
                {
                    pointStr += " " + alt.Value;
                }

                if (m != null)
                {
                    pointStr += " " + m.Value;
                }

                sb.Append(pointStr);
                n++;
                if (n != lineString.Points.Count)
                {
                    sb.Append(",");
                }
            }

            sb.Append(")");

            return(DbGeography.FromText(sb.ToString()));
        }