Exemple #1
0
        public string DisplayAddress(DBEntity dbaddress, string separator = ", ")
        {
            string address = "";

            if (!string.IsNullOrWhiteSpace(dbaddress.Address1))
            {
                address = dbaddress.Address1;
            }
            if (!string.IsNullOrWhiteSpace(dbaddress.Address2))
            {
                address += separator + dbaddress.Address2;
            }
            if (!string.IsNullOrWhiteSpace(dbaddress.City))
            {
                address += separator + dbaddress.City;
            }
            if (!string.IsNullOrWhiteSpace(dbaddress.Region))
            {
                address += separator + dbaddress.Region;
            }
            if (!string.IsNullOrWhiteSpace(dbaddress.PostalCode))
            {
                address += " " + dbaddress.PostalCode;
            }
            if (!string.IsNullOrWhiteSpace(dbaddress.Country))
            {
                address += separator + dbaddress.Country;
            }

            address += separator + string.Format("Lat: {0}, lng: {1}", dbaddress.Latitude, dbaddress.Longitude);
            return(address);
        }
Exemple #2
0
        public static bool HasAddressChanged(ThisEntity from, EM.Entity_Address to)
        {
            bool hasChanged = false;

            if (to.Address1 != from.Address1 ||
                to.Address2 != from.Address2 ||
                to.City != from.City ||
                to.PostalCode != from.PostalCode ||
                to.Region != from.AddressRegion ||
                to.Country != from.Country)
            {
                hasChanged = true;
            }

            return(hasChanged);
        }
Exemple #3
0
        }        //

        //public static ThisEntity Entity_Address_Get( int profileId )
        //{
        //	ThisEntity entity = new ThisEntity();
        //	try
        //	{

        //		using ( var context = new EntityContext() )
        //		{
        //			DBEntity item = context.Entity_Address
        //					.SingleOrDefault( s => s.Id == profileId );

        //			if ( item != null && item.Id > 0 )
        //			{
        //				MapFromDB( item, entity );
        //			}
        //		}
        //	}
        //	catch ( Exception ex )
        //	{
        //		LoggingHelper.LogError( ex, thisClassName + string.Format( ".Entity_Address_Get. profileId: {0}", profileId ) );
        //	}
        //	return entity;
        //}//
        public static void MapFromDB(EM.Entity_Address from, ThisEntity to)
        {
            to.Id       = from.Id;
            to.RowId    = from.RowId;
            to.ParentId = from.EntityId;
            if (from.Entity != null)
            {
                to.ParentRowId = from.Entity.EntityUid;
            }

            to.Name                = from.Name;
            to.IsMainAddress       = from.IsPrimaryAddress ?? false;
            to.Address1            = from.Address1;
            to.Address2            = from.Address2 ?? "";
            to.PostOfficeBoxNumber = from.PostOfficeBoxNumber ?? "";
            to.City                = from.City;
            to.PostalCode          = from.PostalCode;
            to.AddressRegion       = from.Region;
            to.Country             = from.Country;
            //to.CountryId = ( int ) ( from.CountryId ?? 0 );
            //if ( from.Codes_Countries != null )
            //{
            //	to.Country = from.Codes_Countries.CommonName;
            //}
            to.Latitude  = from.Latitude ?? 0;
            to.Longitude = from.Longitude ?? 0;

            //to.ContactPoint = Entity_ContactPointManager.GetAll( to.RowId );

            if (IsValidDate(from.Created))
            {
                to.Created = ( DateTime )from.Created;
            }

            if (IsValidDate(from.LastUpdated))
            {
                to.LastUpdated = ( DateTime )from.LastUpdated;
            }
            //get address specific contacts
            //address could be empty
            to.ContactPoint = Entity_ContactPointManager.GetAll(to.RowId);
        }
Exemple #4
0
        public bool Entity_Address_Delete(int profileId, ref string statusMessage)
        {
            bool isOK = true;

            using (var context = new EntityContext())
            {
                DBEntity p = context.Entity_Address.FirstOrDefault(s => s.Id == profileId);
                if (p != null && p.Id > 0)
                {
                    context.Entity_Address.Remove(p);
                    int count = context.SaveChanges();
                }
                else
                {
                    statusMessage = string.Format("Requested record was not found: {0}", profileId);
                    isOK          = false;
                }
            }
            return(isOK);
        }
Exemple #5
0
        }//

        public static void UpdateGeo(CM.Address from, EM.Entity_Address to)
        {
            //GoogleGeocoding.Results results = GeoServices.GeocodeAddress( from.DisplayAddress() );
            bool doingExpandOfRegion = UtilityManager.GetAppKeyValue("doingExpandOfRegion", false);
            //Try with a looser address if 0/0 lat/lng
            var hasLatLng      = false;
            var results        = new GoogleGeocoding.Results();
            var addressesToTry = new List <string>()
            {
                from.DisplayAddress(),
                from.LooseDisplayAddress(),
                from.PostalCode ?? "",
                from.AddressRegion ?? ""
                //,from.Country ?? ""
            };

            foreach (var test in addressesToTry)
            {
                if (string.IsNullOrWhiteSpace(test) || test.Trim().Length < 5)
                {
                    continue;
                }

                results = TryGetAddress(test, ref hasLatLng);
                if (hasLatLng)
                {
                    break;
                }
                System.Threading.Thread.Sleep(3000);   //Don't spam the Geocoding API
            }

            //Continue
            if (results != null)
            {
                GoogleGeocoding.Location location = results.GetLocation();
                if (location != null)
                {
                    to.Latitude  = location.lat;
                    to.Longitude = location.lng;
                }
                try
                {
                    if (results.results.Count > 0)
                    {
                        //this is inconsistant [0] -postal code, [5]-country, [4] region
                        //                  int pIdx = 0;// results.results[ 0 ].address_components.Count - 1;
                        //int cIdx = results.results[ 0 ].address_components.Count - 1;
                        //                  int regionIdx = results.results[ 0 ].address_components.Count - 2;
                        string postalCode = ""; // results.results[ 0 ].address_components[ 0 ].short_name;
                        string country    = ""; // results.results[ 0 ].address_components[ cIdx ].long_name;
                        string fullRegion = ""; // results.results[ 0 ].address_components[ regionIdx ].long_name;
                        //can we expand the region here? - determine the index number of the region
                        string suffix = "";
                        //want to at least implement in the import
                        foreach (var part in results.results[0].address_components)
                        {
                            if (part.types.Count > 0)
                            {
                                if (part.types[0] == "country")
                                {
                                    country = part.long_name;
                                }
                                else if (part.types[0] == "administrative_area_level_1")
                                {
                                    fullRegion = part.long_name;
                                }
                                else if (part.types[0] == "postal_code")
                                {
                                    postalCode = part.long_name;
                                }
                                else if (part.types[0] == "postal_code_suffix")
                                {
                                    suffix      = part.long_name;
                                    postalCode += "-" + suffix;
                                }
                            }
                            //
                        }

                        if (string.IsNullOrEmpty(to.PostalCode) ||
                            to.PostalCode != postalCode)
                        {
                            //?not sure if should assume the google result is accurate
                            to.PostalCode = postalCode;
                        }
                        if (!string.IsNullOrEmpty(country) &&
                            to.CountryId == null)
                        {
                            //set country string, and perhaps plan update process.
                            to.Country = country;
                            //do lookup, OR at least notify for now
                            //probably should make configurable - or spin off process to attempt update
                            //EmailManager.NotifyAdmin( "CTI Missing country to update", string.Format( "Address without country entered, but resolved via GoogleGeocoding.Location. entity.ParentId: {0}, country: {1}", from.ParentId, country ) );
                        }
                        //expand region
                        if (doingExpandOfRegion &&
                            (to.Region ?? "").Length < fullRegion.Length)
                        {
                            to.Region = fullRegion;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogError(ex, thisClassName + "UpdateGeo");
                }
            }
        }
Exemple #6
0
        public bool Save(ThisEntity entity, Guid parentUid, ref SaveStatus status)
        {
            bool isValid = true;

            if (!IsValidGuid(parentUid))
            {
                status.AddError("Error: a valid parent identifier was not provided.");
                return(false);
            }

            int    count  = 0;
            Entity parent = EntityManager.GetEntity(parentUid);

            if (parent == null || parent.EntityBaseId == 0)
            {
                status.AddError("Error - the parent entity was not found.");
                return(false);
            }

            try
            {
                using (var context = new EntityContext())
                {
                    DBEntity efEntity = new DBEntity();
                    if (ValidateProfile(entity, parent, ref status) == false)
                    {
                        return(false);
                    }
                    bool resetIsPrimaryFlag = false;

                    if (entity.Id == 0)
                    {
                        //add
                        efEntity          = new DBEntity();
                        efEntity.EntityId = parent.Id;
                        entity.ParentId   = parent.Id;
                        MapToDB(entity, efEntity, ref resetIsPrimaryFlag);

                        //could just have contact points without address
                        if (entity.HasAddress())
                        {
                            efEntity.Created = efEntity.LastUpdated = DateTime.Now;
                            if (IsValidGuid(entity.RowId))
                            {
                                efEntity.RowId = entity.RowId;
                            }
                            else
                            {
                                efEntity.RowId = Guid.NewGuid();
                            }

                            context.Entity_Address.Add(efEntity);
                            count = context.SaveChanges();

                            //update profile record so doesn't get deleted
                            entity.Id       = efEntity.Id;
                            entity.ParentId = parent.Id;
                            entity.RowId    = efEntity.RowId;
                            if (count == 0)
                            {
                                status.AddError(string.Format(" Unable to add address. parentUid: {0}, City: {1}, Region: {2} <br\\> ", parentUid, efEntity.City, efEntity.Region));
                            }
                            else
                            {
                                if (resetIsPrimaryFlag)
                                {
                                    Reset_Prior_ISPrimaryFlags(efEntity.EntityId, entity.Id);
                                }
                            }
                        }
                        //handle contact points
                        //if address present, these need to be closely related
                        if (entity.Id > 0)
                        {
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, entity.RowId, ref status);
                        }
                        else
                        {
                            // put under parent
                            //should log this. If under parent should onlybe an org, and delete all has already been done.
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, parentUid, ref status, false);
                        }
                    }
                    else
                    {
                        entity.ParentId = parent.Id;

                        efEntity = context.Entity_Address.SingleOrDefault(s => s.Id == entity.Id);
                        if (efEntity != null && efEntity.Id > 0)
                        {
                            entity.RowId = efEntity.RowId;
                            //update
                            MapToDB(entity, efEntity, ref resetIsPrimaryFlag);
                            //has changed?
                            if (HasStateChanged(context))
                            {
                                efEntity.LastUpdated = System.DateTime.Now;

                                count = context.SaveChanges();
                            }
                            if (resetIsPrimaryFlag)
                            {
                                Reset_Prior_ISPrimaryFlags(entity.ParentId, entity.Id);
                            }

                            //handle contact points - very wierd approach, but shouldn't have updates
                            new Entity_ContactPointManager().SaveList(entity.ContactPoint, entity.RowId, ref status);
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
            {
                string message = HandleDBValidationError(dbex, thisClassName + ".Save() ", "Address Profile");
                status.AddError("Error - the save was not successful. " + message);
                LoggingHelper.LogError(dbex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                isValid = false;
            }
            catch (Exception ex)
            {
                string message = FormatExceptions(ex);
                status.AddError("Error - the save was not successful. " + message);
                LoggingHelper.LogError(ex, thisClassName + string.Format(".Save(), Parent: {0} ({1})", parent.EntityBaseName, parent.EntityBaseId));
                isValid = false;
            }
            return(isValid);
        }
Exemple #7
0
        public static void MapToDB(ThisEntity from, EM.Entity_Address to, ref bool resetIsPrimaryFlag)
        {
            resetIsPrimaryFlag = false;

            //NOTE: the parentId - currently orgId, is handled in the update code
            to.Id   = from.Id;
            to.Name = from.Name;
            //if this address is primary, and not previously primary, set indicator to reset existing settings
            //will need setting to default first address to primary if not entered
            if (from.IsMainAddress && ( bool )(!(to.IsPrimaryAddress ?? false)))
            {
                //initially attempt to only allow adding new primary,not unchecking
                resetIsPrimaryFlag = true;
            }
            to.IsPrimaryAddress = from.IsMainAddress;

            //bool hasChanged = false;
            //bool hasAddress = false;

            //if ( from.HasAddress() )
            //{
            //	hasAddress = true;
            //	if ( to.Latitude == null || to.Latitude == 0
            //	  || to.Longitude == null || to.Longitude == 0 )
            //		hasChanged = true;
            //}
            //if ( hasChanged == false )
            //{
            //	if ( to.Id == 0 )
            //		hasChanged = true;
            //	else
            //		hasChanged = HasAddressChanged( from, to );
            //}

            to.Address1            = from.Address1;
            to.Address2            = GetData(from.Address2, null);
            to.PostOfficeBoxNumber = GetData(from.PostOfficeBoxNumber, null);
            to.City       = from.City;
            to.PostalCode = from.PostalCode;
            to.Region     = from.AddressRegion ?? "";
            to.Country    = from.Country;
            //likely provided
            to.Latitude  = from.Latitude;
            to.Longitude = from.Longitude;

            if (from.HasAddress())
            {
                //check if lat/lng were not provided with address
                //may want to always do this to expand region!
                if (to.Latitude == null || to.Latitude == 0 ||
                    to.Longitude == null || to.Longitude == 0 ||
                    (to.Region ?? "").Length == 2
                    )
                {
                    UpdateGeo(from, to);
                }
            }

            //these will likely not be present?
            //If new, or address has changed, do the geo lookup
            //if ( hasAddress )
            //{
            //	if ( hasChanged )
            //	{
            //		UpdateGeo( from, to );
            //	}
            //}
            //else
            //{
            //	to.Latitude = 0;
            //	to.Longitude = 0;
            //}
        }