public async Task <ActionResult> ImportUsers(HttpPostedFileBase ExcelFile, string temppass) { var message = string.Empty; try { var output = new List <RegisterExcelViewModel>(); if (ExcelFile != null) { var data = ExcelFile.ToFileByteArray(); ImportFromExcel import = new ImportFromExcel(); if (Path.GetExtension(ExcelFile.FileName.ToLower()) == ".xlsx") { import.LoadXlsx(data); } else if (Path.GetExtension(ExcelFile.FileName.ToLower()) == ".xls") { import.LoadXls(data); } else { TempData[BSMessage.TYPE] = BSMessage.MessageType.DANGER; TempData[BSMessage.DIALOGBOX] = "Invalid Excel worksheet: " + Path.GetExtension(ExcelFile.FileName); return(RedirectToAction("Index", "Roles", new { area = "" })); } output = import.ExcelToList <RegisterExcelViewModel>(0, 1); if (output.Count == 0) { TempData[BSMessage.TYPE] = BSMessage.MessageType.WARNING; TempData[BSMessage.DIALOGBOX] = "Excel worksheet has no user records."; return(RedirectToAction("Index", "Roles", new { area = "" })); } var duplicates = output.GroupBy(x => x.UserName) .Select(g => new { Value = g.Key, Count = g.Count() }) .Where(h => h.Count > 1) .Select(s => s.Value); if (duplicates.Count() > 0) { TempData[BSMessage.TYPE] = BSMessage.MessageType.DANGER; message = "<p>We have found the following duplicate records: " + string.Join(", ", duplicates) + " </p>"; } //var users = output.GroupBy(x => x.UserName).Select(x => x.First()).ToList(); TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; foreach (var s in output) { s.PhoneNumber = string.IsNullOrEmpty(s.PhoneNumber) ? null : s.PhoneNumber.TrimStart('0'); using (var db = new ApplicationDbContext()) { var phoneExist = db.Users.Where(x => (x.CountryCode + x.PhoneNumber) == (s.CountryCode + s.PhoneNumber)).FirstOrDefault() != null; var emailExist = db.Users.Where(u => u.UserName == s.Email || u.Email == s.Email).FirstOrDefault() != null; if (emailExist || phoneExist) { s.CountryCode = null; s.PhoneNumber = null; s.Email = null; } } DateTime?bdate; try { bdate = DateTime.ParseExact(s.BirthDate, "M/d/yyyy", new CultureInfo("en-US")); } catch { bdate = null; } var user = new ApplicationUser() { UserName = s.UserName, Email = s.Email, PhoneNumber = s.PhoneNumber, CountryCode = string.IsNullOrEmpty(s.PhoneNumber) ? null : s.CountryCode, UserProfile = new UserProfile { UserName = s.UserName, RegistrationType = s.RegistrationType, LastName = textInfo.ToTitleCase(s.LastName.ToLower()), FirstName = textInfo.ToTitleCase(s.FirstName.ToLower()), BirthDate = bdate, Gender = string.IsNullOrEmpty(s.Gender) ? null : s.Gender[0].ToString().ToUpper(), RegistrationDate = DateTime.Now, IsActive = true } }; var result = await UserManager.CreateAsync(user, string.IsNullOrEmpty(temppass)?user.UserName : temppass); if (result.Succeeded) { if (!string.IsNullOrEmpty(user.UserProfile.RegistrationType)) { RegisterViewModel.AddRole(user.UserName, user.UserProfile.RegistrationType); } } else { message += user.UserName + " / " + user.UserProfile.LastName + ", " + user.UserProfile.FirstName + " was not added. <br>"; } } } } catch (Exception ex) { TempData[BSMessage.TYPE] = BSMessage.MessageType.DANGER; TempData[BSMessage.PANEL] = "Oops! Something went wrong. " + ex.GetBaseException(); } if (!string.IsNullOrEmpty(message)) { TempData[BSMessage.PANEL] = message; } return(RedirectToAction("Index", "Roles", new { area = "" })); }
private ApplicationUser GetDetails(string AccessToken) { Uri eatTargetUri = new Uri("https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=" + ConfigurationManager.AppSettings["Fb_App_ID"] + "&client_secret=" + ConfigurationManager.AppSettings["Fb_App_Secret"] + "&fb_exchange_token=" + AccessToken); HttpWebRequest eat = (HttpWebRequest)HttpWebRequest.Create(eatTargetUri); StreamReader eatStr = new StreamReader(eat.GetResponse().GetResponseStream()); string eatToken = eatStr.ReadToEnd().ToString().Replace("access_token=", ""); // Split the access token and expiration from the single string string[] eatWords = eatToken.Split('&'); string extendedAccessToken = eatWords[0]; // Request the Facebook user information Uri targetUserUri = new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture.width(300),birthday&access_token=" + AccessToken); HttpWebRequest user = (HttpWebRequest)HttpWebRequest.Create(targetUserUri); // Read the returned JSON object response StreamReader userInfo = new StreamReader(user.GetResponse().GetResponseStream()); string jsonResponse = string.Empty; jsonResponse = userInfo.ReadToEnd(); // Deserialize and convert the JSON object to the Facebook.User object type JavaScriptSerializer sr = new JavaScriptSerializer(); string jsondata = jsonResponse; dynamic facebook = JObject.Parse(jsondata); //string FacebookId = facebook.id; string FacebookEmail = facebook.email; /*You can get other dynamic variables*/ if (string.IsNullOrEmpty(FacebookEmail)) { return(null); } else { using (var db = new ApplicationDbContext()) { ApplicationUser _user = UserManager.FindByEmail(FacebookEmail); if (_user == null) { byte[] fbPhotoData; try { WebClient webClient = new WebClient(); string fbPhotoUrl = facebook.picture.data.url; fbPhotoData = webClient.DownloadData(fbPhotoUrl); } catch { fbPhotoData = null; } var newUser = new ApplicationUser() { UserName = FacebookEmail, Email = FacebookEmail, EmailConfirmed = true, //PhoneNumber = , UserProfile = new UserProfile { UserName = FacebookEmail, LastName = facebook.last_name, FirstName = facebook.first_name, BirthDate = facebook.birthday, Gender = facebook.gender == "male" ? "M" : facebook.gender == "female" ? "F" : null, RegistrationType = Session["RegType"] != null ? Session["RegType"].ToString() : null, RegistrationDate = DateTime.Now, IsActive = true, Picture = fbPhotoData } }; UserManager.Create(newUser); string WelcomeMsg = "Hello " + newUser.UserProfile.FirstName + "! Welcome to " + AppSettings.AppTitle + ". "; if (!string.IsNullOrEmpty(newUser.UserProfile.RegistrationType)) { string InitRole = RegisterViewModel.AddRole(newUser.UserName, newUser.UserProfile.RegistrationType); if (!string.IsNullOrEmpty(InitRole)) { WelcomeMsg += "The webapp initially assigns your role as a/n " + InitRole + ". "; } } Session.Remove("RegType"); TempData[BSMessage.DIALOGBOX] = WelcomeMsg; return(newUser); } return(_user); } } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; var user = new ApplicationUser() { UserName = model.UserName, Email = model.UserName, PhoneNumber = string.IsNullOrEmpty(model.PhoneNumber) ? null : model.PhoneNumber.TrimStart('0'), CountryCode = string.IsNullOrEmpty(model.PhoneNumber) ? null : model.CountryCode, UserProfile = new UserProfile { UserName = model.UserName, RegistrationType = model.RegistrationType, LastName = textInfo.ToTitleCase(model.LastName.ToLower()), FirstName = textInfo.ToTitleCase(model.FirstName.ToLower()), BirthDate = model.BirthDate, Gender = model.Gender, RegistrationDate = DateTime.Now, IsActive = true } }; if (AppSettings.EmailVerificationEnabled) { char[] padding = { '=' }; user.Token = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).TrimEnd(padding).Replace('+', '-').Replace('/', '_'); user.TokenExpiration = DateTime.Now.AddHours(1); } var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { string WelcomeMsg = "Hello " + model.FirstName + "! Welcome to " + AppSettings.AppTitle + ". "; RegisterViewModel.SaveRegistrationCustomData(model); if (!string.IsNullOrEmpty(model.RegistrationType)) { string InitRole = RegisterViewModel.AddRole(model.UserName, model.RegistrationType); if (!string.IsNullOrEmpty(InitRole)) { WelcomeMsg += "The webapp initially assigns your role as a/n " + InitRole + ". "; } } if (AppSettings.EmailVerificationEnabled) { var callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = user.Token }); Gabs.Helpers.EmailUtil.SendEmail(user.Email, "Confirm Your Account", "Hello " + model.FirstName + "!<br><br> Please confirm your account by clicking this <a href=\"" + callbackUrl + "\">link</a>."); WelcomeMsg += "Kindly check your email to verify your account. "; } await SignInAsync(user, isPersistent : false); if (!string.IsNullOrEmpty(model.PhoneNumber)) { var smsMsg = "Hello " + model.FirstName + "! You can now login to " + AppSettings.AppTitle + " using your mobile number."; Gabs.Helpers.SMSUtil.Send("+" + model.CountryCode + model.PhoneNumber, smsMsg); WelcomeMsg += " We have sent a welcome message to your mobile phone. "; //return RedirectToAction("VerifyPhoneNumber", "Account"); } TempData[BSMessage.DIALOGBOX] = WelcomeMsg; return(RedirectToAction("Index", "Home", new { area = "", welcome = true })); } else { AddErrors(result); } } // If we got this far, something failed, redisplay form return(View(model)); }