static void ValidateHlsClips() { string dirList = @"C:\Users\epaden\Desktop\dirlist.txt"; int offeringId = 2; int serviceId = 46; var context = new IPTV2Entities(); var directoryList = LoadDirectoryList(dirList); var offering = context.Offerings.Find(offeringId); var service = offering.Services.FirstOrDefault(s => s.PackageId == serviceId); var showList = service.GetAllOnlineShowIds("US"); foreach (var showId in showList) { var showAsCategory = context.CategoryClasses.Find(showId); if (showAsCategory is Show) { var show = (Show)showAsCategory; foreach (var ep in show.Episodes.Where(e => e.Episode.OnlineStatusId == 1).OrderBy(ep => ep.Episode.DateAired)) { var hlsAssets = from a in ep.Episode.PremiumAssets from ac in a.Asset.AssetCdns where ac.CdnId == 2 select ac; foreach (var ha in hlsAssets) { var cdnRef = ha.CdnReference; var videoFile = cdnRef.Replace(",500000,800000,1000000,1300000,1500000,.mp4.csmil/master.m3u8", ".mp4"); videoFile = videoFile.Substring(videoFile.LastIndexOf('/') + 1).Replace(",", ""); if (!directoryList.Contains(videoFile)) { Console.WriteLine("Disabling Episode: {0} {1} {2}", show.CategoryName, ep.Episode.Description, ep.Episode.DateAired); ep.Episode.OnlineStatusId = 0; ep.Episode.MobileStatusId = 0; context.SaveChanges(); } } } } } }
public ActionResult _SignUp(FormCollection f) { var context = new IPTV2Entities(); Dictionary<string, object> collection = new Dictionary<string, object>(); if (String.IsNullOrEmpty(f["email"])) { collection.Add("errorCode", -1); collection.Add("errorMessage", "Please fill up your email address."); return Content(MyUtility.buildJson(collection), "application/json"); // Do something } string email = f["email"]; RegexUtilities util = new RegexUtilities(); //if (!MyUtility.isEmail(email)) if (!util.IsValidEmail(email)) { collection.Add("errorCode", (int)ErrorCodes.IsNotValidEmail); collection.Add("errorMessage", "Invalid email format."); return Content(MyUtility.buildJson(collection), "application/json"); } var tester = context.BetaTesters.FirstOrDefault(b => b.EMailAddress == email); if (tester == null) // New sign up { context.BetaTesters.Add(new BetaTester() { EMailAddress = email, DateSent = DateTime.Now, InvitationKey = System.Guid.NewGuid(), InvitedBy = System.Guid.Parse("9B4216E8-69BA-4548-9552-4CD065E58D3E") }); int result = context.SaveChanges(); if (result > 0) { //Success collection.Add("errorCode", 0); collection.Add("errorMessage", "Thank you for signing up!"); } else { //Fail collection.Add("errorCode", -2); collection.Add("errorMessage", "The system encountered an unidentified error. Please try again."); } } else { // USer has signed up collection.Add("errorCode", -3); collection.Add("errorMessage", "You have already signed up."); } return Content(MyUtility.buildJson(collection), "application/json"); }
public JsonResult _RegisterAndSubscribe(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty, info = "Registration", TransactionType = "Registration" }; if (!Request.IsAjaxRequest()) { ReturnCode.StatusMessage = "Invalid request"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } bool isSourceAir = false; string url = Url.Action("Register", "User").ToString(); var field_names = new string[] { "uid", "provider", "full_name", "pid", "cmd", "a1", "p1", "t1", "a3", "t3", "p3", "src", "item_name", "amount", "currency", "custom", "ip" }; try { if (TempData["qs"] != null) { var qs = (NameValueCollection)TempData["qs"]; ViewBag.qs = qs; TempData["qs"] = qs; } DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (!field_names.Contains(x.Key)) if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { var ip = Request.GetUserHostAddressFromCloudflare(); if (!String.IsNullOrEmpty(tmpCollection["ip"])) ip = tmpCollection["ip"]; var location = MyUtility.GetLocationBasedOnIpAddress(ip); string FirstName = tmpCollection["first_name"]; string LastName = tmpCollection["last_name"]; string EMail = tmpCollection["p_login_email"]; string ConfirmEmail = tmpCollection["p_login_email_c"]; string Password = tmpCollection["login_pass"]; //autodetect country, city, state string CountryCode = location.countryCode; string City = location.city; string State = location.region; string provider = String.IsNullOrEmpty(tmpCollection["provider"]) ? String.Empty : tmpCollection["provider"]; string uid = String.IsNullOrEmpty(tmpCollection["uid"]) ? String.Empty : tmpCollection["uid"]; System.Guid userId = System.Guid.NewGuid(); string browser = Request.UserAgent; if (FirstName.Length > 32) ReturnCode.StatusMessage = "First Name cannot exceed 32 characters."; if (LastName.Length > 32) ReturnCode.StatusMessage = "Last Name cannot exceed 32 characters."; if (EMail.Length > 64) ReturnCode.StatusMessage = "Email address cannot exceed 64 characters."; if (State.Length > 30) ReturnCode.StatusMessage = "State cannot exceed 30 characters."; if (City.Length > 50) ReturnCode.StatusMessage = "City cannot exceed 50 characters."; if (String.Compare(EMail, ConfirmEmail, true) != 0) ReturnCode.StatusMessage = "Email addresses do not match"; RegexUtilities util = new RegexUtilities(); //if (!MyUtility.isEmail(EMail)) if (!util.IsValidEmail(EMail)) ReturnCode.StatusMessage = "Email address is invalid."; var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0); if (user != null) ReturnCode.StatusMessage = "Email address is already taken."; if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) // check if country is part of the exclusion list first ReturnCode.StatusMessage = "Country does not exist."; else if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) // then check if country is part of the list ReturnCode.StatusMessage = "Country does not exist."; if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0) > 0) if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0 && (String.Compare(s.StateCode, State, true) == 0 || String.Compare(s.Name, State, true) == 0)) <= 0) ReturnCode.StatusMessage = "State is invalid for this country."; if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); user = new User() { UserId = userId, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = userId.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = ip, StatusId = GlobalConfig.Visible, ActivationKey = Guid.NewGuid(), DateVerified = registDt }; try { if (Request.Cookies.AllKeys.Contains("tuid")) user.RegistrationCookie = Request.Cookies["tuid"].Value; else if (Request.Cookies.AllKeys.Contains("regcook")) user.RegistrationCookie = Request.Cookies["regcook"].Value; } catch (Exception) { } ////check for cookie try { var dt = DateTime.Parse(Request.Cookies["rcDate"].Value); if (registDt.Subtract(dt).Days < 45) { ReturnCode.StatusMessage = "We have detected that you have already registered using this machine."; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } } catch (Exception) { } string CurrencyCode = GlobalConfig.DefaultCurrency; var country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0); if (country != null) CurrencyCode = country.CurrencyCode; var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0); if (wallet == null) // Wallet does not exist. Create new wallet for User. { wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt); user.UserWallets.Add(wallet); } var transaction = new RegistrationTransaction() { RegisteredState = user.State, RegisteredCity = user.City, RegisteredCountryCode = user.CountryCode, Amount = 0, Currency = CurrencyCode, Reference = isSourceAir ? "New Registration (air)" : "New Registration", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { string verification_email = String.Format("{0}/User/Verify?key={1}", GlobalConfig.baseUrl, user.ActivationKey.ToString()); if (isSourceAir) { try { verification_email = String.Format("{0}&source=air", verification_email); var template = MyUtility.GetUrlContent(GlobalConfig.ProjectAirEmailVerificationBodyTemplateUrl); var htmlBody = String.Format(template, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", htmlBody, MailType.HtmlOnly, String.Empty); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } catch (Exception) { string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } } else { string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email); if (!Request.IsLocal) try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } } GSResponse res = null; if (!String.IsNullOrEmpty(uid) && !String.IsNullOrEmpty(provider)) { Dictionary<string, object> collection = new Dictionary<string, object>(); collection.Add("siteUID", user.UserId); collection.Add("uid", Uri.UnescapeDataString(uid)); collection.Add("cid", String.Format("{0} - New User", provider)); res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection)); if (res.GetErrorCode() == 0) //Successful link { if (user != null) { var UserId = user.UserId.ToString(); user.StatusId = GlobalConfig.Visible; //activate account user.DateVerified = DateTime.Now; SetAutheticationCookie(UserId); SetSession(UserId); if (!ContextHelper.SaveSessionInDatabase(context, user)) context.SaveChanges(); } } } else { var info = new GigyaUserInfo() { firstName = FirstName, lastName = LastName, email = EMail }; var registrationInfo = new GigyaNotifyLoginInfo() { siteUID = user.UserId.ToString(), cid = "TFCTV - Registration", sessionExpiration = 0, newUser = true, userInfo = Newtonsoft.Json.JsonConvert.SerializeObject(info) }; GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(registrationInfo)); res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", obj); } if (user != null) { if (user.StatusId == GlobalConfig.Visible) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } //authenticate user SetAutheticationCookie(user.UserId.ToString()); SendToGigya(user); SetSession(user.UserId.ToString()); ContextHelper.SaveSessionInDatabase(context, user); //add uid cookie HttpCookie uidCookie = new HttpCookie("uid"); uidCookie.Value = user.UserId.ToString(); uidCookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(uidCookie); } } GigyaHelpers.setCookie(res, this.ControllerContext); GigyaUserData2 userData = new GigyaUserData2() { city = user.City, country = user.CountryCode, email = user.EMail, firstName = user.FirstName, lastName = user.LastName, state = user.State }; //GigyaUserDataInfo userDataInfo = new GigyaUserDataInfo() //{ // UID = user.UserId.ToString(), // data = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None) //}; TFCTV.Helpers.UserData privacyData = new UserData() { IsExternalSharingEnabled = "true,false", IsInternalSharingEnabled = "true,false", IsProfilePrivate = "false" }; GigyaUserDataInfo2 userDataInfo = new GigyaUserDataInfo2() { UID = user.UserId.ToString(), profile = Newtonsoft.Json.JsonConvert.SerializeObject(userData, Formatting.None), data = Newtonsoft.Json.JsonConvert.SerializeObject(privacyData, Formatting.None) }; GSObject userDataInfoObj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(userDataInfo)); //res = GigyaHelpers.createAndSendRequest("gcs.setUserData", userDataInfoObj); res = GigyaHelpers.createAndSendRequest("ids.setAccountInfo", userDataInfoObj); var returnCode = res.GetErrorCode(); //Publish to Activity Feed List<ActionLink> actionlinks = new List<ActionLink>(); actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) }); //mediaItem List<MediaItem> mediaItems = new List<MediaItem>(); mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) }); UserAction action = new UserAction() { actorUID = userId.ToString(), userMessage = SNSTemplates.register_usermessage, title = SNSTemplates.register_title, subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle), linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback), description = String.Format(SNSTemplates.register_description, FirstName), actionLinks = actionlinks, mediaItems = mediaItems }; GigyaMethods.PublishUserAction(action, userId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, userId, "internal"); TempData["qs"] = null; // empty the TempData upon successful registration ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.info7 = user.EMail; if (user.StatusId == GlobalConfig.Visible) { ReturnCode.StatusHeader = "Your 7-Day Free Trial Starts Now!"; ReturnCode.StatusMessage = "Congratulations! You are now registered to TFC.tv."; ReturnCode.StatusMessage2 = "Pwede ka nang manood ng mga piling Kapamilya shows at movies!"; ReturnCode.info3 = user.UserId.ToString(); //Change to social registration ReturnCode.info = "SocialRegistration"; ReturnCode.TransactionType = "SocialRegistration"; } else { ReturnCode.StatusHeader = "Email verification sent!"; ReturnCode.StatusMessage = "Congratulations! You are one step away from completing your registration."; ReturnCode.StatusMessage2 = "An email has been sent to you.<br> Verify your email address to complete your registration."; } TempData["ErrorMessage"] = ReturnCode; //if(xoom) if (Request.Cookies.AllKeys.Contains("xoom")) { var userPromo = new UserPromo(); userPromo.UserId = user.UserId; userPromo.PromoId = GlobalConfig.Xoom2PromoId; userPromo.AuditTrail.CreatedOn = registDt; context.UserPromos.Add(userPromo); context.SaveChanges(); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); // successful registration } } else ReturnCode.StatusMessage = "Please fill in all required fields."; url = String.Format("{0}?{1}", Request.UrlReferrer.AbsolutePath, MyUtility.DictionaryToQueryString(tmpCollection)); } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public ActionResult _ResetYourPassword(FormCollection fc) { if (User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home"); var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; string url = Url.Action("ResetPassword", "User").ToString(); try { if (User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home"); DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { string NewPassword = tmpCollection["newPass"]; string CNewPassword = tmpCollection["cnewPass"]; string oid = tmpCollection["oid"]; string key = tmpCollection["key"]; //ViewBag.oid = oid; //ViewBag.key = key; //ViewBag.ts = MyUtility.ConvertToTimestamp(registDt); Guid temp_key; try { temp_key = Guid.Parse(key); } catch (Exception) { ReturnCode.StatusMessage = "The page you requested has an invalid key (key)."; } url = Url.Action("ResetPassword", "User", new { key = key, oid = oid }).ToString(); if (String.Compare(NewPassword, CNewPassword, false) != 0) ReturnCode.StatusMessage = "The passwords you entered do not match."; else { using (var context = new IPTV2Entities()) { var activation_key = new Guid(key); User user = context.Users.FirstOrDefault(u => u.ActivationKey == activation_key); if (user != null) { string oid_base = MyUtility.GetSHA1(String.Format("{0}{1}", user.UserId, user.LastUpdated)); if (registDt.Subtract(user.LastUpdated).TotalSeconds > 86400) ReturnCode.StatusMessage = "The page you requested has already expired."; else if (String.Compare(oid, oid_base, true) != 0) ReturnCode.StatusMessage = "The page you requested has an invalid key (oid)."; else { string hashedNewPassword = MyUtility.GetSHA1(NewPassword); user.Password = hashedNewPassword; user.LastUpdated = registDt; if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Reset Password Complete!"; ReturnCode.StatusMessage = "You've successfully updated your password."; ReturnCode.StatusMessage2 = String.Empty; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Home"); //Successful reset of password, redirect user login } else ReturnCode.StatusMessage = "We were unable to reset your password. Please try again."; } } else return RedirectToAction("ResetPassword", "User", new { key = key, oid = oid }); } } TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("ResetPassword", "User", new { key = key, oid = oid }); } else ReturnCode.StatusMessage = "Please fill in all required fields."; if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) TempData["ErrorMessage"] = ReturnCode.StatusMessage; } catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusMessage = "The system encountered an unspecified error."; } return Redirect(url); }
public ActionResult ForgotPassword(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = "The system encountered an unspecified error. Please contact Customer Support.", info = "Forget Password" }; string url = Url.Action("Index", "Home").ToString(); try { DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) { string EmailAddress = fc["forgotpassword_email"]; var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0); if (user == null) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "User does not exist."; TempData["ForgotPasswordErrorMessage"] = ReturnCode.StatusMessage; return Redirect(Request.UrlReferrer.AbsoluteUri); } if (user.StatusId != 1) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "Email address is not verified."; TempData["ForgotPasswordErrorMessage"] = ReturnCode.StatusMessage; return Redirect(Request.UrlReferrer.AbsoluteUri); } user.LastUpdated = registDt; if (context.SaveChanges() > 0) { string oid = MyUtility.GetSHA1(String.Format("{0}{1}", user.UserId, user.LastUpdated)); string reset_pwd_email = String.Format("{0}/User/ResetPassword?key={1}&oid={2}", GlobalConfig.baseUrl, user.ActivationKey, oid.ToLower()); string emailBody = String.Format(GlobalConfig.ResetPasswordBodyTextOnly, user.FirstName, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), reset_pwd_email); try { MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, "Reset your TFC.tv Password", emailBody, MailType.TextOnly, emailBody); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Instructions on how to reset your password have been sent to your email address."; } catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusCode = (int)ErrorCodes.UnknownError; ReturnCode.StatusMessage = "The system encountered an unspecified error. Please contact Customer Support."; TempData["ForgotPasswordErrorMessage"] = ReturnCode.StatusMessage; return Redirect(Request.UrlReferrer.AbsoluteUri); } } else { ReturnCode.StatusCode = (int)ErrorCodes.UnknownError; ReturnCode.StatusMessage = "The system was unable to process your request. Please try again later."; } } } catch (Exception e) { MyUtility.LogException(e); } if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) TempData["ForgotPasswordErrorMessage"] = ReturnCode.StatusMessage; url = Request.UrlReferrer.AbsoluteUri; return Redirect(url); }
public ActionResult _EditUserProfile(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; string url = Url.Action("EditYourProfile", "User").ToString(); var field_names = new string[] { "recurring_status", "disabled_list", "enabled_list", "internal_share", "external_share", "private_profile" }; try { if (!User.Identity.IsAuthenticated) return RedirectToAction("EditYourProfile", "User"); DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (!field_names.Contains(x.Key)) if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { string FirstName = tmpCollection["first_name"]; string LastName = tmpCollection["last_name"]; string CountryCode = tmpCollection["country"]; string City = tmpCollection["city"]; string State = tmpCollection["state"]; string browser = Request.UserAgent; if (FirstName.Length > 32) ReturnCode.StatusMessage = "First Name cannot exceed 32 characters."; if (LastName.Length > 32) ReturnCode.StatusMessage = "Last Name cannot exceed 32 characters."; if (State.Length > 30) ReturnCode.StatusMessage = "State cannot exceed 30 characters."; if (City.Length > 50) ReturnCode.StatusMessage = "City cannot exceed 50 characters."; var context = new IPTV2Entities(); var userId = new Guid(User.Identity.Name); User user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user == null) return RedirectToAction("Index", "Home"); if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) // check if country is part of the exclusion list first ReturnCode.StatusMessage = "Country does not exist."; else if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) // then check if country is part of the list ReturnCode.StatusMessage = "Country does not exist."; if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0) > 0) if (context.States.Count(s => String.Compare(s.CountryCode, CountryCode, true) == 0 && (String.Compare(s.StateCode, State, true) == 0 || String.Compare(s.Name, State, true) == 0)) <= 0) ReturnCode.StatusMessage = "State is invalid for this country."; if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) { TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("EditYourProfile", "User"); } string currentCountryCode = user.CountryCode; string newCountryCode = CountryCode; string currentCurrencyCode = user.Country.CurrencyCode; string newCurrencyCode = GlobalConfig.DefaultCurrency; //Update information that is not affected by country change user.FirstName = FirstName; user.LastName = LastName; user.LastUpdated = registDt; //Update privacy policy string IsInternalSharingEnabled = fc["internal_share"]; string IsExternalSharingEnabled = fc["external_share"]; string IsProfilePrivate = fc["private_profile"]; try { UserData userData = new UserData() { IsInternalSharingEnabled = IsInternalSharingEnabled, IsExternalSharingEnabled = IsExternalSharingEnabled, IsProfilePrivate = IsProfilePrivate }; GigyaMethods.SetUserData(user.UserId, userData); } catch (Exception) { } // Update recurring billing if (!String.IsNullOrEmpty(fc["disabled_list"])) UpdateRecurringBillingViaEditProfile2(context, user, fc["disabled_list"], false); if (!String.IsNullOrEmpty(fc["enabled_list"])) UpdateRecurringBillingViaEditProfile2(context, user, fc["enabled_list"], true); //Check if country of user changed if (String.Compare(user.CountryCode, CountryCode, true) != 0) { var offering = context.Offerings.Find(GlobalConfig.offeringId); //Get User Transactions if (user.HasOtherPendingGomsTransaction(offering)) ReturnCode.StatusMessage = "We are still processing your transactions. Please try again after a few minutes."; else if (user.HasPendingGomsChangeCountryTransaction(offering)) ReturnCode.StatusMessage = "We are processing your recent change in location. Please try again after a few minutes."; else if (user.HasTVEverywhereEntitlement(MyUtility.StringToIntList(GlobalConfig.TVEverywherePackageIds), offering)) ReturnCode.StatusMessage = "You are not allowed to change country being a TV Everywhere user."; else { var newCountry = context.Countries.FirstOrDefault(c => String.Compare(c.Code, newCountryCode, true) == 0); if (newCountry != null) newCurrencyCode = newCountry.CurrencyCode; var currentWallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, currentCurrencyCode, true) == 0); if (currentWallet == null) //If no wallet, get default USD wallet. currentWallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, GlobalConfig.DefaultCurrency, true) == 0); var newWallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, newCurrencyCode, true) == 0); decimal balance = 0; decimal currentWalletBalance = currentWallet.Balance; var currentGomsWalletId = currentWallet.GomsWalletId; if (newWallet == null) // new wallet currency does not exist. create new wallet for user { if (currentWallet != null) { balance = Forex.Convert(context, currentWallet.Currency, newCurrencyCode, currentWallet.Balance); currentWallet.Balance = 0; currentWallet.IsActive = false; currentWallet.LastUpdated = registDt; var wallet = ContextHelper.CreateWallet(balance, newCurrencyCode, registDt); user.UserWallets.Add(wallet); } } else // new wallet currency exists, update the balance onl { if (String.Compare(newCurrencyCode, currentCurrencyCode, true) != 0) { balance = Forex.Convert(context, currentWallet.Currency, newWallet.Currency, currentWallet.Balance); newWallet.Balance = balance; newWallet.IsActive = true; newWallet.LastUpdated = registDt; newWallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.Balance = 0; // Deactivate old wallet currentWallet.IsActive = false; //Deactivate currentWallet.LastUpdated = registDt; } else { newWallet.GomsWalletId = null; newWallet.LastUpdated = registDt; } } ChangeCountryTransaction transaction = new ChangeCountryTransaction() { OldCountryCode = currentCountryCode, NewCountryCode = newCountryCode, Date = registDt, OfferingId = GlobalConfig.offeringId, Reference = "Change Country", UserId = user.UserId, Amount = 0, NewWalletBalance = balance, OldWalletBalance = currentWalletBalance, OldGomsCustomerId = user.GomsCustomerId, OldGomsWalletId = currentGomsWalletId, Currency = currentCurrencyCode, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); user.CountryCode = CountryCode; } if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) { TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("EditYourProfile", "User"); } user.State = State; user.City = City; if (context.SaveChanges() > 0) { setUserData(user.UserId.ToString(), user); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Profile update complete!"; ReturnCode.StatusMessage = "You should see the changes on your profile automatically."; ReturnCode.StatusMessage2 = String.Empty; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Profile"); } else ReturnCode.StatusMessage = "Ooops! We encountered a problem updating your profile. Please try again later."; } else { user.City = City; user.State = State; if (context.SaveChanges() > 0) { setUserData(user.UserId.ToString(), user); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Profile update complete!"; ReturnCode.StatusMessage = "You should see the changes on your profile automatically."; ReturnCode.StatusMessage2 = String.Empty; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Profile"); } else ReturnCode.StatusMessage = "The system encountered an unspecified error while updating your profile. Please contact support."; } } else ReturnCode.StatusMessage = "Please fill in all required fields."; TempData["ErrorMessage"] = ReturnCode; url = Request.UrlReferrer.AbsolutePath; } catch (System.Data.Entity.Validation.DbEntityValidationException en) { MyUtility.LogException((Exception)en, string.Join(",", en.EntityValidationErrors).ToString()); } catch (Exception e) { MyUtility.LogException(e); } return Redirect(url); }
public ActionResult _LoginX(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); if (MyUtility.isUserLoggedIn()) //User is logged in. return RedirectToAction("Index", "Home"); try { ViewBag.IsTVEverywhere = false; string EmailAddress = fc["EmailAddress"]; string Password = fc["Password"]; if (String.IsNullOrEmpty(fc["EmailAddress"])) { errorCode = ErrorCodes.IsMissingRequiredFields; collection = MyUtility.setError(errorCode, "Email address is required."); return Content(MyUtility.buildJson(collection), "application/json"); } if (String.IsNullOrEmpty(fc["Password"])) { errorCode = ErrorCodes.IsMissingRequiredFields; collection = MyUtility.setError(errorCode, "Password is required."); return Content(MyUtility.buildJson(collection), "application/json"); } var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0); if (user == null) collection = MyUtility.setError(ErrorCodes.UserDoesNotExist); else { //if (user.StatusId != 1 && user.DateVerified == null) // Not verified if (user.StatusId != 1) // Not verified { errorCode = ErrorCodes.IsNotVerified; collection = MyUtility.setError(errorCode, "Email is not verified."); return Content(MyUtility.buildJson(collection), "application/json"); } Password = MyUtility.GetSHA1(Password); if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0) { Dictionary<string, object> userInfo = new Dictionary<string, object>(); userInfo.Add("firstName", user.FirstName); userInfo.Add("lastName", user.LastName); userInfo.Add("email", user.EMail); Dictionary<string, object> gigyaCollection = new Dictionary<string, object>(); gigyaCollection.Add("siteUID", user.UserId); gigyaCollection.Add("cid", "TFCTV - Login"); gigyaCollection.Add("sessionExpiration", "0"); gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection)); GigyaHelpers.setCookie(res, this.ControllerContext); errorMessage = "Login successful!"; //Session.SessionID; SetAutheticationCookie(user.UserId.ToString()); SetSession(user.UserId.ToString()); ContextHelper.SaveSessionInDatabase(context, user); //FormsAuthentication.SetAuthCookie(user.UserId.ToString(), true); collection = MyUtility.setError(ErrorCodes.Success, errorMessage); var UserHostAddress = Request.GetUserHostAddressFromCloudflare(); collection.Add("info", String.Format("{0}|{1}|{2}|{3}|{4}", user.EMail, UserHostAddress, "Site", MyUtility.getCountry(UserHostAddress).getCode(), DateTime.Now.ToString("yyyyMMdd-HHmmss"))); //UPDATE: FEB18,2013 - If TVE cookie is valid, assign user who logged in as TVERegistrant try { if (MyUtility.isTVECookieValid()) { user.IsTVERegistrant = true; context.SaveChanges(); MyUtility.RemoveTVECookie(); } if (user.IsTVEverywhere == true) { collection.Add("href", "/TFCChannel"); } } catch (Exception) { } } else collection = MyUtility.setError(ErrorCodes.IsWrongPassword); } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); //Debug.WriteLine(e.InnerException); throw; } return Content(MyUtility.buildJson(collection), "application/json"); }
public JsonResult _SignIn(FormCollection fc) { //Response.ContentType = "application/json"; var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = "The system encountered an unspecified error. Please contact Customer Support.", HtmlUri = "" }; try { ViewBag.IsTVEverywhere = false; string EmailAddress = fc["EmailAddress"]; string Password = fc["Password"]; if (String.IsNullOrEmpty(fc["EmailAddress"])) { ReturnCode.StatusCode = (int)ErrorCodes.IsMissingRequiredFields; ReturnCode.StatusMessage = "Email address is required."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (String.IsNullOrEmpty(fc["Password"])) { ReturnCode.StatusCode = (int)ErrorCodes.IsMissingRequiredFields; ReturnCode.StatusMessage = "Password is required."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (!Request.IsAjaxRequest()) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Your request is invalid."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } var context = new IPTV2Entities(); if (User.Identity.IsAuthenticated) { var UserId = new Guid(User.Identity.Name); var tUser = context.Users.FirstOrDefault(u => u.UserId == UserId); if (tUser != null) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Login successful. Please wait while we redirect you..."; var UserHostAddress = Request.GetUserHostAddressFromCloudflare(); ReturnCode.info = String.Format("{0}|{1}|{2}|{3}|{4}", tUser.EMail, UserHostAddress, "Site", MyUtility.getCountry(UserHostAddress).getCode(), DateTime.Now.ToString("yyyyMMdd-HHmmss")); //UPDATE: FEB18,2013 - If TVE cookie is valid, assign user who logged in as TVERegistrant try { if (tUser.IsTVEverywhere == true) ReturnCode.HtmlUri = "/TFCChannel"; } catch (Exception) { } } return Json(ReturnCode, JsonRequestBehavior.AllowGet); } var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0); if (user == null) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "User does not exist."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (user.StatusId != GlobalConfig.Visible) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "Email address is not verified."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } Password = MyUtility.GetSHA1(Password); if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0) { SendToGigya(user); SetAutheticationCookie(user.UserId.ToString()); SetSession(user.UserId.ToString()); ContextHelper.SaveSessionInDatabase(context, user); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Login successful. Please wait while we redirect you..."; var UserHostAddress = Request.GetUserHostAddressFromCloudflare(); ReturnCode.info = String.Format("{0}|{1}|{2}|{3}|{4}", user.EMail, UserHostAddress, "Site", MyUtility.getCountry(UserHostAddress).getCode(), DateTime.Now.ToString("yyyyMMdd-HHmmss")); //UPDATE: FEB18,2013 - If TVE cookie is valid, assign user who logged in as TVERegistrant try { if (MyUtility.isTVECookieValid()) { user.IsTVERegistrant = true; context.SaveChanges(); MyUtility.RemoveTVECookie(); ReturnCode.HtmlUri = "/RegisterTFCEverywhere"; } if (user.IsTVEverywhere == true) ReturnCode.HtmlUri = "/TFCChannel"; } catch (Exception) { } } else { ReturnCode.StatusCode = (int)ErrorCodes.IsMismatchPassword; ReturnCode.StatusMessage = "Email/Password do not match."; } return Json(ReturnCode, JsonRequestBehavior.AllowGet); } catch (Exception e) { MyUtility.LogException(e); } return Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public JsonResult _ChangePassword(FormCollection f) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; string currentPassword = f["Password"]; string newPassword = f["NewPassword"]; string confirmPassword = f["ConfirmPassword"]; if (String.IsNullOrEmpty(currentPassword) || String.IsNullOrEmpty(newPassword) || String.IsNullOrEmpty(confirmPassword)) { errorMessage = "Please fill in the required fields."; collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } if (String.Compare(newPassword, confirmPassword, false) != 0) { errorMessage = "Password mismatch."; collection = MyUtility.setError(ErrorCodes.IsMismatchPassword, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } try { System.Guid userId = System.Guid.Parse(User.Identity.Name); var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { string hashedPassword = MyUtility.GetSHA1(currentPassword); string hashedNewPassword = MyUtility.GetSHA1(newPassword); if (String.Compare(user.Password, hashedPassword, false) != 0) { errorMessage = "The current password you entered is incorrect. Please try again."; collection = MyUtility.setError(ErrorCodes.IsMismatchPassword, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } user.Password = hashedNewPassword; user.LastUpdated = registDt; if (context.SaveChanges() > 0) { errorMessage = "Your password has been changed succcessfully."; collection = MyUtility.setError(ErrorCodes.Success, errorMessage); } else { errorMessage = "The system encountered an unidentified error. Please try again."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); } } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); } return this.Json(collection, JsonRequestBehavior.AllowGet); }
//private void Send() //{ // //Trace.WriteLine(context.Database.Connection.ConnectionString); // try // { // var context = new IPTV2Entities(); // context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities"); // Trace.TraceInformation("Fetching users for recurring..."); // DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess"))); // var recurringBillings = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NextRun < dtRecur); // Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count())); // if (recurringBillings != null) // { // var gomsService = new GomsTfcTv(); // //Set Goms Values via Azure // gomsService.UserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvUserId"); // gomsService.Password = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvPassword"); // gomsService.ServiceUserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUserId"); // gomsService.ServicePassword = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServicePassword"); // gomsService.ServiceUrl = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUrl"); // gomsService.ServiceId = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceId")); // gomsService.GSapikey = RoleEnvironment.GetConfigurationSettingValue("GSapikey"); // gomsService.GSsecretkey = RoleEnvironment.GetConfigurationSettingValue("GSsecretkey"); // foreach (var i in recurringBillings) // { // Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", i.User.EMail, i.Product.Description, i.EndDate)); // try // { // ProductPrice priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == i.User.Country.CurrencyCode); // if (priceOfProduct == null) // priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode); // Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); // i.User.Purchases.Add(purchase); // PurchaseItem item = CreatePurchaseItem(i.UserId, i.Product, priceOfProduct); // purchase.PurchaseItems.Add(item); // var cardType = i.User.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; // CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() // { // Amount = priceOfProduct.Amount, // Currency = priceOfProduct.CurrencyCode, // Reference = cardType.ToUpper(), // Date = registDt, // Purchase = purchase, // OfferingId = offeringId, // StatusId = 1 // }; // var response = gomsService.CreateOrderViaRecurringPayment(context, i.UserId, transaction); // if (response.IsSuccess) // { // DateTime endDate = registDt; // item.SubscriptionProduct = (SubscriptionProduct)i.Product; // if (item.SubscriptionProduct is PackageSubscriptionProduct) // { // PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)i.Product; // foreach (var package in subscription.Packages) // { // string packageName = package.Package.Description; // string ProductNameBought = packageName; // PackageEntitlement currentPackage = i.User.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); // EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, i.Product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); // if (currentPackage != null) // { // request.StartDate = currentPackage.EndDate; // currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); // endDate = currentPackage.EndDate; // currentPackage.LatestEntitlementRequest = request; // request.EndDate = endDate; // } // else // { // PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); // request.EndDate = entitlement.EndDate; // i.User.PackageEntitlements.Add(entitlement); // } // i.User.EntitlementRequests.Add(request); // item.EntitlementRequest = request; //UPDATED: November 22, 2012 // } // i.EndDate = endDate; // i.NextRun = endDate.AddDays(-3).Date; // i.UpdatedOn = registDt; // } // } // else // throw new Exception(response.StatusMessage); // } // catch (Exception e) // { // Trace.TraceError(e.Message); // i.GomsRemarks = e.Message; // // TFCTV.Helpers.MyUtility.LogException(e, "Recurring Billing Scheduled Task"); // } // } // context.SaveChanges(); // } // } // catch (Exception e) // { // //TFCTV.Helpers.MyUtility.LogException(e); // Trace.TraceInformation("Error: " + e.Message); // Trace.TraceInformation("Inner Exception: " + e.InnerException.Message); // } //} private void Send() { //Trace.WriteLine(context.Database.Connection.ConnectionString); try { Trace.TraceInformation("Fetching users for recurring..."); DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess"))); var recurringBillings = GetUsersEligibleForRenewal(dtRecur); Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count())); if (recurringBillings != null) { using (var context = new IPTV2Entities()) { context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities"); var gomsService = new GomsTfcTv(); SetGomsServiceVariables(gomsService); try { gomsService.TestConnect(); Console.WriteLine("Test Connect success"); } catch (Exception) { Console.WriteLine("Test Connect failed."); } foreach (var i in recurringBillings) { var user = context.Users.FirstOrDefault(u => u.UserId == i.UserId); var recurringBilling = context.RecurringBillings.Find(i.RecurringBillingId); var product = context.Products.Find(i.ProductId); Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, i.EndDate)); try { ProductPrice priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId); if (priceOfProduct == null) priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId); Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); user.Purchases.Add(purchase); PurchaseItem item = CreatePurchaseItem(user.UserId, product, priceOfProduct); purchase.PurchaseItems.Add(item); var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() { Amount = priceOfProduct.Amount, Currency = priceOfProduct.CurrencyCode, Reference = cardType.ToUpper(), Date = registDt, Purchase = purchase, OfferingId = offeringId, StatusId = 1 }; var response = gomsService.CreateOrderViaRecurringPayment(context, user.UserId, transaction); if (response.IsSuccess) { DateTime endDate = registDt; item.SubscriptionProduct = (SubscriptionProduct)product; if (item.SubscriptionProduct is PackageSubscriptionProduct) { PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product; foreach (var package in subscription.Packages) { string packageName = package.Package.Description; string ProductNameBought = packageName; PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); if (currentPackage != null) { request.StartDate = currentPackage.EndDate; currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); endDate = currentPackage.EndDate; currentPackage.LatestEntitlementRequest = request; request.EndDate = endDate; } else { PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); request.EndDate = entitlement.EndDate; user.PackageEntitlements.Add(entitlement); } user.EntitlementRequests.Add(request); item.EntitlementRequest = request; //UPDATED: November 22, 2012 } recurringBilling.EndDate = endDate; recurringBilling.NextRun = endDate.AddDays(-3).Date; recurringBilling.UpdatedOn = registDt; recurringBilling.GomsRemarks = String.Empty; recurringBilling.NumberOfAttempts = 0; } Trace.TraceInformation(user.EMail + ": renewal process complete!"); } else { recurringBilling.GomsRemarks = response.StatusMessage; recurringBilling.NumberOfAttempts += 1; throw new Exception(user.EMail + ": " + response.StatusMessage); } } catch (Exception e) { Trace.TraceError("INNER ERROR: " + e.Message); } if (context.SaveChanges() > 0) Trace.TraceInformation("Saving changes..."); } } } } catch (Exception e) { Trace.TraceError("ERROR: " + e.Message); } }
public JsonResult _EnterPromo(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError) }; DateTime registDt = DateTime.Now; int promoID = GlobalConfig.TFCtvFirstYearAnniversaryPromoId; var userID = new System.Guid(User.Identity.Name); try { var context = new IPTV2Entities(); Promo promo = context.Promos.FirstOrDefault(p => p.PromoId == promoID && p.StatusId == GlobalConfig.Visible && p.EndDate > registDt && p.StartDate < registDt); if (promo != null) { UserPromo userPromo = context.UserPromos.FirstOrDefault(u => u.UserId == userID && u.PromoId == promoID); if (userPromo == null) userPromo = new UserPromo() { PromoId = promoID, UserId = userID, AuditTrail = new AuditTrail() { CreatedOn = DateTime.Now } }; context.UserPromos.Add(userPromo); if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "You have successfully joined the promo."; //adds points for each presconnected SNS var providers = GigyaMethods.GetUserInfoByKey(userID, "providers"); var providerList = providers.Split(','); foreach (string p in providerList) { if (!(String.Compare(p, "site") == 0)) { GigyaActionSingleAttribute actionAttribute = new GigyaActionSingleAttribute(); { actionAttribute.description = new List<string> { "You connected to " + p }; } GigyaMethods.NotifyAction(userID, AnniversaryPromo.AnnivPromo_LinkingSNS.ToString(), actionAttribute); } } } else { ReturnCode.StatusCode = (int)ErrorCodes.UnknownError; ReturnCode.StatusMessage = "You have already joined the promo."; } } } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public JsonResult LogUserToPromo() { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError) }; if (!Request.IsLocal) if (!Request.IsAjaxRequest()) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Your request is invalid."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (!User.Identity.IsAuthenticated) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Your request is invalid."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } try { var UserId = new Guid(User.Identity.Name); var registDt = DateTime.Now; var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.ProjectAirPromoId && p.StartDate < registDt && p.EndDate > registDt && p.StatusId == GlobalConfig.Visible); if (promo != null) { if (context.UserPromos.Count(p => p.PromoId == GlobalConfig.ProjectAirPromoId && p.UserId == user.UserId) <= 0) { var uObj = new UserPromo() { UserId = user.UserId, PromoId = promo.PromoId, AuditTrail = new AuditTrail() { CreatedOn = DateTime.Now } }; context.UserPromos.Add(uObj); if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Success"; } } } } } catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusMessage = e.Message; } return Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public ActionResult EditProfile(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; if (MyUtility.isUserLoggedIn()) { try { var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => u.UserId == new System.Guid(User.Identity.Name)); if (user != null) { string CurrencyCode = GlobalConfig.DefaultCurrency; string OldCountryCode = GlobalConfig.DefaultCountry; Country country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, user.CountryCode, true) == 0); if (country != null) { CurrencyCode = country.Currency.Code; country = null; OldCountryCode = user.Country.Code; } UserWallet currentWallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0); if (currentWallet == null) //If no wallet, get default USD wallet. currentWallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, GlobalConfig.DefaultCurrency, true) == 0); string newCountryCode = fc["CountryCode"]; user.FirstName = fc["FirstName"]; user.LastName = fc["LastName"]; user.City = fc["City"]; user.State = String.IsNullOrEmpty(fc["State"]) || fc["State"] == "" ? (String.IsNullOrEmpty(fc["StateDD"]) ? user.State : fc["StateDD"]) : fc["State"]; country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, newCountryCode, true) == 0); if (country != null) { Currency currency = country.Currency; CurrencyCode = (currency == null) ? GlobalConfig.DefaultCurrency : currency.Code; } UserWallet wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0); decimal balance = 0; decimal oldWalletBalance = currentWallet.Balance; string oldCurrency = currentWallet.Currency; if (wallet == null) // Wallet does not exist. Create new wallet for User. { if (currentWallet != null) { balance = currentWallet.Currency != CurrencyCode ? Forex.Convert(context, currentWallet.Currency, CurrencyCode, currentWallet.Balance) : currentWallet.Balance; //balance = currentWallet.Balance; currentWallet.Balance = 0; currentWallet.IsActive = false; currentWallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.LastUpdated = registDt; } wallet = ContextHelper.CreateWallet(balance, CurrencyCode, registDt); user.UserWallets.Add(wallet); } else // Wallet already exists. Update the balance only. { if (currentWallet.Currency != wallet.Currency) { balance = currentWallet.Currency != wallet.Currency ? Forex.Convert(context, currentWallet.Currency, wallet.Currency, currentWallet.Balance) : currentWallet.Balance; wallet.Balance = balance; //wallet.Balance += (currentWallet.Balance * 1); wallet.IsActive = true; wallet.LastUpdated = registDt; wallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.Balance = 0; // Deactivate old wallet currentWallet.IsActive = false; //Deactivate currentWallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.LastUpdated = registDt; } } user.CountryCode = newCountryCode; // Update user country user.LastUpdated = registDt; // lastUpdate if (OldCountryCode != newCountryCode) { ChangeCountryTransaction transaction = new ChangeCountryTransaction() { OldCountryCode = OldCountryCode, NewCountryCode = newCountryCode, Date = registDt, OfferingId = GlobalConfig.offeringId, Reference = "Change Country", UserId = user.UserId, Amount = 0, NewWalletBalance = balance, OldWalletBalance = oldWalletBalance, Currency = oldCurrency, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } if (context.SaveChanges() > 0) { //setUserData setUserData(user.UserId.ToString(), user); errorMessage = "Your information has been updated successfully."; collection = MyUtility.setError(ErrorCodes.Success, errorMessage); } else { errorMessage = "Error in updating your profile."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); } } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); } } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult Register(FormCollection fc) { SynapseResponse response = new SynapseResponse(); Dictionary<string, object> collection = new Dictionary<string, object>(); response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated; response.errorMessage = @"Please go to http://tfc.tv to register."; return this.Json(response, JsonRequestBehavior.AllowGet); if (MyUtility.isUserLoggedIn()) //User is logged in. { response.errorCode = (int)ErrorCodes.IsAlreadyAuthenticated; response.errorMessage = "User is already authenticated."; return this.Json(response, JsonRequestBehavior.AllowGet); } if (String.IsNullOrEmpty(fc["Email"])) { response.errorCode = (int)ErrorCodes.IsEmailEmpty; response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsEmailEmpty); return this.Json(response, JsonRequestBehavior.AllowGet); } if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0) { response.errorCode = (int)ErrorCodes.IsMismatchPassword; response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMismatchPassword); return this.Json(response, JsonRequestBehavior.AllowGet); } if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"])) { response.errorCode = (int)ErrorCodes.IsMissingRequiredFields; response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsMissingRequiredFields); return this.Json(response, JsonRequestBehavior.AllowGet); } try { string FirstName = fc["FirstName"]; string LastName = fc["LastName"]; string CountryCode = fc["CountryCode"]; string EMail = fc["Email"]; string Password = fc["Password"]; string City = fc["City"]; string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"]; System.Guid userId = System.Guid.NewGuid(); if (FirstName.Length > 32) { response.errorCode = (int)ErrorCodes.LimitReached; response.errorMessage = "First Name cannot exceed 32 characters."; return this.Json(response, JsonRequestBehavior.AllowGet); } if (LastName.Length > 32) { response.errorCode = (int)ErrorCodes.LimitReached; response.errorMessage = "Last Name cannot exceed 32 characters."; return this.Json(response, JsonRequestBehavior.AllowGet); } if (EMail.Length > 64) { response.errorCode = (int)ErrorCodes.LimitReached; response.errorMessage = "Email cannot exceed 64 characters."; return this.Json(response, JsonRequestBehavior.AllowGet); } if (!String.IsNullOrEmpty(State)) if (State.Length > 30) { response.errorCode = (int)ErrorCodes.LimitReached; response.errorMessage = "State cannot exceed 30 characters."; return this.Json(response, JsonRequestBehavior.AllowGet); } if (!String.IsNullOrEmpty(City)) if (City.Length > 50) { response.errorCode = (int)ErrorCodes.LimitReached; response.errorMessage = "City cannot exceed 50 characters."; return this.Json(response, JsonRequestBehavior.AllowGet); } var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0); if (user != null) { response.errorCode = (int)ErrorCodes.IsExistingEmail; response.errorMessage = MyUtility.getErrorMessage(ErrorCodes.IsExistingEmail); return this.Json(response, JsonRequestBehavior.AllowGet); } /***** CHECK FOR COUNTRY CODE ****/ if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) { response.errorCode = (int)ErrorCodes.IsMissingRequiredFields; response.errorMessage = "Country Code is invalid."; return this.Json(response, JsonRequestBehavior.AllowGet); } else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) { response.errorCode = (int)ErrorCodes.IsMissingRequiredFields; response.errorMessage = "Country Code is invalid."; return this.Json(response, JsonRequestBehavior.AllowGet); } DateTime registDt = DateTime.Now; user = new User() { UserId = userId, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = userId.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = Request.GetUserHostAddressFromCloudflare(), StatusId = 1, ActivationKey = Guid.NewGuid(), DateVerified = registDt }; string CurrencyCode = GlobalConfig.DefaultCurrency; Country country = context.Countries.FirstOrDefault(c => String.Compare(c.Code, CountryCode, true) == 0); if (country != null) { Currency currency = context.Currencies.FirstOrDefault(c => String.Compare(c.Code, country.CurrencyCode, true) == 0); if (currency != null) CurrencyCode = currency.Code; } UserWallet wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, CurrencyCode, true) == 0); if (wallet == null) // Wallet does not exist. Create new wallet for User. { wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt); user.UserWallets.Add(wallet); } var transaction = new RegistrationTransaction() { RegisteredState = user.State, RegisteredCity = user.City, RegisteredCountryCode = user.CountryCode, Amount = 0, Currency = CurrencyCode, Reference = "New Registration (Mobile)", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { if (!String.IsNullOrEmpty(fc["UID"])) { Dictionary<string, object> GigyaCollection = new Dictionary<string, object>(); collection.Add("uid", fc["UID"]); collection.Add("siteUID", userId); collection.Add("cid", String.Format("{0} - New User", fc["provider"])); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection)); } else { Dictionary<string, object> userInfo = new Dictionary<string, object>(); userInfo.Add("firstName", user.FirstName); userInfo.Add("lastName", user.LastName); userInfo.Add("email", user.EMail); Dictionary<string, object> gigyaCollection = new Dictionary<string, object>(); gigyaCollection.Add("siteUID", user.UserId); gigyaCollection.Add("cid", "TFCTV - Registration"); gigyaCollection.Add("sessionExpiration", "0"); gigyaCollection.Add("newUser", true); gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection)); GigyaHelpers.setCookie(res, this.ControllerContext); } //setUserData User usr = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0); setUserData(usr.UserId.ToString(), usr); if (usr.IsTVERegistrant == null || usr.IsTVERegistrant == false) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); context = new IPTV2Entities(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } //if (user.StatusId == GlobalConfig.Visible) PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } } //Publish to Activity Feed List<ActionLink> actionlinks = new List<ActionLink>(); actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = SNSTemplates.register_actionlink_href }); UserAction action = new UserAction() { actorUID = userId.ToString(), userMessage = SNSTemplates.register_usermessage, title = SNSTemplates.register_title, subtitle = SNSTemplates.register_subtitle, linkBack = SNSTemplates.register_linkback, description = String.Format(SNSTemplates.register_description, FirstName), actionLinks = actionlinks }; GigyaMethods.PublishUserAction(action, userId, "external"); action.userMessage = String.Empty; action.title = String.Empty; GigyaMethods.PublishUserAction(action, userId, "internal"); //string verification_email = String.Format("{0}/User/Verify?email={1}&key={2}", GlobalConfig.baseUrl, EMail, user.ActivationKey.ToString()); //string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, FirstName, EMail, verification_email); //if (!Request.IsLocal) // try { MyUtility.SendEmailViaSendGrid(EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } // catch (Exception e) { MyUtility.LogException(e, "Unable to send email via SendGrid"); } response.errorCode = (int)ErrorCodes.Success; response.errorMessage = "Registration successful."; GSResponse gres = GetToken(user); if (gres != null) { SynapseToken token = new SynapseToken() { uid = user.UserId.ToString(), token = gres.GetString("access_token", String.Empty), expire = gres.GetInt("expires_in", 0), }; response.data = token; } HttpCookie authCookie = SetAutheticationCookie(user.UserId.ToString()); SynapseCookie cookie = new SynapseCookie() { cookieName = authCookie.Name, cookieDomain = authCookie.Domain, cookiePath = authCookie.Path, cookieValue = authCookie.Value }; response.info = cookie; } else { response.errorCode = (int)ErrorCodes.EntityUpdateError; response.errorMessage = "Unable to register user"; } } catch (Exception e) { response.errorCode = (int)ErrorCodes.UnknownError; response.errorMessage = e.Message; } return this.Json(response, JsonRequestBehavior.AllowGet); }
public RespConsumePrepaidCard UsePrepaidCard(IPTV2Entities context, System.Guid userId, Transaction transaction) { RespConsumePrepaidCard result = null; InitializeServiceClient(); try { // validate user GomsException validationResult = UserValidation(context, userId); if (!(validationResult is GomsSuccess)) { throw validationResult; } var user = context.Users.Find(userId); if ((transaction == null) || (transaction.TransactionId == 0)) { throw new GomsInvalidTransactionException(); } if (transaction is PpcPaymentTransaction | transaction is PpcReloadTransaction) { // prepare request var req = new ReqConsumePrepaidCard { UID = ServiceUserId, PWD = ServicePassword, Email = user.EMail, CustomerId = (int)user.GomsCustomerId, ServiceId = (int)user.GomsServiceId, SubsidiaryId = (int)user.GomsSubsidiaryId, WalletId = (int)user.GomsWalletId, PhoenixId = transaction.TransactionId, TransactionDate = transaction.Date, Amount = (double)transaction.Amount // TODO: use transactionID or use base number // PhoenixId=(int)(DateTime.Now.Ticks - int.MaxValue), }; if (transaction is PpcReloadTransaction) { var reloadTransaction = (PpcReloadTransaction)transaction; req.PPCPin = reloadTransaction.ReloadPpc.Pin; req.PPCSerial = reloadTransaction.ReloadPpc.SerialNumber; req.CurrencyId = (int)context.Currencies.Find(reloadTransaction.ReloadPpc.Currency).GomsId; } else if (transaction is PpcPaymentTransaction) { var paymentTransaction = (PpcPaymentTransaction)transaction; int currencyId = 0; string curr = transaction.Currency; if (transaction.Currency == "---") { currencyId = (int)paymentTransaction.User.Country.Currency.GomsId; curr = paymentTransaction.User.Country.CurrencyCode; } else { currencyId = (int)context.Currencies.Find(paymentTransaction.Currency).GomsId; } req.PPCPin = paymentTransaction.SubscriptionPpc.Pin; req.PPCSerial = paymentTransaction.SubscriptionPpc.SerialNumber; req.CurrencyId = currencyId; var item = paymentTransaction.Purchase.PurchaseItems.FirstOrDefault(); if (item != null) { var endDate = item.EntitlementRequest.EndDate; var startDate = endDate; switch (item.SubscriptionProduct.DurationType.ToUpper()) { case "D": { startDate = endDate.AddDays(item.SubscriptionProduct.Duration * -1); break; }; case "M": { startDate = endDate.AddMonths(item.SubscriptionProduct.Duration * -1); break; }; case "Y": { startDate = endDate.AddYears(item.SubscriptionProduct.Duration * -1); break; }; default: { break; } } req.SubscriptionStartDate = startDate; req.SubscriptionEndDate = endDate; } } else { throw new GomsInvalidTransactionTypeException(); } try { result = _serviceClient.ConsumePrepaidCard(req); if (result.IsSuccess) { transaction.GomsTransactionId = result.TransactionId; transaction.GomsTransactionDate = DateTime.Now; context.SaveChanges(); } } catch (Exception e) { throw new GomsServiceCallException(e.Message); } } else { throw new GomsInvalidTransactionTypeException(); } } catch (GomsException e) { result = new RespConsumePrepaidCard { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage }; } return (result); }
public ActionResult UpdateRecurringProducts(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; collection = MyUtility.setError(errorCode, "Unable to update. Please contact support."); try { DateTime registDt = DateTime.Now; var status = fc["value"]; var name = fc["name"]; if (!String.IsNullOrEmpty(status) && !String.IsNullOrEmpty(name)) { if (MyUtility.isUserLoggedIn()) { var context = new IPTV2Entities(); bool RecurringStatus = false; try { RecurringStatus = Convert.ToBoolean(status); } catch (Exception e) { MyUtility.LogException(e); } int RecurringBillingId = 0; try { RecurringBillingId = Convert.ToInt32(name.Substring(2)); } catch (Exception e) { MyUtility.LogException(e); } var userId = new Guid(User.Identity.Name); var user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { var billing = user.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == RecurringBillingId && r.StatusId != 2); if (billing != null) { //Check first if there is a same package with recurring turned on if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0) { //there is same package with recurring enabled. collection = MyUtility.setError(ErrorCodes.UnknownError, "There is same recurring package enabled."); } else { billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; if (registDt.Date > billing.NextRun && RecurringStatus) billing.NextRun = registDt.AddDays(1).Date; if (context.SaveChanges() > 0) collection = MyUtility.setError(ErrorCodes.Success, "Success!"); else collection = MyUtility.setError(ErrorCodes.EntityUpdateError, "Unable to update. Please try again later."); } } } else collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, "User does not exist."); } else collection = MyUtility.setError(ErrorCodes.NotAuthenticated, "Not authenticated."); } } catch (Exception e) { MyUtility.LogException(e); } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult _Registration(FormCollection fc) { //fc["Email"] = "*****@*****.**"; //fc["Password"] = "******"; //fc["ConfirmPassword"] = "******"; //fc["FirstName"] = "Albin"; //fc["LastName"] = "Lim"; //fc["CountryCode"] = "US"; //fc["City"] = "CA"; //fc["State"] = "CA"; Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); if (!Request.IsAjaxRequest()) { collection = MyUtility.setError(ErrorCodes.UnknownError, "Your request is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } bool isConnectedToSocialNetworks = false; string href = "/User/RegisterVerify"; if (MyUtility.isUserLoggedIn()) //User is logged in. return RedirectToAction("Index", "Home"); if (String.IsNullOrEmpty(fc["Email"])) { collection = MyUtility.setError(ErrorCodes.IsEmailEmpty); return Content(MyUtility.buildJson(collection), "application/json"); } if (String.Compare(fc["Password"], fc["ConfirmPassword"], false) != 0) { collection = MyUtility.setError(ErrorCodes.IsMismatchPassword); return Content(MyUtility.buildJson(collection), "application/json"); } if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"])) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields); return Content(MyUtility.buildJson(collection), "application/json"); } RegexUtilities util = new RegexUtilities(); //if (!MyUtility.isEmail(fc["Email"])) if (!util.IsValidEmail(fc["Email"])) { collection = MyUtility.setError(ErrorCodes.IsNotValidEmail); return Content(MyUtility.buildJson(collection), "application/json"); } try { string FirstName = fc["FirstName"]; string LastName = fc["LastName"]; string CountryCode = fc["CountryCode"]; string EMail = fc["Email"]; string Password = fc["Password"]; string City = fc["City"]; string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"]; System.Guid userId = System.Guid.NewGuid(); string provider = "tfctv"; if (FirstName.Length > 32) { collection = MyUtility.setError(ErrorCodes.LimitReached, "First Name cannot exceed 32 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (LastName.Length > 32) { collection = MyUtility.setError(ErrorCodes.LimitReached, "Last Name cannot exceed 32 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (EMail.Length > 64) { collection = MyUtility.setError(ErrorCodes.LimitReached, "Email cannot exceed 64 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (!String.IsNullOrEmpty(State)) if (State.Length > 30) { collection = MyUtility.setError(ErrorCodes.LimitReached, "State cannot exceed 30 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (!String.IsNullOrEmpty(City)) if (City.Length > 50) { collection = MyUtility.setError(ErrorCodes.LimitReached, "City cannot exceed 50 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EMail, true) == 0); if (user != null) { collection = MyUtility.setError(ErrorCodes.IsExistingEmail); return Content(MyUtility.buildJson(collection), "application/json"); } /***** CHECK FOR COUNTRY CODE ****/ if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } if (String.IsNullOrEmpty(State)) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is required."); return Content(MyUtility.buildJson(collection), "application/json"); } else { if (context.States.Count(c => c.CountryCode == CountryCode.ToUpper()) > 0) { if (context.States.Count(s => s.CountryCode == CountryCode.ToUpper() && (s.StateCode == State || s.Name == State)) == 0) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } } } DateTime registDt = DateTime.Now; user = new User() { UserId = userId, FirstName = FirstName, LastName = LastName, City = City, State = State, CountryCode = CountryCode, EMail = EMail, Password = MyUtility.GetSHA1(Password), GigyaUID = userId.ToString(), RegistrationDate = registDt, LastUpdated = registDt, RegistrationIp = Request.GetUserHostAddressFromCloudflare(), StatusId = 0, ActivationKey = Guid.NewGuid() }; //UPDATE: FEB 18, 2013 if (MyUtility.isTVECookieValid()) user.IsTVERegistrant = true; string CurrencyCode = GlobalConfig.DefaultCurrency; Country country = context.Countries.FirstOrDefault(c => c.Code == CountryCode); if (country != null) { Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode); if (currency != null) CurrencyCode = currency.Code; } UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode); if (wallet == null) // Wallet does not exist. Create new wallet for User. { wallet = ContextHelper.CreateWallet(0, CurrencyCode, registDt); user.UserWallets.Add(wallet); } var transaction = new RegistrationTransaction() { RegisteredState = user.State, RegisteredCity = user.City, RegisteredCountryCode = user.CountryCode, Amount = 0, Currency = CurrencyCode, Reference = "New Registration", Date = registDt, OfferingId = GlobalConfig.offeringId, UserId = user.UserId, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); context.Users.Add(user); if (context.SaveChanges() > 0) { if (TempData["qs"] != null) { NameValueCollection qs = (NameValueCollection)TempData["qs"]; Dictionary<string, object> GigyaCollection = new Dictionary<string, object>(); collection.Add("uid", qs["UID"]); collection.Add("siteUID", userId); collection.Add("cid", String.Format("{0} - New User", qs["provider"])); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection)); provider = qs["provider"]; isConnectedToSocialNetworks = true; } else { Dictionary<string, object> userInfo = new Dictionary<string, object>(); userInfo.Add("firstName", user.FirstName); userInfo.Add("lastName", user.LastName); userInfo.Add("email", user.EMail); Dictionary<string, object> gigyaCollection = new Dictionary<string, object>(); gigyaCollection.Add("siteUID", user.UserId); gigyaCollection.Add("cid", "TFCTV - Registration"); gigyaCollection.Add("sessionExpiration", "0"); gigyaCollection.Add("newUser", true); gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection)); GigyaHelpers.setCookie(res, this.ControllerContext); } //setUserData User usr = context.Users.FirstOrDefault(u => u.EMail == EMail); setUserData(usr.UserId.ToString(), usr); var ActivationKey = usr.ActivationKey; bool isTFCnowCustomer = false; if (TempData["TFCnowCustomer"] != null) { Customer customer = (Customer)TempData["TFCnowCustomer"]; usr.StatusId = 1; usr.DateVerified = registDt; TempData["TFCnowCustomer"] = customer; href = "/Migration/Migrate"; if (context.SaveChanges() > 0) { //SetAutheticationCookie(userId.ToString()); isTFCnowCustomer = true; } } if (isConnectedToSocialNetworks) { usr.StatusId = 1; usr.DateVerified = registDt; context.SaveChanges(); } //If FreeTrial is enabled, insert free trial. //if (GlobalConfig.IsFreeTrialEnabled) //{ // context = new IPTV2Entities(); // if (isConnectedToSocialNetworks) // PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial14ProductId, SubscriptionProductType.Package, userId, null); // else // PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial7ProductId, SubscriptionProductType.Package, userId, null); // context.SaveChanges(); //} /***** DEC 31 2012 ****/ //UPDATED: FEB 18, 2013 - To include checking for TVE if (usr.IsTVERegistrant == null || usr.IsTVERegistrant == false) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); context = new IPTV2Entities(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } if (Request.Cookies.AllKeys.Contains("vntycok")) { freeTrialProductId = GlobalConfig.FreeTrial14ProductId; } if (isConnectedToSocialNetworks) PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } } //Publish to Activity Feed List<ActionLink> actionlinks = new List<ActionLink>(); actionlinks.Add(new ActionLink() { text = SNSTemplates.register_actionlink_text, href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_actionlink_href) }); //mediaItem List<MediaItem> mediaItems = new List<MediaItem>(); mediaItems.Add(new MediaItem() { type = SNSTemplates.register_mediaitem_type, src = String.Format("{0}{1}", GlobalConfig.AssetsBaseUrl, SNSTemplates.register_mediaitem_src), href = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_mediaitem_href) }); UserAction action = new UserAction() { actorUID = userId.ToString(), userMessage = SNSTemplates.register_usermessage, title = SNSTemplates.register_title, subtitle = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_subtitle), linkBack = String.Format("{0}{1}", GlobalConfig.baseUrl, SNSTemplates.register_linkback), description = String.Format(SNSTemplates.register_description, FirstName), actionLinks = actionlinks, mediaItems = mediaItems }; GigyaMethods.PublishUserAction(action, userId, "external"); action.userMessage = String.Empty; action.title = String.Empty; action.mediaItems = null; GigyaMethods.PublishUserAction(action, userId, "internal"); var email_err = String.Empty; //FormsAuthentication.SetAuthCookie(userId.ToString(), true); if (isConnectedToSocialNetworks) { //SetAutheticationCookie(userId.ToString()); if (!Request.IsLocal) { try { MyUtility.SendConfirmationEmail(context, usr); } catch (Exception) { } } href = GlobalConfig.RegistrationConfirmPage; //UPDATED: FEB 18, 2013 if (usr.IsTVERegistrant != null) if ((bool)usr.IsTVERegistrant) { href = GlobalConfig.TVERegistrationPage; MyUtility.RemoveTVECookie(); } } else { if (!isTFCnowCustomer) { //string emailBody = String.Format("Copy and paste this url to activate your TFC.tv Account {0}/User/Verify?email={1}&key={2}", GlobalConfig.baseUrl, usr.EMail, ActivationKey.ToString()); string verification_email = String.Format("{0}/User/Verify?key={1}", GlobalConfig.baseUrl, usr.ActivationKey.ToString()); string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, usr.FirstName, usr.EMail, verification_email); //MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody); if (!Request.IsLocal) try { //MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody); MyUtility.SendEmailViaSendGrid(usr.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody); } catch (Exception) { email_err = " But we are not able to send the verification email."; } } } ////UPDATED: FEB 12, 2012 //if (!String.IsNullOrEmpty(fc["TVEverywhere"])) //{ // if (String.Compare(fc["TVEverywhere"], "0", true) == 0) // { // TempData["tempUserId"] = userId; // href = GlobalConfig.TVERegistrationPage; // TempData["isConnectedToSocialNetworks"] = isConnectedToSocialNetworks; // } //} if (usr.StatusId == GlobalConfig.Visible) //UPDATED: MARCH 1, 2013. Only set Authentication Cookie when user is verified. SetAutheticationCookie(userId.ToString()); errorMessage = "Thank you! You are now registered to TFC.tv!" + email_err; collection = MyUtility.setError(ErrorCodes.Success, errorMessage); collection.Add("info", String.Format("{0}|{1}|{2}", user.EMail, Request.GetUserHostAddressFromCloudflare(), provider)); collection.Add("href", href); FlagBetaKey(fc["iid"]); } else { errorMessage = "The system encountered an unidentified error. Please try again."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.EntityUpdateError, e.InnerException.InnerException.Message + "<br/>" + e.InnerException.InnerException.StackTrace); } return Content(MyUtility.buildJson(collection), "application/json"); }
public JsonResult _ForgotPassword(FormCollection f) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; string email = f["EmailAddress"]; if (String.IsNullOrEmpty(email)) { errorMessage = "Please fill in the required fields."; collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } try { var context = new IPTV2Entities(); User user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0); if (user != null) { //Guid randomGuid = System.Guid.NewGuid(); //string newPassword = randomGuid.ToString().Substring(0, 8); //string hashedPassword = MyUtility.GetSHA1(newPassword); //user.Password = hashedPassword; //user.LastUpdated = registDt; //if (context.SaveChanges() > 0) //{ // var mailer = new UserMailer(); // var msg = mailer.ForgotPassword(to: user.EMail, password: newPassword); // msg.SendAsync(); // errorMessage = "Your password has been changed succcessfully."; // collection = MyUtility.setError(ErrorCodes.Success, errorMessage); //} //else //{ // errorMessage = "The system encountered an unidentified error. Please try again."; // collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); //} if (user.StatusId != 1) { errorMessage = "Email has not been verified."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } user.LastUpdated = registDt; if (context.SaveChanges() > 0) { string oid = MyUtility.GetSHA1(String.Format("{0}{1}", user.UserId, user.LastUpdated)); string reset_pwd_email = String.Format("{0}/User/ResetPassword?key={1}&oid={2}", GlobalConfig.baseUrl, user.ActivationKey, oid.ToLower()); string emailBody = String.Format(GlobalConfig.ResetPasswordBodyTextOnly, user.FirstName, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), reset_pwd_email); try { //MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody); MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, "Reset your TFC.tv Password", emailBody, MailType.TextOnly, emailBody); collection = MyUtility.setError(ErrorCodes.Success, "Instructions on how to reset your password has been sent."); } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.InnerException.Message); } } } else { errorMessage = "Email does not exist."; collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, errorMessage); } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, e.Message); } return this.Json(collection, JsonRequestBehavior.AllowGet); }
public ActionResult _ForgetPassword(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = "The system encountered an unspecified error. Please contact Customer Support." }; try { var registDt = DateTime.Now; string EmailAddress = fc["FEmailAddress"]; if (String.IsNullOrEmpty(fc["FEmailAddress"])) { ReturnCode.StatusCode = (int)ErrorCodes.IsMissingRequiredFields; ReturnCode.StatusMessage = "Email address is required."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } //RegexUtilities util = new RegexUtilities(); if (!MyUtility.isEmail(EmailAddress)) { ReturnCode.StatusMessage = "Email address is invalid."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (!Request.IsAjaxRequest()) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Your request is invalid."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0); if (user == null) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "User does not exist."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (user.StatusId != GlobalConfig.Visible) { ReturnCode.StatusCode = (int)ErrorCodes.UserDoesNotExist; ReturnCode.StatusMessage = "Email address is not verified."; return Json(ReturnCode, JsonRequestBehavior.AllowGet); } user.LastUpdated = registDt; if (context.SaveChanges() > 0) { string oid = MyUtility.GetSHA1(String.Format("{0}{1}", user.UserId, user.LastUpdated)); string reset_pwd_email = String.Format("{0}/User/ResetPassword?key={1}&oid={2}", GlobalConfig.baseUrl, user.ActivationKey, oid.ToLower()); string emailBody = String.Format(GlobalConfig.ResetPasswordBodyTextOnly, user.FirstName, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), reset_pwd_email); try { MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, "Reset your TFC.tv Password", emailBody, MailType.TextOnly, emailBody); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "Instructions on how to reset your password have been sent to your email address."; } catch (Exception e) { MyUtility.LogException(e); ReturnCode.StatusCode = (int)ErrorCodes.UnknownError; ReturnCode.StatusMessage = "The system encountered an unspecified error. Please contact Customer Support."; } } else { ReturnCode.StatusCode = (int)ErrorCodes.UnknownError; ReturnCode.StatusMessage = "The system was unable to process your request. Please try again later."; } return Json(ReturnCode, JsonRequestBehavior.AllowGet); } catch (Exception e) { MyUtility.LogException(e); } return Json(ReturnCode, JsonRequestBehavior.AllowGet); }
//public ActionResult ResendVerification() //{ // if (MyUtility.isUserLoggedIn()) // return RedirectToAction("Index", "Home"); // return View(); //} public ActionResult Verify(string key, string source) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty, info = "Activation", TransactionType = "Activation" }; string url = Url.Action("Index", "Home").ToString(); try { if (String.IsNullOrEmpty(key)) ReturnCode.StatusMessage = "You are missing some required information."; else { var registDt = DateTime.Now; var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => u.ActivationKey == new Guid(key)); if (user != null) { if (user.StatusId == 0 || user.StatusId == null) { user.StatusId = GlobalConfig.Visible; user.DateVerified = DateTime.Now; Guid userId = user.UserId; if (context.SaveChanges() > 0) { //if (xoomPromo != null) //{ // var xoomUserPromo = context.UserPromos.FirstOrDefault(u => u.PromoId == GlobalConfig.Xoom2PromoId && u.UserId == user.UserId); // if (xoomUserPromo != null) // { // SetAutheticationCookie(user.UserId.ToString()); // SendToGigya(user); // SetSession(user.UserId.ToString()); // ContextHelper.SaveSessionInDatabase(context, user); // //add uid cookie // HttpCookie uidCookie = new HttpCookie("uid"); // uidCookie.Value = user.UserId.ToString(); // uidCookie.Expires = DateTime.Now.AddDays(30); // Response.Cookies.Add(uidCookie); // if (!Request.IsLocal) // if (user.IsTVERegistrant == null || user.IsTVERegistrant == false) //If user is TVE, do not send email // if (!String.IsNullOrEmpty("source")) // MyUtility.SendConfirmationEmailAir(context, user); // else // MyUtility.SendConfirmationEmail(context, user); // ReturnCode.StatusCode = (int)ErrorCodes.Success; // ReturnCode.StatusHeader = "Congratulations! You are now registered to TFC.tv."; // ReturnCode.StatusMessage = "You are one step away from claiming your free 1 Month Premium Subscription."; // //ReturnCode.StatusMessage2 = "Pwede ka nang manood ng mga piling Kapamilya shows at movies!"; // TempData["ErrorMessage"] = ReturnCode; // return RedirectToAction("Details", "Subscribe", new { id = "xoom" }); // } //} bool IsEligibleForXoomPromo = false; try { var xoomPromo = context.Promos.FirstOrDefault(u => u.PromoId == GlobalConfig.Xoom2PromoId && u.StartDate < registDt && u.EndDate > registDt && u.StatusId == GlobalConfig.Visible); if (xoomPromo != null) { var xoomUserPromo = context.UserPromos.FirstOrDefault(u => u.PromoId == GlobalConfig.Xoom2PromoId && u.UserId == user.UserId); if (xoomUserPromo != null) IsEligibleForXoomPromo = true; } } catch (Exception) { } if (user.IsTVERegistrant == null || user.IsTVERegistrant == false) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled && !IsEligibleForXoomPromo) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } if (Request.Cookies.AllKeys.Contains("vntycok") || GlobalConfig.Country14DayTrials.Contains(user.CountryCode)) freeTrialProductId = GlobalConfig.FreeTrial14ProductId; PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } if (GlobalConfig.IsABSCBNFreeLiveStreamFreeOnRegistrationEnabled) if (GlobalConfig.ABSCBNFreeLiveStreamStartDate < registDt && GlobalConfig.ABSCBNFreeLiveStreamEndDate > registDt) PaymentHelper.PayViaWallet(context, userId, GlobalConfig.ABSCBNFreeLiveStreamProductId, SubscriptionProductType.Package, userId, null); SetAutheticationCookie(user.UserId.ToString()); SendToGigya(user); SetSession(user.UserId.ToString()); ContextHelper.SaveSessionInDatabase(context, user); //add uid cookie HttpCookie uidCookie = new HttpCookie("uid"); uidCookie.Value = user.UserId.ToString(); uidCookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(uidCookie); if (!Request.IsLocal) if (user.IsTVERegistrant == null || user.IsTVERegistrant == false) //If user is TVE, do not send email if (!String.IsNullOrEmpty(source)) MyUtility.SendConfirmationEmailAir(context, user); else MyUtility.SendWelcomeEmail(context, user, freeTrialProductId); ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Your 7-Day Free Trial Starts Now!"; if (Request.Cookies.AllKeys.Contains("vntycok") || GlobalConfig.Country14DayTrials.Contains(user.CountryCode)) { ReturnCode.StatusHeader = "Your 14-Day Free Trial Starts Now!"; HttpCookie vanCookie = new HttpCookie("vntycok"); vanCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(vanCookie); } ReturnCode.StatusMessage = "Congratulations! You are now registered to TFC.tv."; ReturnCode.StatusMessage2 = "Pwede ka nang manood ng mga piling Kapamilya shows at movies!"; TempData["ErrorMessage"] = ReturnCode; if (!String.IsNullOrEmpty(source)) return Redirect("/WatchNow"); //return RedirectToAction("Index", "Air"); //redirect to air if source is coming from project air //Eligible for Xoom Promo if (IsEligibleForXoomPromo) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Congratulations! You are now registered to TFC.tv."; ReturnCode.StatusMessage = "You are one step away from claiming your free 1 Month Premium Subscription."; ReturnCode.StatusMessage2 = String.Empty; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Details", "Subscribe", new { id = "xoom" }); } //check preblack cookie if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("redirectlckbprea")) { HttpCookie preBlackCookie = new HttpCookie("redirectlckbprea"); preBlackCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(preBlackCookie); return RedirectToAction("Details", "Subscribe", new { id = "lckbprea" }); } if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("redirect3178")) { HttpCookie pacMayCookie = new HttpCookie("redirect3178"); pacMayCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(pacMayCookie); //return Redirect("/Subscribe/mayweather-vs-pacquiao-may-3"); return RedirectToAction("Details", "Subscribe", new { id = "mayweather-vs-pacquiao-may-3" }); } if (MyUtility.isTVECookieValid()) { MyUtility.RemoveTVECookie(); return RedirectToAction("RegisterToTFCEverywhere", "User"); } return RedirectToAction("Index", "Home"); // successful verification } } else ReturnCode.StatusMessage = "The system encountered an unspecified error. Please contact Customer Support."; } else ReturnCode.StatusMessage = "This email address has already been verified."; } else ReturnCode.StatusMessage = "This email address does not exist."; } } catch (Exception e) { MyUtility.LogException(e); } return View("UXGenericError", ReturnCode); if (!Request.Cookies.AllKeys.Contains("version")) { } else { string result = String.Empty; if (String.IsNullOrEmpty(key)) result = "Missing required fields"; else { var registDt = DateTime.Now; var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => u.ActivationKey == new Guid(key)); if (user != null) { if (user.StatusId == 0 || user.StatusId == null) { user.StatusId = 1; user.DateVerified = DateTime.Now; var userId = user.UserId; //var transaction = new RegistrationTransaction() //{ // RegisteredState = user.State, // RegisteredCity = user.City, // RegisteredCountryCode = user.CountryCode, // Amount = 0, // Currency = user.Country.CurrencyCode //}; //user.Transactions.Add(transaction); //If FreeTrial is enabled, insert free trial. if (context.SaveChanges() > 0) { //if (GlobalConfig.IsFreeTrialEnabled) // PaymentHelper.PayViaWallet(context, userId, GlobalConfig.FreeTrial7ProductId, SubscriptionProductType.Package, userId, null); /****** DEC 31 2012 *****/ //UPDATE: FEB 18, 2013 if (user.IsTVERegistrant == null || user.IsTVERegistrant == false) { int freeTrialProductId = 0; if (GlobalConfig.IsFreeTrialEnabled) { freeTrialProductId = MyUtility.GetCorrespondingFreeTrialProductId(); if (GlobalConfig.TfcTvFree2StartDate < registDt && GlobalConfig.TfcTvFree2EndDate > registDt) { string UserCountryCode = user.CountryCode; if (!GlobalConfig.isUAT) try { UserCountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy(); } catch (Exception) { } var countryList = GlobalConfig.TfcTvFree2CountryWhiteList.Split(','); if (countryList.Contains(UserCountryCode) && String.Compare(user.CountryCode, UserCountryCode, true) == 0) freeTrialProductId = GlobalConfig.TfcTvFree2ProductId; } PaymentHelper.PayViaWallet(context, userId, freeTrialProductId, SubscriptionProductType.Package, userId, null); } if (GlobalConfig.IsABSCBNFreeLiveStreamFreeOnRegistrationEnabled) if (GlobalConfig.ABSCBNFreeLiveStreamStartDate < registDt && GlobalConfig.ABSCBNFreeLiveStreamEndDate > registDt) PaymentHelper.PayViaWallet(context, userId, GlobalConfig.ABSCBNFreeLiveStreamProductId, SubscriptionProductType.Package, userId, null); } result = "Successful"; SetAutheticationCookie(user.UserId.ToString()); TempData["isConnectedToSocialNetworks"] = false; if (!Request.IsLocal) if (user.IsTVERegistrant == null || user.IsTVERegistrant == false) //If user is TVE, do not send email MyUtility.SendConfirmationEmail(context, user); return RedirectToAction("RegisterConfirm", "User"); } else result = "Not successful"; } else result = "This email is already activated."; } else result = "User does not exist"; } ViewBag.ErrorMessage = result; return Content(result, "text/plain"); } }
public ActionResult _UpdatePassword(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; string url = Url.Action("ChangePassword", "User").ToString(); try { if (!User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home"); DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { string CurrentPassword = tmpCollection["currentPass"]; string NewPassword = tmpCollection["newPass"]; string CNewPassword = tmpCollection["cnewPass"]; if (String.Compare(NewPassword, CNewPassword, false) != 0) ReturnCode.StatusMessage = "The passwords you entered do not match."; else if (String.Compare(CurrentPassword, NewPassword) == 0) ReturnCode.StatusMessage = "Your current & new passwords are the same. Please choose another password."; else { using (var context = new IPTV2Entities()) { var userId = new Guid(User.Identity.Name); var user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { string hashedPassword = MyUtility.GetSHA1(CurrentPassword); if (String.Compare(user.Password, hashedPassword, false) != 0) ReturnCode.StatusMessage = "The current password you entered is incorrect."; else { string hashedNewPassword = MyUtility.GetSHA1(NewPassword); user.Password = hashedNewPassword; user.LastUpdated = registDt; if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusHeader = "Change Password Complete!"; ReturnCode.StatusMessage = "You've successfully updated your password."; ReturnCode.StatusMessage2 = String.Empty; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Profile"); //Successful change of password, redirect user to his profile. } else ReturnCode.StatusMessage = "We were unable to change your password. Please try again."; } } else return RedirectToAction("ChangePassword", "User"); } } TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("ChangePassword", "User"); } else ReturnCode.StatusMessage = "Please fill in all required fields."; if (!String.IsNullOrEmpty(ReturnCode.StatusMessage)) TempData["ErrorMessage"] = ReturnCode.StatusMessage; url = Request.UrlReferrer.AbsolutePath; } catch (Exception e) { MyUtility.LogException(e); } return Redirect(url); }
private void FlagBetaKey(string iid) { if (!String.IsNullOrEmpty(iid)) { var context = new IPTV2Entities(); var tester = context.BetaTesters.FirstOrDefault(b => b.InvitationKey == new System.Guid(iid) && b.DateClaimed == null); if (tester != null) { tester.DateClaimed = DateTime.Now; tester.IpAddress = Request.GetUserHostAddressFromCloudflare(); context.SaveChanges(); } } }
public ActionResult _RegisterTFCEverywhere(FormCollection fc) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; string url = Url.Action("RegisterTFCEverywhere", "User").ToString(); var field_names = new string[] { "smartCardNum", "cusAccount" }; try { if (TempData["qs"] != null) { var qs = (NameValueCollection)TempData["qs"]; ViewBag.qs = qs; TempData["qs"] = qs; } DateTime registDt = DateTime.Now; Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]); bool isMissingRequiredFields = false; foreach (var x in tmpCollection) { if (!field_names.Contains(x.Key)) if (String.IsNullOrEmpty(x.Value)) { isMissingRequiredFields = true; break; } } if (!isMissingRequiredFields) // process form { if (HasConsumedNumberOfRetriesForTFCEverywhere()) { ReturnCode.StatusMessage = "Invalid data entered. Please call our Customer Service at 18778846832 or chat with our live support team for assistance."; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("RegisterTFCEverywhere", "User"); } if (String.IsNullOrEmpty(fc["smartCardNum"]) && String.IsNullOrEmpty(fc["cusAccount"])) { ReturnCode.StatusMessage = "Please fill up all the required fields."; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("RegisterTFCEverywhere", "User"); } var context = new IPTV2Entities(); User user = null; if (User.Identity.IsAuthenticated) { string CurrencyCode = GlobalConfig.DefaultCurrency; var UserId = new Guid(User.Identity.Name); user = context.Users.FirstOrDefault(u => u.UserId == UserId); if (user != null) { CurrencyCode = user.Country.CurrencyCode; var transaction = new TfcEverywhereTransaction() { Amount = 0, Date = registDt, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, StatusId = GlobalConfig.Visible, Reference = "TFC Everywhere - CLAIM", UserId = user.UserId }; var gomsService = new GomsTfcTv(); var MacAddressOrSmartCard = fc["smartCardNum"].Replace(" ", ""); var AccountNumber = fc["cusAccount"].Replace(" ", ""); var ActivationNumber = fc["actCode"].Replace(" ", ""); var response = gomsService.ClaimTVEverywhere(context, user.UserId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationNumber); if (response.IsSuccess) { AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user); transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate); transaction.GomsTFCEverywhereStartDate = registDt; user.Transactions.Add(transaction); user.IsTVEverywhere = true; if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.info = "TFC Everywhere Activation"; ReturnCode.CCStatusMessage = "Congratulations! Your TFC Everywhere is now activated."; ReturnCode.StatusMessage = "Pwede ka nang manood ng piling Kapamilya shows at<br>movies mula sa paborito niyong TFC Channels."; TempData["ErrorMessage"] = ReturnCode; return RedirectToAction("Index", "Home"); // successful tve activation } } else { SetNumberOfTriesForTFCEverywhereCookie(); if (String.Compare(response.StatusCode, "8", true) == 0) ReturnCode.StatusMessage = "Go to your Edit My Profile page to update the last name registered on your TFC.tv account."; else ReturnCode.StatusMessage = response.StatusMessage; } } else ReturnCode.StatusMessage = "User does not exist."; } else ReturnCode.StatusMessage = "You are not logged in."; } else ReturnCode.StatusMessage = "Please fill in all required fields."; TempData["ErrorMessage"] = ReturnCode; url = Request.UrlReferrer.AbsolutePath; } catch (Exception e) { MyUtility.LogException(e); } return Redirect(url); }
public ActionResult _CreateSmartPit(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); if (!MyUtility.isUserLoggedIn()) { collection = MyUtility.setError(ErrorCodes.NotAuthenticated); return Content(MyUtility.buildJson(collection), "application/json"); } var context = new IPTV2Entities(); var userId = new Guid(User.Identity.Name); User user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user == null) { collection = MyUtility.setError(ErrorCodes.UnknownError, "User does not exist"); return Content(MyUtility.buildJson(collection), "application/json"); } if (user.Country == null) { collection = MyUtility.setError(ErrorCodes.UnknownError, "User's country is missing."); return Content(MyUtility.buildJson(collection), "application/json"); } if (user.Country.Code != GlobalConfig.JapanCountryCode) { collection = MyUtility.setError(ErrorCodes.UnknownError, "User is not authorized."); return Content(MyUtility.buildJson(collection), "application/json"); } if (!String.IsNullOrEmpty(user.SmartPitId)) { collection = MyUtility.setError(ErrorCodes.UnknownError, "User is already enrolled."); return Content(MyUtility.buildJson(collection), "application/json"); } DateTime registDt = DateTime.Now; var smartpitcardno = String.IsNullOrEmpty(fc["SmartPitCardNumber"]) ? String.Empty : fc["SmartPitCardNumber"]; var service = new GomsTfcTv(); try { var response = service.EnrollSmartPit(context, userId, smartpitcardno); if (response.IsSuccess) { user.SmartPitId = response.SmartPitCardNo; user.SmartPitRegistrationDate = registDt; if (context.SaveChanges() > 0) { collection = MyUtility.setError(ErrorCodes.Success, response.StatusMessage); collection.Add("spcno", response.SmartPitCardNo); } else collection = MyUtility.setError(ErrorCodes.EntityUpdateError, "Unable to process your request. Please try again later."); } else collection = MyUtility.setError(ErrorCodes.EntityUpdateError, response.StatusMessage); } catch (Exception e) { Trace.TraceError(e.Message); collection = MyUtility.setError(ErrorCodes.UnknownError, String.Format("{0} {1}", e.Message, e.InnerException == null ? String.Empty : e.InnerException.Message)); } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult _Link(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); if (MyUtility.isUserLoggedIn()) //User is logged in. return RedirectToAction("Index", "Home"); try { string EmailAddress = fc["EmailAddress"]; string Password = fc["Password"]; var context = new IPTV2Entities(); var user = context.Users.FirstOrDefault(u => u.EMail == EmailAddress); if (user == null) collection = MyUtility.setError(ErrorCodes.UserDoesNotExist); else { Password = MyUtility.GetSHA1(Password); if (String.Compare(user.EMail, EmailAddress, true) == 0 && String.Compare(user.Password, Password, false) == 0) { /** notifyRegistration **/ Dictionary<string, object> regCollection = new Dictionary<string, object>(); regCollection.Add("siteUID", user.UserId.ToString()); NameValueCollection qs; if (TempData["qs"] != null) { qs = (NameValueCollection)TempData["qs"]; regCollection.Add("uid", Uri.UnescapeDataString(qs["UID"])); regCollection.Add("cid", String.Format("{0} - New User", qs["provider"])); } GSResponse notifyRegistration = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(regCollection)); /** end of notifyRegistration **/ if (notifyRegistration.GetErrorCode() == 0) //Successful link { //notifyLogin if (GlobalConfig.EnableNotifyLoginOnLinkAccount) { Dictionary<string, object> userInfo = new Dictionary<string, object>(); userInfo.Add("firstName", user.FirstName); userInfo.Add("lastName", user.LastName); userInfo.Add("email", user.EMail); Dictionary<string, object> gigyaCollection = new Dictionary<string, object>(); gigyaCollection.Add("siteUID", user.UserId); gigyaCollection.Add("cid", "TFCTV - Login"); gigyaCollection.Add("sessionExpiration", "0"); gigyaCollection.Add("userInfo", MyUtility.buildJson(userInfo)); GSResponse res = GigyaHelpers.createAndSendRequest("socialize.notifyLogin", GigyaHelpers.buildParameter(gigyaCollection)); GigyaHelpers.setCookie(res, this.ControllerContext); } //Activate the account user.DateVerified = DateTime.Now; user.StatusId = 1; //UPDATE: FEB 18, 2013 - Cookie is valid. Tag as TVE Registrant. if (GlobalConfig.IsTVERegistrationEnabled) { if (MyUtility.isTVECookieValid()) { user.IsTVERegistrant = true; MyUtility.RemoveTVECookie(); var href = GlobalConfig.TVERegistrationPage; collection.Add("href", href); } } context.SaveChanges(); errorMessage = "Linking successful!"; SetAutheticationCookie(user.UserId.ToString()); //FormsAuthentication.SetAuthCookie(user.UserId.ToString(), false); collection = MyUtility.setError(ErrorCodes.Success, errorMessage); } else { errorMessage = "Unable to link your account. Please try again."; collection = MyUtility.setError(ErrorCodes.FailedToLinkAccount, errorMessage); } } else collection = MyUtility.setError(ErrorCodes.IsWrongPassword); } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); //Debug.WriteLine(e.InnerException); throw; } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult _ResetPassword(FormCollection fc) { if (MyUtility.isUserLoggedIn()) return RedirectToAction("Index", "Home"); string key = fc["key"]; string oid = fc["oid"]; string password = fc["NewPassword"]; string confirm_password = fc["ConfirmPassword"]; Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; if (String.IsNullOrEmpty(key) || String.IsNullOrEmpty(oid)) { errorMessage = "The page you requested is not valid."; collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } try { Guid tempkey; tempkey = Guid.Parse(key); } catch (Exception) { errorMessage = "The page you requested is not valid."; collection = MyUtility.setError(ErrorCodes.UnknownError, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } try { var context = new IPTV2Entities(); var activationKey = new Guid(key); User user = context.Users.FirstOrDefault(u => u.ActivationKey == activationKey); if (user != null) { if (registDt.Subtract(user.LastUpdated).TotalSeconds > 86400) { errorMessage = "The page you requested has already expired."; collection = MyUtility.setError(ErrorCodes.UnknownError, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } string oid_base = MyUtility.GetSHA1(String.Format("{0}{1}", user.UserId, user.LastUpdated)); if (String.Compare(oid, oid_base, true) != 0) { errorMessage = "The page you requested is not valid."; collection = MyUtility.setError(ErrorCodes.UnknownError, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } if (String.Compare(password, confirm_password, false) != 0) { errorMessage = "Password mismatch!"; collection = MyUtility.setError(ErrorCodes.IsMismatchPassword, errorMessage); return this.Json(collection, JsonRequestBehavior.AllowGet); } //Guid randomGuid = System.Guid.NewGuid(); //string newPassword = randomGuid.ToString().Substring(0, 8); string hashedPassword = MyUtility.GetSHA1(password); user.Password = hashedPassword; user.LastUpdated = registDt; if (context.SaveChanges() > 0) { errorMessage = "Your password has been changed succcessfully."; collection = MyUtility.setError(ErrorCodes.Success, errorMessage); } else { errorMessage = "The system encountered an unidentified error. Please try again."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); } } else { errorMessage = "The page you requested is not valid."; collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, errorMessage); } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, e.Message); } return this.Json(collection, JsonRequestBehavior.AllowGet); }
public JsonResult CancelRecurring(int? pid) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; DateTime registDt = DateTime.Now; try { if (pid == null) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Request is not valid"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (!Request.IsAjaxRequest()) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Request is not valid"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (User.Identity.IsAuthenticated) { var context = new IPTV2Entities(); var userId = new Guid(User.Identity.Name); var user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { var product = context.Products.FirstOrDefault(p => p.ProductId == (int)pid); if (product != null) { if (product is SubscriptionProduct) { var subscription_product = (SubscriptionProduct)product; var packageIds = subscription_product.ProductGroup.GetPackageIds(true); var CurrencyCode = GlobalConfig.DefaultCurrency; try { CurrencyCode = user.Country.CurrencyCode; } catch (Exception) { } var rb = context.RecurringBillings.Where(r => r.UserId == user.UserId && r.StatusId == GlobalConfig.Visible && packageIds.Contains(r.PackageId)); if (rb != null) { if (rb.Count() > 0) { var gomsService = new GomsTfcTv(); foreach (var billing in rb) { string reference = String.Empty; bool serviceUpdateSuccess = false; string cancellation_remarks = String.Empty; if (billing is PaypalRecurringBilling) { try { var paypalrbilling = (PaypalRecurringBilling)billing; billing.StatusId = 0; billing.UpdatedOn = registDt; try { if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId)) { reference = String.Format("PayPal Payment Renewal id {0} cancelled", billing.RecurringBillingId); String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } } catch (Exception) { } } catch (Exception) { } } else { try { var result = gomsService.CancelRecurringPayment(user, billing.Product); if (result.IsSuccess) { billing.StatusId = 0; billing.UpdatedOn = registDt; reference = String.Format("Credit Card Payment Renewal {0} cancelled", billing.RecurringBillingId); cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } else { ReturnCode.StatusMessage = result.StatusMessage; throw new Exception(result.StatusMessage); } } catch (Exception) { } } //serviceUpdateSuccess = true; if (serviceUpdateSuccess) { var transaction = new CancellationTransaction() { Amount = 0, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, CancellationRemarks = cancellation_remarks, OriginalTransactionId = -1, GomsTransactionId = -1000, Date = registDt, Reference = reference, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } } if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "We have disabled all your automatic payment renewal."; } } } } } } } else { ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated; ReturnCode.StatusMessage = "User is not authenticated"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
public ActionResult _ClaimTVE(FormCollection fc, string EmailAddress, string MacAddressOrSmartCard, string AccountNumber, string ActivationCode) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); try { DateTime registDt = DateTime.Now; var context = new IPTV2Entities(); var userId = new Guid("E21D87F3-5940-451A-B7EE-ADA4F3CEC234"); if (!String.IsNullOrEmpty(EmailAddress)) { var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0); if (user != null) { userId = user.UserId; string CurrencyCode = GlobalConfig.DefaultCurrency; Country country = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode); if (country != null) { Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode); if (currency != null) CurrencyCode = currency.Code; } var transaction = new TfcEverywhereTransaction() { Amount = 0, Date = DateTime.Now, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, StatusId = GlobalConfig.Visible, Reference = "TFC Everywhere - Activate" }; //string MacAddressOrSmartCard = "00172F0108FC"; //string AccountNumber = "US-000179857"; //string ActivationCode = "5S3UDP"; var gomsService = new GomsTfcTv(); var response = gomsService.ClaimTVEverywhere(context, userId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationCode); if (response.IsSuccess) { //ADD Entitlement AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user); transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate); transaction.GomsTFCEverywhereStartDate = registDt; user.Transactions.Add(transaction); user.IsTVEverywhere = true; if (context.SaveChanges() > 0) collection = MyUtility.setError(ErrorCodes.Success, "Claimed TVE"); } else collection = MyUtility.setError(ErrorCodes.UnknownError, response.StatusMessage); } } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, e.Message); } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult _EditProfile(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; if (Request.IsAjaxRequest()) { if (MyUtility.isUserLoggedIn()) { try { string CountryCode = fc["CountryCode"]; string State = String.IsNullOrEmpty(fc["State"]) ? fc["StateDD"] : fc["State"]; if (String.IsNullOrEmpty(fc["FirstName"]) || String.IsNullOrEmpty(fc["LastName"]) || String.IsNullOrEmpty(fc["CountryCode"])) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields); return Content(MyUtility.buildJson(collection), "application/json"); } string FirstName = fc["FirstName"]; string LastName = fc["LastName"]; string City = fc["City"]; if (FirstName.Length > 32) { collection = MyUtility.setError(ErrorCodes.LimitReached, "First Name cannot exceed 32 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (LastName.Length > 32) { collection = MyUtility.setError(ErrorCodes.LimitReached, "Last Name cannot exceed 32 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (!String.IsNullOrEmpty(State)) if (State.Length > 30) { collection = MyUtility.setError(ErrorCodes.LimitReached, "State cannot exceed 30 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } if (!String.IsNullOrEmpty(City)) if (City.Length > 50) { collection = MyUtility.setError(ErrorCodes.LimitReached, "City cannot exceed 50 characters."); return Content(MyUtility.buildJson(collection), "application/json"); } var context = new IPTV2Entities(); /***** CHECK FOR COUNTRY CODE ****/ if (context.Countries.Count(c => String.Compare(c.Code, CountryCode, true) == 0) <= 0) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } else if (GlobalConfig.ExcludedCountriesFromRegistrationDropDown.Split(',').Contains(CountryCode)) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Country Code is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } if (String.IsNullOrEmpty(State)) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is required."); return Content(MyUtility.buildJson(collection), "application/json"); } else { if (context.States.Count(c => c.CountryCode == CountryCode.ToUpper()) > 0) { if (context.States.Count(s => s.CountryCode == CountryCode.ToUpper() && (s.StateCode == State || s.Name == State)) == 0) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is invalid."); return Content(MyUtility.buildJson(collection), "application/json"); } } } //if (String.IsNullOrEmpty(State)) //{ // collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is required."); // return Content(MyUtility.buildJson(collection), "application/json"); //} //else //{ // if (context.Countries.Count(c => c.Code == CountryCode.ToUpper()) > 0) // { // if (context.States.Count(s => s.CountryCode == CountryCode.ToUpper() && (s.StateCode == State || s.Name == State)) == 0) // { // collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "State is invalid."); // return Content(MyUtility.buildJson(collection), "application/json"); // } // } //} User user = context.Users.FirstOrDefault(u => u.UserId == new System.Guid(User.Identity.Name)); if (user != null) { string CurrencyCode = GlobalConfig.DefaultCurrency; string OldCountryCode = GlobalConfig.DefaultCountry; Country country = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode); if (country != null) { CurrencyCode = country.Currency.Code; country = null; OldCountryCode = user.Country.Code; } UserWallet currentWallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode); if (currentWallet == null) //If no wallet, get default USD wallet. currentWallet = user.UserWallets.FirstOrDefault(w => w.Currency == GlobalConfig.DefaultCurrency); string newCountryCode = fc["CountryCode"]; user.FirstName = fc["FirstName"]; user.LastName = fc["LastName"]; user.City = fc["City"]; user.State = String.IsNullOrEmpty(fc["State"]) || fc["State"] == "" ? (String.IsNullOrEmpty(fc["StateDD"]) ? user.State : fc["StateDD"]) : fc["State"]; country = context.Countries.FirstOrDefault(c => c.Code == newCountryCode); if (country != null) { Currency currency = country.Currency; CurrencyCode = (currency == null) ? GlobalConfig.DefaultCurrency : currency.Code; } UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == CurrencyCode); decimal balance = 0; decimal oldWalletBalance = currentWallet.Balance; string oldCurrency = currentWallet.Currency; var oldGomsWalletId = currentWallet.GomsWalletId; if (wallet == null) // Wallet does not exist. Create new wallet for User. { if (currentWallet != null) { balance = currentWallet.Currency != CurrencyCode ? Forex.Convert(context, currentWallet.Currency, CurrencyCode, currentWallet.Balance) : currentWallet.Balance; //balance = currentWallet.Balance; currentWallet.Balance = 0; currentWallet.IsActive = false; //currentWallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.LastUpdated = registDt; } wallet = ContextHelper.CreateWallet(balance, CurrencyCode, registDt); user.UserWallets.Add(wallet); } else // Wallet already exists. Update the balance only. { if (currentWallet.Currency != wallet.Currency) { balance = currentWallet.Currency != wallet.Currency ? Forex.Convert(context, currentWallet.Currency, wallet.Currency, currentWallet.Balance) : currentWallet.Balance; wallet.Balance = balance; //wallet.Balance += (currentWallet.Balance * 1); wallet.IsActive = true; wallet.LastUpdated = registDt; wallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.Balance = 0; // Deactivate old wallet currentWallet.IsActive = false; //Deactivate //currentWallet.GomsWalletId = null; // Reset Goms WalletId currentWallet.LastUpdated = registDt; } } user.CountryCode = newCountryCode; // Update user country user.LastUpdated = registDt; // lastUpdate // update the user's recurring billing if (!String.IsNullOrEmpty(fc["rb_list"])) UpdateRecurringBillingViaEditProfile(context, user, fc["rb_list"]); if (OldCountryCode != newCountryCode) { var offering = context.Offerings.Find(GlobalConfig.offeringId); //Get User Transactions if (user.HasOtherPendingGomsTransaction(offering)) { errorMessage = "We are still processing your transactions. Please try again after a few minutes."; collection = MyUtility.setError(ErrorCodes.HasPendingChangeCountryTransaction, errorMessage); return Content(MyUtility.buildJson(collection), "application/json"); } if (user.HasPendingGomsChangeCountryTransaction(offering)) { errorMessage = "We are processing your recent change in location. Please try again after a few minutes."; collection = MyUtility.setError(ErrorCodes.HasPendingChangeCountryTransaction, errorMessage); return Content(MyUtility.buildJson(collection), "application/json"); } if (user.HasTVEverywhereEntitlement(MyUtility.StringToIntList(GlobalConfig.TVEverywherePackageIds), offering)) { errorMessage = "You are not allowed to change country being a TV Everywhere user."; collection = MyUtility.setError(ErrorCodes.HasPendingChangeCountryTransaction, errorMessage); return Content(MyUtility.buildJson(collection), "application/json"); } ChangeCountryTransaction transaction = new ChangeCountryTransaction() { OldCountryCode = OldCountryCode, NewCountryCode = newCountryCode, Date = registDt, OfferingId = GlobalConfig.offeringId, Reference = "Change Country", UserId = user.UserId, Amount = 0, NewWalletBalance = balance, OldWalletBalance = oldWalletBalance, OldGomsCustomerId = user.GomsCustomerId, OldGomsWalletId = oldGomsWalletId, Currency = oldCurrency, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } if (context.SaveChanges() > 0) { //string ProfilePageShare = fc["ProfilePageShare"]; //string EveryoneActivityFeedShare = fc["EveryoneActivityFeedShare"]; //string SocialNetworkShare = fc["SocialNetworkShare"]; string IsInternalSharingEnabled = fc["IsInternalSharingEnabled"]; string IsExternalSharingEnabled = fc["IsExternalSharingEnabled"]; string IsProfilePrivate = fc["IsProfilePrivate"]; UserData userData = new UserData() { IsInternalSharingEnabled = IsInternalSharingEnabled, IsExternalSharingEnabled = IsExternalSharingEnabled, IsProfilePrivate = IsProfilePrivate //ProfilePageShare = ProfilePageShare, //EveryoneActivityFeedShare = EveryoneActivityFeedShare, //SocialNetworkShare = SocialNetworkShare }; var res = GigyaMethods.SetUserData(user.UserId, userData); //setUserData setUserData(user.UserId.ToString(), user); errorMessage = "Your information has been updated successfully."; collection = MyUtility.setError(ErrorCodes.Success, errorMessage); } else { errorMessage = "Error in updating your profile."; collection = MyUtility.setError(ErrorCodes.EntityUpdateError, errorMessage); } } } catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); } } } return Content(MyUtility.buildJson(collection), "application/json"); }
public ActionResult _ClaimTVEverywhere(FormCollection fc) { Dictionary<string, object> collection = new Dictionary<string, object>(); ErrorCodes errorCode = ErrorCodes.UnknownError; string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError); collection = MyUtility.setError(errorCode, errorMessage); DateTime registDt = DateTime.Now; try { if (HasConsumedNumberOfRetriesForTFCEverywhere()) { collection = MyUtility.setError(ErrorCodes.LimitReached, "Invalid data entered. Please call our Customer Service at 18778846832 or chat with our live support team for assistance."); return Content(MyUtility.buildJson(collection), "application/json"); } if (((String.IsNullOrEmpty(fc["MacAddressOrSmartCard"]) && String.IsNullOrEmpty(fc["AccountNumber"]))) || String.IsNullOrEmpty(fc["ActivationNumber"])) { collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Please fill up the required fields."); return Content(MyUtility.buildJson(collection), "application/json"); } var context = new IPTV2Entities(); User user = null; if (MyUtility.isUserLoggedIn()) { var userId = new Guid(User.Identity.Name); user = context.Users.FirstOrDefault(u => u.UserId == userId); } else { var userId = (Guid)TempData["tempUid"]; TempData["tempUserId"] = userId; // REASSIGN TempData["tempUid"] = userId; // REASSIGN user = context.Users.FirstOrDefault(u => u.UserId == userId); } if (user != null) { string CurrencyCode = GlobalConfig.DefaultCurrency; Country country = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode); if (country != null) { Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode); if (currency != null) CurrencyCode = currency.Code; } var transaction = new TfcEverywhereTransaction() { Amount = 0, Date = DateTime.Now, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, StatusId = GlobalConfig.Visible, Reference = "TFC Everywhere - CLAIM", UserId = user.UserId }; var gomsService = new GomsTfcTv(); var MacAddressOrSmartCard = fc["MacAddressOrSmartCard"].Replace(" ", ""); var AccountNumber = fc["AccountNumber"].Replace(" ", ""); var ActivationNumber = fc["ActivationNumber"].Replace(" ", ""); var response = gomsService.ClaimTVEverywhere(context, user.UserId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationNumber); if (response.IsSuccess) { AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user); transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate); transaction.GomsTFCEverywhereStartDate = registDt; user.Transactions.Add(transaction); user.IsTVEverywhere = true; if (context.SaveChanges() > 0) { collection = MyUtility.setError(ErrorCodes.Success, String.Empty); collection.Add("href", GlobalConfig.RegistrationCompleteTVE); } } else { SetNumberOfTriesForTFCEverywhereCookie(); if (String.Compare(response.StatusCode, "8", true) == 0) { var sb = new StringBuilder(); sb.Append(response.StatusMessage); sb.Append(" Go to your <a href=\"/EditProfile\" target=\"_blank\">Edit My Profile</a> page to update the last name registered on your TFC.tv account."); collection = MyUtility.setError(ErrorCodes.UnknownError, sb.ToString()); } else collection = MyUtility.setError(ErrorCodes.UnknownError, response.StatusMessage); } } else collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, "User does not exist."); } catch (Exception e) { MyUtility.LogException(e); collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); } return Content(MyUtility.buildJson(collection), "application/json"); }