public async Task <MirrorStatus> RefreshCachedPOI(int poiId)
        {
            var mirrorStatus = await Task.Run <MirrorStatus>(() =>
            {
                var dataModel = new OCMEntities();
                var poiModel  = dataModel.ChargePoints.FirstOrDefault(p => p.ID == poiId);

                var poiCollection = database.GetCollection <POIMongoDB>("poi");
                var query         = Query.EQ("ID", poiId);
                var removeResult  = poiCollection.Remove(query);
                System.Diagnostics.Debug.WriteLine("POIs removed from cache [" + poiId + "]:" + removeResult.DocumentsAffected);

                if (poiModel != null)
                {
                    var cachePOI = POIMongoDB.FromChargePoint(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(poiModel));
                    if (cachePOI.AddressInfo != null)
                    {
                        cachePOI.SpatialPosition = new GeoJsonPoint <GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(cachePOI.AddressInfo.Longitude, cachePOI.AddressInfo.Latitude));
                    }

                    poiCollection.Insert <POIMongoDB>(cachePOI);
                }
                else
                {
                    //poi not present in master DB, we've removed it from cache
                }

                long numPOIInMasterDB = dataModel.ChargePoints.LongCount();
                return(RefreshMirrorStatus(poiCollection.Count(), 1, numPOIInMasterDB));
            });

            return(mirrorStatus);
        }
        public List<OCM.API.Common.Model.MediaItem> GetUserMediaItems(int userId)
        {
            var dataModel = new OCMEntities();

            var list = dataModel.MediaItems.Where(u => u.UserID == userId);

            var results = new List<OCM.API.Common.Model.MediaItem>();
            foreach (var mediaItem in list)
            {
                results.Add(OCM.API.Common.Model.Extensions.MediaItem.FromDataModel(mediaItem));
            }

            return results;
        }
        public void DeleteMediaItem(int userId, int mediaItemId)
        {
            var dataModel = new OCMEntities();

            var item = dataModel.MediaItems.FirstOrDefault(c => c.ID == mediaItemId);

            if (item != null)
            {
                var cpID = item.ChargePointID;
                dataModel.MediaItems.Remove(item);
                dataModel.ChargePoints.Find(cpID).DateLastStatusUpdate = DateTime.UtcNow;
                dataModel.SaveChanges();

                //TODO: delete from underlying storage
                var user = new UserManager().GetUser(userId);
                AuditLogManager.Log(user, AuditEventType.DeletedItem, "{EntityType:\"Comment\", EntityID:" + mediaItemId + ",ChargePointID:" + cpID + "}", "User deleted media item");
            }
        }
        public MediaItem AddPOIMediaItem(string tempFolder, string sourceImageFile, int chargePointId, string comment, bool isVideo, int userId)
        {
            var dataModel = new OCMEntities();

            var mediaItem = new MediaItem();

            var poi = new POIManager().Get(chargePointId);
            string[] urls = UploadPOIImageToStorage(tempFolder, sourceImageFile, poi);
            if (urls == null)
            {
                //failed to upload, preserve submission data
                System.IO.File.WriteAllText(tempFolder + "//OCM_" + chargePointId + "_" + (DateTime.Now.ToFileTimeUtc().ToString()) + ".json", "{userId:" + userId + ",comment:\"" + comment + "\"}");
                return null;
            }
            else
            {
                mediaItem.ItemURL = urls[0];
                mediaItem.ItemThumbnailURL = urls[1];

                mediaItem.User = dataModel.Users.FirstOrDefault(u => u.ID == userId);
                mediaItem.ChargePoint = dataModel.ChargePoints.FirstOrDefault(cp => cp.ID == chargePointId);
                mediaItem.Comment = comment;
                mediaItem.DateCreated = DateTime.UtcNow;
                mediaItem.IsEnabled = true;
                mediaItem.IsExternalResource = false;
                mediaItem.IsVideo = isVideo;

                dataModel.MediaItems.Add(mediaItem);

                dataModel.ChargePoints.Find(chargePointId).DateLastStatusUpdate = DateTime.UtcNow;
                dataModel.SaveChanges();

                new UserManager().AddReputationPoints(userId, 1);

                return mediaItem;
            }
        }
        public List <OCM.API.Common.Model.ChargePoint> GetPOIListToUpdate(OCMEntities dataModel, CacheUpdateStrategy updateStrategy)
        {
            if (!database.CollectionExists("poi"))
            {
                database.CreateCollection("poi");
            }
            var poiCollection = database.GetCollection <POIMongoDB>("poi");

            //incremental update based on POI Id - up to 100 results at a time
            if (updateStrategy == CacheUpdateStrategy.Incremental)
            {
                var maxPOI = poiCollection.FindAll().SetSortOrder(SortBy.Descending("ID")).SetLimit(1).FirstOrDefault();
                int maxId  = 0;
                if (maxPOI != null)
                {
                    maxId = maxPOI.ID;
                }

                //from max poi we have in mirror to next 100 results in order of ID
                var dataList = dataModel.ChargePoints.Include("AddressInfo,ConnectionInfo,MetadataValue,UserComment,MediaItem,User").OrderBy(o => o.ID).Where(o => o.ID > maxId).Take(100);
                var poiList  = new List <OCM.API.Common.Model.ChargePoint>();
                foreach (var cp in dataList)
                {
                    poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true));
                }
                return(poiList);
            }

            //update based on POI last modified since last status update
            if (updateStrategy == CacheUpdateStrategy.Modified)
            {
                var      maxPOI           = poiCollection.FindAll().SetSortOrder(SortBy.Descending("DateLastStatusUpdate")).SetLimit(1).FirstOrDefault();
                DateTime?dateLastModified = null;
                if (maxPOI != null)
                {
                    dateLastModified = maxPOI.DateLastStatusUpdate.Value.AddMinutes(-10);
                }

                //determine POI updated since last status update we have in cache
                //db.poi.find().sort({DateLastStatusUpdate:-1})

                //"AddressInfo,ConnectionInfo,MetadataValue,UserComment,MediaItem,User"
                var dataList = new Data.OCMEntities().ChargePoints
                               .Include(a1 => a1.AddressInfo)
                               .Include(a1 => a1.Connections)
                               .Include(a1 => a1.MetadataValues)
                               .Include(a1 => a1.UserComments)
                               .Include(a1 => a1.MediaItems)
                               .OrderBy(o => o.DateLastStatusUpdate)
                               .Where(o => o.DateLastStatusUpdate > dateLastModified).ToList();
                var poiList = new List <OCM.API.Common.Model.ChargePoint>();
                foreach (var cp in dataList)
                {
                    poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true));
                }
                return(poiList);
            }
            if (updateStrategy == CacheUpdateStrategy.All)
            {
                var dataList = new Data.OCMEntities().ChargePoints
                               .Include(a1 => a1.AddressInfo)
                               .Include(a1 => a1.Connections)
                               .Include(a1 => a1.MetadataValues)
                               .Include(a1 => a1.UserComments)
                               .Include(a1 => a1.MediaItems)
                               .OrderBy(o => o.ID)
                               .ToList();

                var poiList = new List <OCM.API.Common.Model.ChargePoint>();
                foreach (var cp in dataList)
                {
                    poiList.Add(OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(cp, true, true, true, true));
                }
                return(poiList);
            }

            return(null);
        }
        private ActionResult ProcessLoginResult(string userIdentifier, string loginProvider, string name, string email)
        {
            //TODO: move all of this logic to UserManager
            string newSessionToken = Guid.NewGuid().ToString();

            var dataModel = new OCMEntities();
            var userDetails = dataModel.Users.FirstOrDefault(u => u.Identifier.ToLower() == userIdentifier.ToLower() && u.IdentityProvider.ToLower() == loginProvider.ToLower());
            if (userDetails == null)
            {
                //create new user details
                userDetails = new Core.Data.User();
                userDetails.IdentityProvider = loginProvider;
                userDetails.Identifier = userIdentifier;
                if (String.IsNullOrEmpty(name) && loginProvider.ToLower() == "twitter") name = userIdentifier;
                if (String.IsNullOrEmpty(name) && email != null) name = email.Substring(0, email.IndexOf("@"));

                userDetails.Username = name;
                userDetails.EmailAddress = email;
                userDetails.DateCreated = DateTime.UtcNow;
                userDetails.DateLastLogin = DateTime.UtcNow;
                userDetails.IsProfilePublic = true;

                //only update session token if new (also done on logout)
                if (String.IsNullOrEmpty(userDetails.CurrentSessionToken)) userDetails.CurrentSessionToken = newSessionToken;

                dataModel.Users.Add(userDetails);
            }
            else
            {
                //update date last logged in and refresh users details if more information provided
                userDetails.DateLastLogin = DateTime.UtcNow;

                if (userDetails.Username == userDetails.Identifier && !String.IsNullOrEmpty(name)) userDetails.Username = name;
                if (String.IsNullOrEmpty(userDetails.EmailAddress) && !String.IsNullOrEmpty(email)) userDetails.EmailAddress = email;

                //only update session token if new (also done on logout)
                if (String.IsNullOrEmpty(userDetails.CurrentSessionToken)) userDetails.CurrentSessionToken = newSessionToken;
            }

            //get whichever session token we used
            //newSessionToken = userDetails.CurrentSessionToken;

            //store updates to user
            dataModel.SaveChanges();

            PerformCoreLogin(OCM.API.Common.Model.Extensions.User.FromDataModel(userDetails));

            if (!String.IsNullOrEmpty((string)Session["_redirectURL"]))
            {
                string returnURL = Session["_redirectURL"].ToString();
                return Redirect(returnURL);
            }
            else
            {
                //nowhere specified to redirect to, redirect to home page
                return RedirectToAction("Index", "Home");
            }
        }
Exemple #7
0
        /// <summary>
        /// For given query/output settings, return list of charge points. May be a cached response.
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        public List<Model.ChargePoint> GetChargePoints(APIRequestParams settings)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            bool cachingConfigEnabled = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["EnableInMemoryCaching"]);
            if (cachingConfigEnabled == false) settings.EnableCaching = false;

            string cacheKey = settings.HashKey;
            List<Model.ChargePoint> dataList = null;

            if ((HttpContext.Current != null && HttpContext.Current.Cache[cacheKey] == null) || settings.EnableCaching == false)
            {
                bool enableNoSQLCaching = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["EnableNoSQLCaching"]);
                if (enableNoSQLCaching && settings.AllowMirrorDB)
                {
                    try
                    {
                        dataList = new CacheProviderMongoDB().GetPOIList(settings);
                    }
                    catch (Exception exp)
                    {
                        //failed to query mirror db, will now fallback to sql server if dataList is null
                        //TODO: send error notification
                        if (HttpContext.Current != null) AuditLogManager.ReportWebException(HttpContext.Current.Server, AuditEventType.SystemErrorAPI, "POI Cache query exception:"+exp.ToString());
                    }
                }

                //if dataList is null we didn't get any cache DB results, use SQL DB
                if (dataList == null)
                {
                    int maxResults = settings.MaxResults;
                    this.LoadUserComments = settings.IncludeComments;
                    bool requiresDistance = false;

                    if (settings.Latitude != null && settings.Longitude != null)
                    {
                        requiresDistance = true;
                        //maxResults = 10000; //TODO find way to prefilter on distance.
                    }

                    dataList = new List<Model.ChargePoint>();
                    var dataModel = new OCMEntities();
                    dataModel.Configuration.LazyLoadingEnabled = true;
                    dataModel.Configuration.AutoDetectChangesEnabled = false;
                    ((IObjectContextAdapter)dataModel).ObjectContext.CommandTimeout = 180; //allow longer time for query to complete

                    //if distance filter provided in miles, convert to KM before use
                    if (settings.DistanceUnit == Model.DistanceUnit.Miles && settings.Distance != null)
                    {
                        settings.Distance = GeoManager.ConvertMilesToKM((double)settings.Distance);
                    }

                    bool filterByConnectionTypes = false;
                    bool filterByLevels = false;
                    bool filterByOperators = false;
                    bool filterByCountries = false;
                    bool filterByUsage = false;
                    bool filterByStatus = false;
                    bool filterByDataProvider = false;
                    bool filterByChargePoints = false;

                    if (settings.ConnectionTypeIDs != null) { filterByConnectionTypes = true; }
                    else { settings.ConnectionTypeIDs = new int[] { -1 }; }

                    if (settings.LevelIDs != null) { filterByLevels = true; }
                    else { settings.LevelIDs = new int[] { -1 }; }

                    if (settings.OperatorIDs != null) { filterByOperators = true; }
                    else { settings.OperatorIDs = new int[] { -1 }; }

                    if (settings.ChargePointIDs != null) { filterByChargePoints = true; }
                    else { settings.ChargePointIDs = new int[] { -1 }; }

                    //either filter by named country code or by country id list
                    if (settings.CountryCode != null)
                    {
                        var filterCountry = dataModel.Countries.FirstOrDefault(c => c.ISOCode.ToUpper() == settings.CountryCode.ToUpper());
                        if (filterCountry != null)
                        {
                            filterByCountries = true;
                            settings.CountryIDs = new int[] { filterCountry.ID };
                        }
                        else
                        {
                            filterByCountries = false;
                            settings.CountryIDs = new int[] { -1 };
                        }
                    }
                    else
                    {
                        if (settings.CountryIDs != null && settings.CountryIDs.Any()) { filterByCountries = true; }
                        else { settings.CountryIDs = new int[] { -1 }; }
                    }

                    if (settings.UsageTypeIDs != null) { filterByUsage = true; }
                    else { settings.UsageTypeIDs = new int[] { -1 }; }

                    if (settings.StatusTypeIDs != null) { filterByStatus = true; }
                    else { settings.StatusTypeIDs = new int[] { -1 }; }

                    if (settings.DataProviderIDs != null) { filterByDataProvider = true; }
                    else { settings.DataProviderIDs = new int[] { -1 }; }

                    if (settings.SubmissionStatusTypeID == -1) settings.SubmissionStatusTypeID = null;

                    //compile initial list of locations
                    var chargePointList = from c in dataModel.ChargePoints.AsNoTracking()
                                          where
                                              (c.AddressInfo != null && c.AddressInfo.Latitude != null && c.AddressInfo.Longitude != null && c.AddressInfo.CountryID != null)
                                              && ((settings.SubmissionStatusTypeID == null && (c.SubmissionStatusTypeID == null || c.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_Published || c.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_Published))
                                                    || (settings.SubmissionStatusTypeID == 0) //return all regardless of status
                                                    || (settings.SubmissionStatusTypeID != null && c.SubmissionStatusTypeID == settings.SubmissionStatusTypeID)
                                                    ) //by default return live cps only, otherwise use specific submission statusid
                                              && (c.SubmissionStatusTypeID != (int)StandardSubmissionStatusTypes.Delisted_NotPublicInformation)
                                              && (settings.OperatorName == null || c.Operator.Title == settings.OperatorName)
                                              && (settings.IsOpenData == null || (settings.IsOpenData != null && ((settings.IsOpenData == true && c.DataProvider.IsOpenDataLicensed == true) || (settings.IsOpenData == false && c.DataProvider.IsOpenDataLicensed != true))))
                                              && (settings.DataProviderName == null || c.DataProvider.Title == settings.DataProviderName)
                                              && (settings.LocationTitle == null || c.AddressInfo.Title.Contains(settings.LocationTitle))
                                              && (filterByCountries == false || (filterByCountries == true && settings.CountryIDs.Contains((int)c.AddressInfo.CountryID)))
                                              && (filterByOperators == false || (filterByOperators == true && settings.OperatorIDs.Contains((int)c.OperatorID)))
                                              && (filterByChargePoints == false || (filterByChargePoints == true && settings.ChargePointIDs.Contains((int)c.ID)))
                                              && (filterByUsage == false || (filterByUsage == true && settings.UsageTypeIDs.Contains((int)c.UsageTypeID)))
                                              && (filterByStatus == false || (filterByStatus == true && settings.StatusTypeIDs.Contains((int)c.StatusTypeID)))
                                              && (filterByDataProvider == false || (filterByDataProvider == true && settings.DataProviderIDs.Contains((int)c.DataProviderID)))
                                          select c;
                    if (settings.ChangesFromDate != null)
                    {
                        chargePointList = chargePointList.Where(c => c.DateLastStatusUpdate >= settings.ChangesFromDate.Value);
                    }

                    if (settings.CreatedFromDate != null)
                    {
                        chargePointList = chargePointList.Where(c => c.DateCreated >= settings.CreatedFromDate.Value);
                    }

                    //apply connectionInfo filters, all filters must match a distinct connection within the charge point, rather than any filter matching any connectioninfo
                    chargePointList = from c in chargePointList
                                      where
                                      c.Connections.Any(conn =>
                                            (settings.ConnectionType == null || (settings.ConnectionType != null && conn.ConnectionType.Title == settings.ConnectionType))
                                            && (settings.MinPowerKW == null || (settings.MinPowerKW != null && conn.PowerKW >= settings.MinPowerKW))
                                            && (filterByConnectionTypes == false || (filterByConnectionTypes == true && settings.ConnectionTypeIDs.Contains(conn.ConnectionType.ID)))
                                            && (filterByLevels == false || (filterByLevels == true && settings.LevelIDs.Contains((int)conn.ChargerType.ID)))
                                             )
                                      select c;

                    System.Data.Entity.Spatial.DbGeography searchPos = null;

                    if (requiresDistance && settings.Latitude != null && settings.Longitude != null) searchPos = System.Data.Entity.Spatial.DbGeography.PointFromText("POINT(" + settings.Longitude + " " + settings.Latitude + ")", 4326);

                    //compute/filter by distance (if required)
                    var filteredList = from c in chargePointList
                                       where
                                       (requiresDistance == false)
                                       ||
                                       (
                                           (requiresDistance == true
                                               && (c.AddressInfo.Latitude != null && c.AddressInfo.Longitude != null)
                                               && (settings.Latitude != null && settings.Longitude != null)
                                               && (settings.Distance == null ||
                                                        (settings.Distance != null &&
                                           // GetDistanceFromLatLonKM(settings.Latitude, settings.Longitude, c.AddressInfo.Latitude, c.AddressInfo.Longitude) <= settings.Distance
                                                           c.AddressInfo.SpatialPosition.Distance(searchPos) / 1000 < settings.Distance
                                                        )
                                               )
                                           )
                                       )
                                       select new
                                       {
                                           c,
                                           //    DistanceKM = GetDistanceFromLatLonKM(settings.Latitude, settings.Longitude, c.AddressInfo.Latitude, c.AddressInfo.Longitude)
                                           DistanceKM = c.AddressInfo.SpatialPosition.Distance(searchPos) / 1000
                                       };

                    if (requiresDistance)
                    {
                        //if distance was a required output, sort results by distance
                        filteredList = filteredList.OrderBy(d => d.DistanceKM).Take(settings.MaxResults);
                    }
                    else
                    {
                        filteredList = filteredList.OrderByDescending(p => p.c.DateCreated);
                    }

                    //query is of type IQueryable
            #if DEBUG
                    string sql = filteredList.ToString();

                    //writes to output window
                    System.Diagnostics.Debug.WriteLine(sql);
            #endif
                    var additionalFilteredList = filteredList.Take(maxResults).ToList();

                    stopwatch.Stop();

                    System.Diagnostics.Debug.WriteLine("Total query time: " + stopwatch.Elapsed.ToString());

                    stopwatch.Restart();

                    foreach (var item in additionalFilteredList) //.ToList
                    {
                        //note: if include comments is enabled, media items and metadata values are also included
                        Model.ChargePoint c = Model.Extensions.ChargePoint.FromDataModel(item.c, settings.IncludeComments, settings.IncludeComments, settings.IncludeComments, !settings.IsCompactOutput);

                        if (requiresDistance && c.AddressInfo != null)
                        {
                            c.AddressInfo.Distance = item.DistanceKM;
                            if (settings.DistanceUnit == Model.DistanceUnit.Miles && c.AddressInfo.Distance != null) c.AddressInfo.Distance = GeoManager.ConvertKMToMiles(c.AddressInfo.Distance);
                            c.AddressInfo.DistanceUnit = settings.DistanceUnit;
                        }

                        if (settings.IsLegacyAPICall && !(settings.APIVersion >= 2))
                        {
                            //for legacy callers, produce artificial list of Charger items
            #pragma warning disable 612  //suppress obsolete warning
                            if (c.Chargers == null || c.Chargers.Count == 0)
                            {
                                if (c.Connections != null)
                                {
                                    var chargerList = new List<Common.Model.ChargerInfo>();
                                    foreach (var con in c.Connections)
                                    {
                                        if (con.Level != null)
                                        {
                                            if (!chargerList.Exists(l => l.ChargerType == con.Level))
                                            {
                                                chargerList.Add(new Common.Model.ChargerInfo() { ChargerType = con.Level });
                                            }
                                        }
                                    }
                                    chargerList = chargerList.Distinct().ToList();
                                    c.Chargers = chargerList;
                                }
                            }
                        }

            #pragma warning restore 612

                        if (c != null)
                        {
                            dataList.Add(c);
                        }
                    }

                    //cache results (if caching enabled)
                    if (settings.EnableCaching == true && HttpContext.Current != null)
                    {
                        HttpContext.Current.Cache.Add(cacheKey, dataList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0), System.Web.Caching.CacheItemPriority.AboveNormal, null);
                    }
                }
            }
            else
            {
                //TODO: pass caching context instead of trying to access HttpContext.Current as not available during async
                if (HttpContext.Current != null)
                {
                    dataList = (List<Model.ChargePoint>)HttpContext.Current.Cache[cacheKey];
                }
            }

            System.Diagnostics.Debug.WriteLine("POI List Conversion to simple data model: " + stopwatch.Elapsed.ToString());

            return dataList.Take(settings.MaxResults).ToList();
        }
Exemple #8
0
        /// <summary>
        /// Populate AddressInfo data from settings in a simple AddressInfo object
        /// </summary>
        public Core.Data.AddressInfo PopulateAddressInfo_SimpleToData(Model.AddressInfo simpleAddressInfo, Core.Data.AddressInfo dataAddressInfo, OCMEntities dataModel)
        {
            if (simpleAddressInfo != null && dataAddressInfo == null) dataAddressInfo = new Core.Data.AddressInfo();

            if (simpleAddressInfo != null && dataAddressInfo != null)
            {
                dataAddressInfo.Title = simpleAddressInfo.Title;
                dataAddressInfo.AddressLine1 = simpleAddressInfo.AddressLine1;
                dataAddressInfo.AddressLine2 = simpleAddressInfo.AddressLine2;
                dataAddressInfo.Town = simpleAddressInfo.Town;
                dataAddressInfo.StateOrProvince = simpleAddressInfo.StateOrProvince;
                dataAddressInfo.Postcode = simpleAddressInfo.Postcode;
                if (simpleAddressInfo.CountryID > 0 || (simpleAddressInfo.Country != null && simpleAddressInfo.Country.ID > 0))
                {
                    int countryId = (simpleAddressInfo.CountryID != null ? (int)simpleAddressInfo.CountryID : simpleAddressInfo.Country.ID);
                    dataAddressInfo.Country = dataModel.Countries.FirstOrDefault(c => c.ID == countryId);
                    dataAddressInfo.CountryID = dataAddressInfo.Country.ID;
                }
                dataAddressInfo.Latitude = simpleAddressInfo.Latitude;
                dataAddressInfo.Longitude = simpleAddressInfo.Longitude;
                dataAddressInfo.ContactTelephone1 = simpleAddressInfo.ContactTelephone1;
                dataAddressInfo.ContactTelephone2 = simpleAddressInfo.ContactTelephone2;
                dataAddressInfo.ContactEmail = simpleAddressInfo.ContactEmail;
                dataAddressInfo.AccessComments = simpleAddressInfo.AccessComments;
            #pragma warning disable 612 //suppress obsolete warning
                dataAddressInfo.GeneralComments = simpleAddressInfo.GeneralComments;
            #pragma warning restore 612 //suppress obsolete warning
                dataAddressInfo.RelatedURL = simpleAddressInfo.RelatedURL;
            }

            return dataAddressInfo;
        }
Exemple #9
0
        public Model.ChargePoint Get(int id, bool includeExtendedInfo, bool allowDiskCache = false, bool allowMirrorDB = false)
        {
            if (allowMirrorDB)
            {
                var p = new CacheProviderMongoDB().GetPOI(id);
                if (p != null)
                {
                    return p;
                }
            }

            try
            {
                var dataModel = new OCMEntities();
                var item = dataModel.ChargePoints.Find(id);

                if (allowDiskCache)
                {
                    var poiCache = GetFromCache(id);
                    if (poiCache != null && poiCache.POI.DateLastStatusUpdate == item.DateLastStatusUpdate)
                    {
                        //found a cached version of POI which is up to date
                        return poiCache.POI;
                    }
                }

                var poi = Model.Extensions.ChargePoint.FromDataModel(item, includeExtendedInfo, includeExtendedInfo, includeExtendedInfo, true);

                if (allowDiskCache && poi != null)
                {
                    //cache results
                    CachePOIDetails(poi);
                }
                return poi;
            }
            catch (Exception)
            {
                //POI not found matching id
                return null;
            }
        }
Exemple #10
0
        /// <summary>
        /// for given charge point, return list of similar charge points based on location/title etc with approx similarity
        /// </summary>
        /// <param name="poi"></param>
        /// <returns></returns>
        public List<Model.ChargePoint> FindSimilar(Model.ChargePoint poi)
        {
            List<Model.ChargePoint> list = new List<Model.ChargePoint>();

            OCMEntities dataModel = new OCMEntities();

            //find similar locations (excluding same cp)
            var similarData = dataModel.ChargePoints.Where(c =>
                        c.ID != poi.ID
                        && c.ParentChargePointID == null //exclude under review and delisted charge points
                        && (c.SubmissionStatusTypeID == null || c.SubmissionStatusTypeID == 100 || c.SubmissionStatusTypeID == 200)
                        && (
                            c.AddressInfoID == poi.AddressInfo.ID
                            ||
                            c.AddressInfo.Postcode == poi.AddressInfo.Postcode
                            ||
                            c.AddressInfo.AddressLine1 == poi.AddressInfo.AddressLine1
                             ||
                            c.AddressInfo.Title == poi.AddressInfo.Title
                            )
                        );

            foreach (var item in similarData)
            {
                Model.ChargePoint c = Model.Extensions.ChargePoint.FromDataModel(item);

                if (c != null)
                {
                    int percentageSimilarity = 0;
                    if (c.AddressInfo.ID == poi.AddressInfo.ID) percentageSimilarity += 75;
                    if (c.AddressInfo.Postcode == poi.AddressInfo.Postcode) percentageSimilarity += 20;
                    if (c.AddressInfo.AddressLine1 == poi.AddressInfo.AddressLine1) percentageSimilarity += 50;
                    if (c.AddressInfo.Title == poi.AddressInfo.Title) percentageSimilarity += 25;
                    if (percentageSimilarity > 100) percentageSimilarity = 99;
                    c.PercentageSimilarity = percentageSimilarity;
                    list.Add(c);
                }
            }
            return list;
        }
Exemple #11
0
        /// <summary>
        /// used to replace a POI from an external source with a new OCM provided POI, updated POI must still be saved after to store association
        /// </summary>
        /// <param name="oldPOI"></param>
        /// <param name="updatedPOI"></param>
        public int SupersedePOI(OCMEntities dataModel, Model.ChargePoint oldPOI, Model.ChargePoint updatedPOI)
        {
            //When applying an edit to imported or externally provided data:
            //Save old item with new POI ID, Submission Status: Delisted - Superseded By Edit
            //Save edit over old POI ID, with Contributor set to OCM, Parent POI ID set to new (old) POI ID
            //This means that comments/photos/metadata etc for the old POI are preserved against the new POI

            //zero existing ids we want to move to superseded poi (otherwise existing items will be updated)
            oldPOI.ID = 0;
            oldPOI.UUID = null;
            if (oldPOI.AddressInfo != null) oldPOI.AddressInfo.ID = 0;
            if (oldPOI.Connections != null)
            {
                foreach (var connection in oldPOI.Connections)
                {
                    connection.ID = 0;
                }
            }
            oldPOI.SubmissionStatus = null;
            oldPOI.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Delisted_SupersededByUpdate;

            var supersededPOIData = this.PopulateChargePoint_SimpleToData(oldPOI, dataModel);
            supersededPOIData.DateLastStatusUpdate = DateTime.UtcNow;
            dataModel.ChargePoints.Add(supersededPOIData);
            dataModel.SaveChanges();

            //associate updated poi with older parent poi, set OCM as data provider
            updatedPOI.ParentChargePointID = supersededPOIData.ID;
            updatedPOI.DataProvider = null;
            updatedPOI.DataProvidersReference = null;
            updatedPOI.DataProviderID = (int)StandardDataProviders.OpenChargeMapContrib;

            //return new ID for the archived version of the POI
            return supersededPOIData.ID;
        }
Exemple #12
0
        /// <summary>
        /// Populates extended properties (reference data etc) of a simple POI from data model, useful for previewing as a fully populated new/edited poi
        /// </summary>
        /// <param name="poi"></param>
        /// <returns></returns>
        public Model.ChargePoint PreviewPopulatedPOIFromModel(Model.ChargePoint poi)
        {
            var dataModel = new OCMEntities();

            var dataPreviewPOI = PopulateChargePoint_SimpleToData(poi, dataModel);

            return Model.Extensions.ChargePoint.FromDataModel(dataPreviewPOI);
        }
        //convert a simple POI to data and back again to fully populate all related properties, as submission may only have simple IDs for ref data etc
        private Model.ChargePoint PopulateFullPOI(Model.ChargePoint poi)
        {
            OCMEntities tempDataModel = new OCMEntities();

            //convert simple poi to fully populated db version
            var poiData = new POIManager().PopulateChargePoint_SimpleToData(poi, tempDataModel);

            //convert back to simple POI
            var modelPOI = Model.Extensions.ChargePoint.FromDataModel(poiData, false, false, true, true);

            //clear temp changes from the poi
            //dataModel.Entry(poiData).Reload();
            tempDataModel.Dispose();
            return modelPOI;
        }