public static bool IsValid(string mobilNumber, bool isExistingPilot)
        {
            var cleanNumber = ParseMobilNumber(mobilNumber);
            var valid = false;
            int num = 0;
            valid = (cleanNumber.StartsWith("+")    // prefixed with internationational code
                & int.TryParse(cleanNumber.Substring(1), out num)   // Numeric 
                & cleanNumber.Length >= 11);    // Minimum length
            if (cleanNumber.StartsWith("+45"))
            {
                // Danish number format validation
                valid = (cleanNumber.Length == 11);
            }
            else if (cleanNumber.StartsWith("+46"))
            {
                // Swedish number format validation
                valid = (cleanNumber.Length == 12);
            }

            if (valid)
            {
                if (!isExistingPilot)
                {
                    return true;
                }
                else
                {
                    using (var shortDb = new FlightContext())
                    {
                        return shortDb.Pilots.Any(d => d.MobilNumber == cleanNumber);
                    }
                }
            }
            return false;
        }
        public static bool IsValid(string email, bool isExistingPilot)
        {
            var cleanEmail = ParseEmail(email);
            var valid = false;
            try
            {
                var addr = new System.Net.Mail.MailAddress(cleanEmail);
                if (addr.Address == cleanEmail)
                {
                    valid = true;
                }
            }
            catch
            {
                return false;
            }

            if (valid)
            {
                if (!isExistingPilot)
                {
                    return true;
                }
                else
                {
                    using (var shortDb = new FlightContext())
                    {
                        return shortDb.Pilots.Any(d => d.Email == cleanEmail);
                    }
                }
            }
            return false;
        }
 public static List<Pilot> FindPilotsByEmail(string email)
 {
     email = ParseEmail(email);
     using (var shortDb = new FlightContext())
     {
         return shortDb.Pilots.Where(d => d.Email == email).ToList();
     }
 }
 public static List<Pilot> FindPilotsByMobilNumber(string mobilNumber)
 {
     mobilNumber = ParseMobilNumber(mobilNumber);
     using (var shortDb = new FlightContext())
     {
         return shortDb.Pilots.Where(d => d.MobilNumber == mobilNumber).ToList();
     }
 }
        public async Task<ActionResult> LinkPilot(string pilot)
        {
            ManageMessageId? message = ManageMessageId.Error;
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
            if (user != null)
            {
                using (var context = new FlightContext())
                {
                    var userPilotBinding = context.Pilots.Find(Convert.ToInt32(pilot));
                    if (userPilotBinding != null)
                    {
                        // Validate User and Pilot have Email or Phone Number in Common

                        using (var db = new ApplicationDbContext())
                        {
                            var dbUser = db.Users.Find(user.Id);
                            if (dbUser != null)
                            {
                                dbUser.BoundToPilotId = userPilotBinding.PilotId.ToString(CultureInfo.InvariantCulture);
                                db.SaveChanges();
                                message = ManageMessageId.BindToPilotSuccess;
                            }
                        }
                    }
                }
            }
            return RedirectToAction("ManagePilotBinding", new { Message = message });
        }
        private static ManagePilotBindingViewModel ManagePilotBindingViewModel(ApplicationUser user)
        {
            Pilot userPilotBinding = null;
            List<Pilot> otherPilots = new List<Pilot>();
            using (var context = new FlightContext())
            {
                if (user.BoundToPilotId != null)
                {
                    userPilotBinding = context.Pilots.Find(Convert.ToInt32(user.BoundToPilotId));
                    // Load club reference information 
                    if (userPilotBinding != null)
                    {
                        context.Entry(userPilotBinding).Reference(p => p.Club).Load();
                    }
                }

                if (user.EmailConfirmed)
                {
                    otherPilots.AddRange(context.Pilots.Where(p => p.Email == user.Email).Include(c => c.Club).ToList());
                }

                if (user.PhoneNumberConfirmed)
                {
                    foreach (var pilot in context.Pilots.Where(p => p.MobilNumber == user.PhoneNumber).Include(c => c.Club).ToList())
                    {
                        if (!otherPilots.Exists(o => o.PilotId == pilot.PilotId))
                        {
                            otherPilots.Add(pilot);
                        }
                    }
                }

                // Remove the existing pilot
                if (userPilotBinding != null && otherPilots.Any())
                {
                    otherPilots = otherPilots.Where(p => p.PilotId != userPilotBinding.PilotId).ToList();
                }

                // Auto set primary pilot binding information
                if (string.IsNullOrEmpty(user.BoundToPilotId) && otherPilots.Count == 1)
                {
                    user.BoundToPilotId = otherPilots.First().PilotId.ToString();
                    // Save to database
                    using (var appcontext = new ApplicationDbContext())
                    {
                        var appUser = appcontext.Users.Find(user.Id);
                        if (appUser != null)
                        {
                            appUser.BoundToPilotId = user.BoundToPilotId;
                            appcontext.SaveChanges();
                        }
                    }
                    userPilotBinding = otherPilots.First();
                    otherPilots = new List<Pilot>();
                }

            }

            var result = new ManagePilotBindingViewModel
            {
                CurrentPilotBinding = userPilotBinding,
                PotentialPilotBindings = otherPilots
            };

            return result;
        }
 public async Task<ActionResult> RemovePilotBinding(string currentPilotIdBinding)
 {
     ManageMessageId? message = ManageMessageId.Error;
     var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
     if (user != null)
     {
         using (var context = new FlightContext())
         {
             if (user.BoundToPilotId != null)
             {
                 var userPilotBinding = context.Pilots.Find(Convert.ToInt32(user.BoundToPilotId));
                 if (userPilotBinding.PilotId.ToString(CultureInfo.InvariantCulture) == currentPilotIdBinding)
                 {
                     using (var db = new ApplicationDbContext())
                     {
                         var dbUser = db.Users.Find(user.Id);
                         if (dbUser != null)
                         {
                             dbUser.BoundToPilotId = null;
                             db.SaveChanges();
                             message = ManageMessageId.RemovePilotBindingSuccess;        
                         }
                     }
                 }
             }
         }
     }
     return RedirectToAction("ManagePilotBinding", new { Message = message });
 }
        /// <summary>
        /// Method parameters allows for UnitTesting 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="routeData"></param>
        /// <returns></returns>
        public static Club GetCurrentClub(HttpContextBase context, RouteData routeData)
        {
            
            // Fetch from URL 
            var urlClubFilter = routeData.Values["club"] as string;

            // If in the direct access we can be dealing with /{ClubId}
            if (urlClubFilter == null && context.Request.Url != null)
            {
                var absolutePath = context.Request.Url.AbsolutePath;
                // Handle switching between one club to another
                if (absolutePath == "/Club/SetCurrentClub" && context.Request.UrlReferrer != null)
                {
                    urlClubFilter = context.Request.UrlReferrer.AbsolutePath.Split('/').FirstOrDefault(d => !string.IsNullOrWhiteSpace(d));
                    urlClubFilter = context.Server.UrlDecode(urlClubFilter);
                }
            }

            // Return Session Cache if set
            if (context.Items["CurrentClub"] != null)
            {
                var ghostClubSession = context.Items["CurrentClub"] as Club;
                if (ghostClubSession != null && Equals(ghostClubSession.ShortName, urlClubFilter))
                {
                    return ghostClubSession;
                }
            }

            // Read Url
            if (urlClubFilter != null && !string.IsNullOrWhiteSpace(urlClubFilter))
            {
                Club ghost = new Club();
                using (var shortDb = new FlightContext())
                {
                    var club = shortDb.Clubs.SingleOrDefault(d => d.ShortName == urlClubFilter);
                    if (club != null)
                    {
                        ghost = new Club();
                        ghost.LocationId = club.LocationId;
                        ghost.Location = club.Location; // for allowing country
                        ghost.ContactInformation = club.ContactInformation;
                        ghost.ShortName = club.ShortName;
                        ghost.Name = club.Name;
                        if (club.Website != null && (club.Website.StartsWith("http://") || club.Website.StartsWith("https://")))
                        {
                            ghost.Website = club.Website;
                        }
                        else if (club.Website != null)
                        {
                            ghost.Website = "http://" + club.Website;
                        }
                        ghost.ClubId = club.ClubId;
                    }
                }

                // Set Session Cache
                context.Items.Remove("CurrentClub");
                context.Items.Add("CurrentClub", ghost);

                // Return Current Club
                return ghost;
            }
            return new Club();
        }