Exemplo n.º 1
0
        public ActionResult Index()
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.NotAuthenticated,
                StatusMessage = String.Empty,
                info = "IT&E Validation",
                TransactionType = "Validation"
            };

            if (User.Identity.IsAuthenticated)
            {
                DateTime registDt = DateTime.Now;
                IPTV2Entities context = new IPTV2Entities();
                var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.ITEPromoId && p.StartDate < registDt && registDt < p.EndDate && p.StatusId == GlobalConfig.Visible);
                if (promo != null)
                    return View();
                else { ReturnCode.StatusCode = (int)ErrorCodes.UnauthorizedCountry; }
            }
            ReturnCode.StatusMessage = MyUtility.getErrorMessage((ErrorCodes)ReturnCode.StatusCode);
            if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
            {
                TempData["ErrorMessage"] = ReturnCode;
            }
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 2
0
        public ActionResult ErrorEncountered(PaymentError error)
        {
            var context = new IPTV2Entities();
            var UserId = new Guid(User.Identity.Name);
            var userWallet = context.UserWallets.FirstOrDefault(u => u.UserId == UserId);

            string message = String.Empty;
            switch (error)
            {
                case PaymentError.CREDIT_CARD_PAYMENT_IS_DISABLED:
                    message = "Credit card payment is currenty disabled."; break;
                case PaymentError.EWALLET_PAYMENT_IS_DISABLED:
                    message = "E-Wallet payment is currently disabled."; break;
                case PaymentError.INSUFFICIENT_WALLET_LOAD:
                    if (GlobalConfig.IsMopayReloadModeEnabled && GlobalConfig.MopayCountryWhitelist.Contains(userWallet.User.CountryCode))
                    {
                        message = String.Format("You don't have enough credits to purchase this product. Your current balance is {0}. Reload <a href=\"/Load/Mopay\">here</a>.", userWallet.Balance.ToString("0.00"));
                    }
                    else message = String.Format("You don't have enough credits to purchase this product. Your current balance is {0}. Reload <a href=\"/Load/CreditCard\">here</a>.", userWallet.Balance.ToString("0.00")); break;
                case PaymentError.MAXIMUM_TRANSACTION_THRESHOLD_REACHED:
                    message = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day.", GlobalConfig.paymentTransactionMaximumThreshold); break;
                case PaymentError.PAYPAL_PAYMENT_IS_DISABLED:
                    message = "Paypal payment is currently disabled."; break;
                case PaymentError.PENDING_GOMS_CHANGE_COUNTRY:
                    message = "We are still processing your recent change in location. Please try again later."; break;
                case PaymentError.PREPAID_CARD_PAYMENT_IS_DISABLED:
                    message = "Prepaid card payment is currently disabled."; break;
                case PaymentError.USER_ENROLLED_IN_SAME_RECURRING_GROUP_PRODUCT:
                    message = "You are currently automatically renewing a similar subscription product through Paypal/Credit card."; break;
                case PaymentError.CREDIT_CARD_IS_NOT_AVAILABLE_IN_YOUR_AREA:
                    message = "Credit card payment is not available in your country."; break;
                default:
                    message = "The system encountered an unspecified error. Please contact Customer Support."; break;
            }
            var ReturnCode = new TransactionReturnType() { StatusMessage = message };
            return PartialView(ReturnCode);
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        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);

        }
Exemplo n.º 5
0
        //[RequireHttps]
        public ActionResult MobileLogin(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            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["login_email"];
                    string Password = fc["login_pass"];
                    if (!String.IsNullOrEmpty(Request.UrlReferrer.AbsolutePath))
                        url = Request.UrlReferrer.AbsolutePath;

                    RegexUtilities util = new RegexUtilities();
                    //if (!MyUtility.isEmail(EmailAddress))
                    if (!util.IsValidEmail(EmailAddress))
                    {
                        ReturnCode.StatusMessage = "Email address is invalid.";
                        TempData["LoginErrorMessage"] = ReturnCode.StatusMessage;
                        return Redirect(url);
                    }

                    using (var context = new IPTV2Entities())
                    {
                        User user = null;
                        if (User.Identity.IsAuthenticated)
                        {
                            var UserId = new Guid(User.Identity.Name);
                            user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                        }
                        else
                        {
                            user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                            if (user == null)
                                ReturnCode.StatusMessage = "Email address does not exist.";
                            else
                            {
                                if (user.StatusId != GlobalConfig.Visible)
                                    ReturnCode.StatusMessage = "Email address is not verified.";
                                else
                                {
                                    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);

                                        //add uid cookie
                                        HttpCookie uidCookie = new HttpCookie("uid");
                                        uidCookie.Value = user.UserId.ToString();
                                        uidCookie.Expires = DateTime.Now.AddDays(30);
                                        Response.Cookies.Add(uidCookie);

                                        if (user.IsTVEverywhere == true)
                                            return Redirect("/TFCChannel");
                                        else if (MyUtility.isTVECookieValid())
                                        {
                                            MyUtility.RemoveTVECookie();
                                            return RedirectToAction("RegisterToTFCEverywhere", "User");
                                        }

                                        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 RedirectToAction("Details", "Subscribe", new { id = "mayweather-vs-pacquiao-may-3" });
                                        }
                                        else if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("promo2014cok"))
                                        {
                                            HttpCookie tempCookie = new HttpCookie("promo2014cok");
                                            tempCookie.Expires = DateTime.Now.AddDays(-1);
                                            Response.Cookies.Add(tempCookie);
                                            return RedirectToAction("Details", "Subscribe", new { id = "Promo201410" });
                                        }
                                        else if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("redirectaintone"))
                                        {
                                            HttpCookie tempCookie = new HttpCookie("redirectaintone");
                                            tempCookie.Expires = DateTime.Now.AddDays(-1);
                                            Response.Cookies.Add(tempCookie);
                                            return RedirectToAction("Details", "Subscribe", new { id = "aintone" });
                                        }
                                        else if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("vntysicook"))
                                        {
                                            HttpCookie tempCookie = new HttpCookie("vntysicook");
                                            tempCookie.Expires = DateTime.Now.AddDays(-1);
                                            Response.Cookies.Add(tempCookie);
                                            return RedirectToAction("Index", "Events", new { id = tempCookie.Value });
                                        }
                                        return RedirectToAction("Index", "Home");
                                    }
                                    else
                                        ReturnCode.StatusMessage = "Email/Password do not match.";
                                }
                            }
                        }
                        if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
                            TempData["LoginErrorMessage"] = ReturnCode.StatusMessage;

                        if (user != null)
                        {
                            if (user.IsTVEverywhere == true)
                                return Redirect("/TFCChannel");
                            else
                                return Redirect(url);
                        }
                    }
                }
                else
                    ReturnCode.StatusMessage = "Please fill in all required fields.";

                if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
                    TempData["LoginErrorMessage"] = ReturnCode.StatusMessage;
                url = Request.UrlReferrer.AbsoluteUri;
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return Redirect(url);
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
 public JsonResult RemoveConnection(FormCollection fc)
 {
     var ReturnCode = new TransactionReturnType()
     {
         StatusCode = (int)ErrorCodes.UnknownError,
         StatusMessage = String.Empty
     };
     try
     {
         if (User.Identity.IsAuthenticated)
         {
             using (var context = new IPTV2Entities())
             {
                 var user = context.Users.FirstOrDefault(u => u.UserId == new Guid(User.Identity.Name));
                 if (user != null)
                 {
                     Dictionary<string, string> collection = new Dictionary<string, string>();
                     collection.Add("uid", user.UserId.ToString());
                     if (!String.IsNullOrEmpty(fc["provider"]))
                         collection.Add("provider", fc["provider"]);
                     collection.Add("format", "json");
                     GSObject obj = new GSObject(Newtonsoft.Json.JsonConvert.SerializeObject(collection));
                     GSResponse res = GigyaHelpers.createAndSendRequest("socialize.removeConnection", obj);
                     var resp = Newtonsoft.Json.JsonConvert.DeserializeObject<DeleteAccountObj>(res.GetData().ToJsonString());
                     ReturnCode.StatusCode = resp.errorCode;
                 }
             }
         }
     }
     catch (Exception e) { MyUtility.LogException(e); }
     return Json(ReturnCode, JsonRequestBehavior.AllowGet);
 }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        public ActionResult Details(int? id, string slug)
        {
            var profiler = MiniProfiler.Current;
            var registDt = DateTime.Now;
            try
            {
                if (id != null)
                {
                    if (id == GlobalConfig.PBB747Cam1EpisodeId || id == GlobalConfig.PBB747Cam2EpisodeId)
                        return Redirect(String.Format("/PinoyBigBrother/PBB737"));

                    var context = new IPTV2Entities();
                    var episode = context.Episodes.FirstOrDefault(e => e.EpisodeId == id);
                    if (episode != null)
                    {
                        if (episode.OnlineStatusId == GlobalConfig.Visible && episode.OnlineStartDate < registDt && episode.OnlineEndDate > registDt)
                        {
                            var dbSlug = MyUtility.GetSlug(episode.Description);
                            if (episode.IsLiveChannelActive == true)
                                return RedirectToActionPermanent("Details", "Live", new { id = id, slug = dbSlug });

                            SortedSet<int> parentCategories;
                            using (profiler.Step("Check for Parent Shows"))
                            {
                                var CacheDuration = new TimeSpan(0, GlobalConfig.GetParentShowsForEpisodeCacheDuration, 0);
                                parentCategories = episode.GetParentShows(CacheDuration);
                                if (parentCategories.Count() > 0)
                                {
                                    if (parentCategories.Contains(GlobalConfig.HalalanNewsAlertsParentCategoryId))
                                        return RedirectToActionPermanent("NewsAlerts", "Halalan2013", new { id = id, slug = dbSlug });
                                    else if (parentCategories.Contains(GlobalConfig.HalalanAdvisoriesParentCategoryId))
                                        return RedirectToActionPermanent("Advisories", "Halalan2013", new { id = id, slug = dbSlug });
                                    //else if (parentCategories.Contains(GlobalConfig.TFCkatCategoryId))
                                    //    return RedirectToActionPermanent("OnDemand", "TFCkat", new { id = id, slug = dbSlug });
                                    else if (parentCategories.Contains(GlobalConfig.UAAPGreatnessNeverEndsCategoryId))
                                        return RedirectToActionPermanent("OnDemand", "UAAP", new { id = id, slug = dbSlug });
                                    else if (parentCategories.Contains(GlobalConfig.KwentoNgPaskoCategoryId))
                                        return Redirect(String.Format("/KwentoNgPasko/{0}/{1}", id, dbSlug));
                                    else if (parentCategories.Contains(GlobalConfig.DigitalShortsCategoryId))
                                        return Redirect(String.Format("/HaloHalo/{0}", id));
                                }
                            }
                            string CountryCode = MyUtility.GetCountryCodeViaIpAddressWithoutProxy();
                            EpisodeCategory episodeCategory = null;
                            if (GlobalConfig.UseServiceOfferingWhenCheckingEpisodeParentCategory)
                            {
                                if (User.Identity.IsAuthenticated)
                                {
                                    var UserId = new Guid(User.Identity.Name);
                                    var user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                                    if (user != null)
                                    {
                                        if (MyUtility.IsDuplicateSession(user, Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]))
                                        {
                                            System.Web.Security.FormsAuthentication.SignOut();
                                            return RedirectToAction("ConcurrentLogin", "Home");
                                        }

                                        var allowedEmails = GlobalConfig.EmailsAllowedToBypassIPBlock.Split(',');
                                        var isEmailAllowed = allowedEmails.Contains(user.EMail.ToLower());
                                        if (isEmailAllowed)
                                            CountryCode = user.CountryCode;

                                        if (GlobalConfig.UseJWPlayer)
                                        {
                                            var videoPlaybackObj = MyUtility.MakePlaybackApiRequest(episode.EpisodeId);
                                            if (String.Compare(videoPlaybackObj.errorCode, "0", true) == 0)
                                                ViewBag.VideoPlaybackObj = videoPlaybackObj;
                                        }                                        
                                    }
                                }
                                var ShowListBasedOnCountryCode = ContextHelper.GetAllShowsBasedOnCountryCode(context, CountryCode, true);
                                episodeCategory = episode.EpisodeCategories.FirstOrDefault(e => ShowListBasedOnCountryCode.Contains(e.CategoryId));
                                //var ShowListBasedOnCountryCode = ContextHelper.GetAllShowsBasedOnCountryCode(context, CountryCode, true);
                                //episodeCategory = episode.EpisodeCategories.FirstOrDefault(e => ShowListBasedOnCountryCode.Contains(e.CategoryId));
                            }
                            else
                            {
                                var excludedCategoryIds = MyUtility.StringToIntList(GlobalConfig.ExcludedCategoryIdsForDisplay);
                                episodeCategory = episode.EpisodeCategories.FirstOrDefault(e => !excludedCategoryIds.Contains(e.CategoryId));
                            }
                            if (episodeCategory != null)
                            {
                                if (episodeCategory.Show.EndDate < registDt || episodeCategory.Show.StatusId != GlobalConfig.Visible)
                                    return RedirectToAction("Index", "Home");

                                ViewBag.Loved = false; ViewBag.Rated = false; // Social
                                ViewBag.HasActiveSubscriptionBasedOnCategoryId = new CheckSubscriptionReturnObject() { HasSubscription = false, Within5DaysOrLess = false };

                                var tempShowNameWithDate = String.Format("{0} {1}", episodeCategory.Show.Description, episode.DateAired.Value.ToString("MMMM d yyyy"));
                                dbSlug = MyUtility.GetSlug(tempShowNameWithDate);
                                if (String.Compare(dbSlug, slug, false) != 0)
                                    return RedirectToActionPermanent("Details", new { id = id, slug = dbSlug });
                                bool isEmailAllowed = false;
                                if (User.Identity.IsAuthenticated)
                                {
                                    var UserId = new Guid(User.Identity.Name);
                                    var user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                                    if (user != null)
                                    {
                                        CountryCode = user.CountryCode;
                                        ViewBag.EmailAddress = user.EMail;
                                        ViewBag.UserId = user.UserId;
                                        ViewBag.CountryCode = CountryCode;
                                        using (profiler.Step("Social Love"))
                                        {
                                            ViewBag.Loved = ContextHelper.HasSocialEngagement(UserId, GlobalConfig.SOCIAL_LOVE, id, EngagementContentType.Episode);
                                        }
                                        using (profiler.Step("Social Rating"))
                                        {
                                            ViewBag.Rated = ContextHelper.HasSocialEngagement(UserId, GlobalConfig.SOCIAL_RATING, id, EngagementContentType.Episode);
                                        }
                                        using (profiler.Step("Check for Active Entitlements")) //check for active entitlements based on categoryId
                                        {
                                            ViewBag.HasActiveSubscriptionBasedOnCategoryId = ContextHelper.HasActiveSubscriptionBasedOnCategoryId(user, parentCategories, registDt);
                                        }

                                        var allowedEmails = GlobalConfig.EmailsAllowedToBypassIPBlock.Split(',');
                                        isEmailAllowed = allowedEmails.Contains(user.EMail.ToLower());
                                    }
                                }
                                else
                                {
                                    using (profiler.Step("Check for Active Entitlements (Not Logged In)")) //check for active entitlements based on categoryId
                                    {
                                        ViewBag.HasActiveSubscriptionBasedOnCategoryId = ContextHelper.HasActiveSubscriptionBasedOnCategoryId(null, parentCategories, registDt, CountryCode);
                                    }
                                }

                                using (profiler.Step("Check for preview asset"))
                                {
                                    var cdnIds = MyUtility.StringToIntList("2,6");
                                    var previewAsset = episode.PreviewAssets.LastOrDefault();
                                    if (previewAsset != null)
                                    {
                                        Asset asset = previewAsset.Asset;
                                        if (asset != null)
                                            if (asset.AssetCdns != null)
                                                if (asset.AssetCdns.Count(a => cdnIds.Contains(a.CdnId)) > 0)
                                                    ViewBag.HasPreviewAsset = true;
                                    }
                                }

                                if (!ContextHelper.IsCategoryViewableInUserCountry(episodeCategory.Show, CountryCode))
                                    if (!isEmailAllowed)
                                        return RedirectToAction("Index", "Home");

                                ViewBag.Show = episodeCategory.Show;
                                ViewBag.CategoryType = "Show";
                                if (episodeCategory.Show is Movie)
                                    ViewBag.CategoryType = "Movie";
                                else if (episodeCategory.Show is SpecialShow)
                                    ViewBag.CategoryType = "SpecialShow";
                                else if (episodeCategory.Show is WeeklyShow)
                                    ViewBag.CategoryType = "WeeklyShow";
                                else if (episodeCategory.Show is DailyShow)
                                    ViewBag.CategoryType = "DailyShow";

                                ViewBag.EpisodeNumber = 0;
                                if (!(episodeCategory.Show is Movie || episodeCategory.Show is SpecialShow))
                                {
                                    using (profiler.Step("Get Episode Number"))
                                    {
                                        var listOfEpisodeIds = context.EpisodeCategories1.Where(e => e.CategoryId == episodeCategory.CategoryId).Select(e => e.EpisodeId);
                                        var episodeIdsOrderedByDate = context.Episodes.Where(e => listOfEpisodeIds.Contains(e.EpisodeId) && e.OnlineStatusId == GlobalConfig.Visible && e.OnlineStartDate < registDt && e.OnlineEndDate > registDt).OrderByDescending(e => e.DateAired).Select(e => e.EpisodeId);
                                        if (episodeIdsOrderedByDate != null)
                                        {
                                            var EpIds = episodeIdsOrderedByDate.ToList();
                                            //for dropdown list
                                            ViewBag.FullEpisodeList = EpIds;

                                            var EpisodeCount = EpIds.Count();
                                            var indexOfCurrentEpisode = EpIds.IndexOf(episode.EpisodeId);
                                            ViewBag.EpisodeNumber = EpisodeCount - indexOfCurrentEpisode;
                                            ViewBag.NextEpisodeId = EpIds.ElementAt(indexOfCurrentEpisode <= 0 ? indexOfCurrentEpisode : indexOfCurrentEpisode - 1); //Next episode id
                                            ViewBag.PreviousEpisodeId = EpIds.ElementAt(indexOfCurrentEpisode >= EpisodeCount - 1 ? indexOfCurrentEpisode : indexOfCurrentEpisode + 1); //Previous episode id
                                            ViewBag.LatestEpisodeId = EpIds.First();
                                            ViewBag.EpisodeCount = EpisodeCount; //Total episode count
                                        }
                                    }
                                }
                                ViewBag.dbSlug = dbSlug;
                                ViewBag.IsAjaxCrawlable = Request.IsAjaxCrawlingCapable(); // Check if page is Ajax Crawlable
                                MyUtility.SetOptimizelyCookie(context);

                                try
                                {
                                    var ShowParentCategories = ContextHelper.GetShowParentCategories(episodeCategory.Show.CategoryId);
                                    if (!String.IsNullOrEmpty(ShowParentCategories))
                                    {
                                        ViewBag.ShowParentCategories = ShowParentCategories;
                                        if (!MyUtility.IsWhiteListed(String.Empty))
                                        {
                                            var ids = MyUtility.StringToIntList(ShowParentCategories);
                                            var alaCarteIds = MyUtility.StringToIntList(GlobalConfig.UXAlaCarteParentCategoryIds);
                                            var DoCheckForGeoIPRestriction = ids.Intersect(alaCarteIds).Count() > 0;
                                            if (DoCheckForGeoIPRestriction)
                                            {
                                                var ipx = Request.IsLocal ? "221.121.187.253" : String.Empty;
                                                if (GlobalConfig.isUAT)
                                                    ipx = Request["ip"];
                                                if (!MyUtility.CheckIfCategoryIsAllowed(episodeCategory.Show.CategoryId, context, ipx))
                                                {
                                                    var ReturnCode = new TransactionReturnType()
                                                    {
                                                        StatusHeader = "Content Advisory",
                                                        StatusMessage = "This content is currently not available in your area.",
                                                        StatusMessage2 = "You may select from among the hundreds of shows and movies that are available on the site."
                                                    };
                                                    TempData["ErrorMessage"] = ReturnCode;
                                                    return RedirectToAction("Index", "Home");
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception) { }

                                try
                                {
                                    var pkg = context.PackageTypes.FirstOrDefault(p => p.PackageId == GlobalConfig.premiumId);
                                    var listOfShows = pkg.GetAllOnlineShowIds(CountryCode);
                                    bool IsPartOfPremium = listOfShows.Contains(episodeCategory.CategoryId);
                                    ViewBag.IsPartOfPremium = IsPartOfPremium;
                                }
                                catch (Exception) { }

                                if (!Request.Cookies.AllKeys.Contains("version"))
                                {
                                    if (GlobalConfig.UseJWPlayer)
                                    {
                                        if (Request.Cookies.AllKeys.Contains("hplayer"))
                                        {
                                            if (Request.Cookies["hplayer"].Value == "2")
                                                return View("DetailsFlowHLS", episode);
                                            else if (Request.Cookies["hplayer"].Value == "3")
                                                return View("DetailsTheOPlayer", episode);
                                            else if (Request.Cookies["hplayer"].Value == "4")
                                            {
                                                return View("Details4", episode);
                                                //return View("DetailsVideoJS", episode);
                                            }
                                            else if (Request.Cookies["hplayer"].Value == "5")
                                                return View("DetailsFlowHLS2", episode);
                                            else if (Request.Cookies["hplayer"].Value == "6")
                                                return View("DetailsJwplayerAkamai", episode);
                                            else if (Request.Cookies["hplayer"].Value == "7")
                                                return View("DetailsJwplayer7Akamai", episode);
                                            else
                                                return View("Details3", episode);
                                        }
                                        else
                                        {
                                            return View("DetailsJwplayerAkamai", episode);
                                            //return View("DetailsVideoJS", episode);
                                            //return View("Details4", episode);
                                        }

                                    }
                                    else
                                        return View("Details3", episode);
                                }
                                return View(episode);
                            }

                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 10
0
        public ActionResult Details(int? id, string slug)
        {
            var profiler = MiniProfiler.Current;
            var registDt = DateTime.Now;
            try
            {
                if (id != null)
                {
                    //if (id == GlobalConfig.TFCkatCategoryId)
                    //    return Redirect("/TFCkat");
                    //else 
                    if (id == GlobalConfig.UAAPGreatnessNeverEndsCategoryId)
                        return RedirectToAction("Index", "UAAP");
                    else if (id == GlobalConfig.UAAPLiveStreamEpisodeId)
                        return RedirectToAction("Live", "UAAP");
                    else if (id == GlobalConfig.FPJCategoryId)
                        return RedirectToAction("Index", "FPJ");
                    var excludedCategoryIds = MyUtility.StringToIntList(GlobalConfig.ExcludedCategoryIdsForDisplay);
                    if (excludedCategoryIds.Contains((int)id))
                        return RedirectToAction("Index", "Home");
                    var context = new IPTV2Entities();
                    var category = context.CategoryClasses.FirstOrDefault(c => c.CategoryId == id);
                    if (category != null)
                    {
                        if (category.StatusId == GlobalConfig.Visible)
                        {
                            ViewBag.Loved = false; ViewBag.Rated = false; // Social
                            ViewBag.HasActiveSubscriptionBasedOnCategoryId = new CheckSubscriptionReturnObject() { HasSubscription = false, Within5DaysOrLess = false };
                            if (category is Show)
                            {
                                var dbSlug = MyUtility.GetSlug(category.Description);
                                if (String.Compare(dbSlug, slug, false) != 0)
                                    return RedirectToActionPermanent("Details", new { id = id, slug = dbSlug });
                                var show = (Show)category;
                                if (show.StartDate < registDt && show.EndDate > registDt)
                                {
                                    string CountryCodeTemp = MyUtility.GetCountryCodeViaIpAddressWithoutProxy();
                                    string CountryCode = CountryCodeTemp;
                                    if (User.Identity.IsAuthenticated)
                                    {
                                        var UserId = new Guid(User.Identity.Name);
                                        var user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                                        if (user != null)
                                        {
                                            var allowedEmails = GlobalConfig.EmailsAllowedToBypassIPBlock.Split(',');
                                            var isEmailAllowed = allowedEmails.Contains(user.EMail.ToLower());
                                            CountryCode = user.CountryCode;
                                            ViewBag.EmailAddress = user.EMail;
                                            ViewBag.UserId = user.UserId;
                                            ViewBag.CountryCode = CountryCode;

                                            if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCode))
                                                return RedirectToAction("Index", "Home");

                                            if (!isEmailAllowed)
                                            {
                                                string CountryCodeBasedOnIpAddress = CountryCodeTemp;
                                                if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCodeBasedOnIpAddress))
                                                    return RedirectToAction("Index", "Home");
                                            }

                                            using (profiler.Step("Social Love"))
                                            {
                                                ViewBag.Loved = ContextHelper.HasSocialEngagement(UserId, GlobalConfig.SOCIAL_LOVE, id, EngagementContentType.Show);
                                            }
                                            using (profiler.Step("Social Rating"))
                                            {
                                                ViewBag.Rated = ContextHelper.HasSocialEngagement(UserId, GlobalConfig.SOCIAL_RATING, id, EngagementContentType.Show);
                                            }

                                            using (profiler.Step("Check for Active Entitlements")) //check for active entitlements based on categoryId
                                            {
                                                ViewBag.HasActiveSubscriptionBasedOnCategoryId = ContextHelper.HasActiveSubscriptionBasedOnCategoryId(user, show.CategoryId, registDt);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!ContextHelper.IsCategoryViewableInUserCountry(show, CountryCode))
                                            return RedirectToAction("Index", "Home");
                                    }

                                    try
                                    {
                                        var ShowParentCategories = ContextHelper.GetShowParentCategories(show.CategoryId);
                                        if (!String.IsNullOrEmpty(ShowParentCategories))
                                        {
                                            ViewBag.ShowParentCategories = ShowParentCategories;
                                            if (!MyUtility.IsWhiteListed(String.Empty))
                                            {
                                                var ids = MyUtility.StringToIntList(ShowParentCategories);
                                                var alaCarteIds = MyUtility.StringToIntList(GlobalConfig.UXAlaCarteParentCategoryIds);
                                                var DoCheckForGeoIPRestriction = ids.Intersect(alaCarteIds).Count() > 0;
                                                if (DoCheckForGeoIPRestriction)
                                                {
                                                    var ipx = Request.IsLocal ? "221.121.187.253" : String.Empty;
                                                    if (GlobalConfig.isUAT)
                                                        ipx = Request["ip"];
                                                    if (!MyUtility.CheckIfCategoryIsAllowed(show.CategoryId, context, ipx))
                                                    {
                                                        var ReturnCode = new TransactionReturnType()
                                                        {
                                                            StatusHeader = "Content Advisory",
                                                            StatusMessage = "This content is currently not available in your area.",
                                                            StatusMessage2 = "You may select from among the hundreds of shows and movies that are available on the site."
                                                        };
                                                        TempData["ErrorMessage"] = ReturnCode;
                                                        return RedirectToAction("Index", "Home");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception) { }

                                    //Get Episode Count
                                    using (profiler.Step("Episode Count"))
                                    {
                                        ViewBag.EpisodeCount = context.EpisodeCategories1.Count(e => e.Episode.OnlineStatusId == GlobalConfig.Visible && e.Show.CategoryId == show.CategoryId && e.Episode.OnlineStartDate < registDt && e.Episode.OnlineEndDate > registDt);
                                    }

                                    using (profiler.Step("Check Show Type"))
                                    {
                                        if (show is Movie)
                                        {
                                            ViewBag.CategoryType = "Movie";
                                            return RedirectToAction("Details", "Episode", new { id = GetMovieEpisodeId(show.CategoryId) });
                                        }
                                        else if (show is SpecialShow)
                                        {
                                            ViewBag.CategoryType = "Special";
                                            return RedirectToAction("Details", "Episode", new { id = GetMovieEpisodeId(show.CategoryId) });
                                        }
                                        else if (show is LiveEvent)
                                        {
                                            ViewBag.CategoryType = "LiveEvent";
                                            var episodeCategory = context.EpisodeCategories1.FirstOrDefault(e => e.CategoryId == show.CategoryId);
                                            if (episodeCategory != null)
                                                return RedirectToAction("Details", "Live", new { id = episodeCategory.EpisodeId, slug = MyUtility.GetSlug(episodeCategory.Episode.EpisodeName) });
                                        }
                                    }
                                    ViewBag.dbSlug = dbSlug;
                                    ViewBag.IsAjaxCrawlable = Request.IsAjaxCrawlingCapable(); // Check if page is Ajax Crawlable
                                    if (!Request.Cookies.AllKeys.Contains("version"))
                                        return View("Details2", show);
                                    return View(show);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 11
0
        public ActionResult ActivatePpc(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            string url = Url.Action("Index", "Ppc").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) // process form
                {
                    string serial = fc["serial"];
                    string pin = fc["pin"];
                    //remove whitespaces
                    serial = serial.Replace(" ", String.Empty);
                    pin = pin.Replace(" ", String.Empty);
                    if (!Request.IsLocal)
                        pin = MyUtility.GetSHA1(pin); // encrypt

                    if (User.Identity.IsAuthenticated)
                    {
                        Ppc.ErrorCode code;
                        var context = new IPTV2Entities();
                        System.Guid userId = new System.Guid(User.Identity.Name);
                        User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                        if (user != null)
                        {
                            Offering offering = context.Offerings.Find(GlobalConfig.offeringId);
                            if (user.HasPendingGomsChangeCountryTransaction(offering))
                                ReturnCode.StatusMessage = "We are processing your recent change in location. Please try again after a few minutes.";
                            else
                            {
                                var ppc = context.Ppcs.FirstOrDefault(p => String.Compare(p.SerialNumber, serial, true) == 0);
                                if (ppc != null)
                                {
                                    if (!(String.Compare(ppc.SerialNumber, serial, true) == 0 && String.Compare(ppc.Pin, pin, false) == 0))
                                        ReturnCode.StatusMessage = "Invalid serial/pin combination.";
                                    else if (ppc.ExpirationDate < registDt)
                                        ReturnCode.StatusMessage = "Prepaid Card/ePIN is already expired.";
                                    else if (ppc.UserId != null)
                                        ReturnCode.StatusMessage = "Prepaid Card/ePIN is already used.";
                                    else
                                    {
                                        if (ppc is ReloadPpc)
                                        {
                                            if (user.HasExceededMaximumReloadTransactionsForTheDay(GlobalConfig.reloadTransactionMaximumThreshold, registDt))
                                                ReturnCode.StatusMessage = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day. Please try again later.", GlobalConfig.paymentTransactionMaximumThreshold);
                                            else // process reloadPpc                                            
                                            {
                                                code = ReloadHelper.ReloadViaPrepaidCard(context, userId, serial, pin);
                                                if (code == Ppc.ErrorCode.Success)
                                                {
                                                    var wallet = user.UserWallets.FirstOrDefault(w => String.Compare(w.Currency, user.Country.CurrencyCode, true) == 0);
                                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                                    ReturnCode.StatusMessage = String.Format("You have successfully topped up your wallet. Your wallet balance is {0} {1}.", wallet.Currency, wallet.Balance);
                                                }
                                                else
                                                    ReturnCode.StatusMessage = MyUtility.GetPpcErrorMessages(code);
                                            }

                                        }
                                        else if (ppc is SubscriptionPpc)
                                        {
                                            if (user.HasExceededMaximumPaymentTransactionsForTheDay(GlobalConfig.paymentTransactionMaximumThreshold, registDt))
                                                ReturnCode.StatusMessage = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day. Please try again later.", GlobalConfig.paymentTransactionMaximumThreshold);
                                            else
                                            {
                                                SubscriptionPpc sPpc = (SubscriptionPpc)ppc;
                                                Product product = context.Products.FirstOrDefault(p => p.ProductId == sPpc.ProductId);
                                                if (product == null)
                                                    ReturnCode.StatusMessage = "This product does not exist.";
                                                else
                                                {
                                                    //if (sPpc.IsRegular)
                                                    //    if (!product.IsForSale)
                                                    //    {
                                                    //        ReturnCode.StatusMessage = "This product is currently not for sale.";
                                                    //        TempData["ErrorMessage"] = ReturnCode;
                                                    //        url = Request.UrlReferrer.AbsolutePath;
                                                    //        return Redirect(url);
                                                    // }
                                                    SubscriptionProductType subscriptionType = ContextHelper.GetProductType(product);
                                                    ErrorResponse response = PaymentHelper.PayViaPrepaidCard(context, userId, sPpc.ProductId, subscriptionType, serial, pin, userId, null);
                                                    code = (Ppc.ErrorCode)response.Code;
                                                    if (code == Ppc.ErrorCode.Success)
                                                    {
                                                        ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                                        ReturnCode.StatusHeader = "Activate Prepaid Card/ePIN Complete!";
                                                        ReturnCode.StatusMessage = String.Format("You have successfully subscribed to {0}.", product.Description);
                                                        ReturnCode.StatusMessage2 = "Pwede ka nang manood ng mga piling Kapamilya shows at movies.<br>Visit your Free Trial page to see what's available and start watching!";
                                                        TempData["ErrorMessage"] = ReturnCode;
                                                        return RedirectToAction("Index", "Home"); //successful activation of ppc
                                                    }
                                                    else
                                                        ReturnCode.StatusMessage = MyUtility.GetPpcErrorMessages(code);
                                                }
                                            }
                                        }
                                        else
                                            ReturnCode.StatusMessage = "Unable to retrieve this type of Prepaid Card/ePIN.";
                                    }
                                }
                                else
                                    ReturnCode.StatusMessage = "Prepaid Card/ePIN does not exist.";
                            }
                        }
                        else
                            ReturnCode.StatusMessage = "User does not exist.";
                    }
                    else
                        ReturnCode.StatusMessage = "Your session has already expired. Please login again.";
                }
                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);
        }
Exemplo n.º 12
0
        public ActionResult PremiumTrial(string email)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty,
                info = "Promo",
                TransactionType = "Premium Trial"
            };
            if (String.IsNullOrEmpty(email))
                ReturnCode.StatusMessage = "You are missing some required information.";

            var registDt = DateTime.Now;
            try
            {
                var context = new IPTV2Entities();
                var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, email, true) == 0);
                if (user != null)
                {
                    var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.PremiumTrialPromoId && p.StartDate < registDt && p.EndDate > registDt && p.StatusId == GlobalConfig.Visible);
                    if (promo != null)
                    {
                        var userpromo = context.UserPromos.FirstOrDefault(s => s.UserId == user.UserId && s.PromoId == GlobalConfig.PremiumTrialPromoId);
                        if (userpromo != null)
                        {
                            if (userpromo.AuditTrail.UpdatedOn == null)
                            {
                                PaymentHelper.PayViaWallet(context, user.UserId, GlobalConfig.PremiumTrialPromoProductId, SubscriptionProductType.Package, user.UserId, null);
                                userpromo.AuditTrail.UpdatedOn = registDt;
                                context.SaveChanges();
                                ReturnCode.StatusHeader = "Your FREE Premium Subscription starts now!";
                                ReturnCode.StatusMessage = "Pwede ka nang manood ng mga piling Kapamilya shows at movies. Visit your My Entitlements Page to see your free entitlement.";
                            }
                            else
                            {
                                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                ReturnCode.StatusMessage = "You have already claimed your free entitlement.";
                            }
                        }
                        else
                        {
                            ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                            ReturnCode.StatusMessage = "You are not eligible for this promo.";
                        }
                    }
                    else
                    {
                        ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                        ReturnCode.StatusMessage = "The promo has already ended.";
                    }
                }
                else
                {
                    ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                    ReturnCode.StatusMessage = String.Format("{0} does not exist.", email);
                }
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                ReturnCode.StatusMessage = e.Message;
            }
            if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
            {
                TempData["ErrorMessage"] = ReturnCode;
            }
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 13
0
        public ActionResult _Claim201411(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty,
                info = "Compensation Claim",
                TransactionType = "CompensationClaimTransaction"
            };
            var registDt = DateTime.Now;
            var userId = fc["targetUserId"];
            if (String.IsNullOrEmpty(userId))
                ReturnCode.StatusMessage = "You are missing some required information.";
            else
            {
                try
                {
                    var context = new IPTV2Entities();
                    var user = context.Users.FirstOrDefault(u => u.UserId == new Guid(userId));
                    var subscriptionproductids = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds);
                    var subscriptionProductIdsfor3days = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds1Month);
                    var subscriptionProductIdsfor7days = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds12Month).Union(MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds3Month));
                    var freeProductId = GlobalConfig.Compensation201411ProductId1Month;
                    var freeProductIdPremium = GlobalConfig.Compensatory3DaysProductId;
                    if (user != null)
                    {
                        var userpromo = context.UserPromos.FirstOrDefault(u => u.PromoId == GlobalConfig.Compensation2014PromoId && u.UserId == user.UserId);
                        if (userpromo != null)
                        {
                            if (userpromo.AuditTrail.UpdatedOn == null)
                            {
                                var purchaseitem = context.PurchaseItems.OrderByDescending(p => p.PurchaseId).FirstOrDefault(p => p.RecipientUserId == user.UserId && subscriptionproductids.Contains(p.ProductId));
                                if (purchaseitem != null)
                                {
                                    if ((subscriptionProductIdsfor7days.Contains(purchaseitem.ProductId)))
                                    {
                                        freeProductId = GlobalConfig.Compensation201411ProductId3and12Month;
                                        freeProductIdPremium = GlobalConfig.Compensatory7DaysProductId;

                                    }

                                    var success = PaymentHelper.PayViaWallet(context, user.UserId, freeProductId, SubscriptionProductType.Package, user.UserId, null);
                                    success = PaymentHelper.PayViaWallet(context, user.UserId, freeProductIdPremium, SubscriptionProductType.Package, user.UserId, null);
                                    if (success.Code == 0)
                                    {
                                        userpromo.AuditTrail.UpdatedOn = registDt;
                                        if (context.SaveChanges() > 0)
                                        {
                                            ReturnCode.StatusCode = 0;
                                            ReturnCode.StatusHeader = "Your Free Package starts now!";
                                            ReturnCode.StatusMessage = "Pwede ka nang manood ng mga piling Kapamilya shows at movies. Visit your My Subscriptions Page to see your free entitlements.";
                                        }
                                        else
                                        {
                                            ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                            ReturnCode.StatusMessage = "Our system encountered an unidentified error. Please try again later.";
                                        }
                                    }
                                    else
                                    {
                                        ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                        ReturnCode.StatusMessage = success.Message;
                                    }
                                }


                                else
                                {
                                    ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                    ReturnCode.StatusMessage = "User's last paid purchase not found.";
                                }
                            }
                            else
                            {
                                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                ReturnCode.StatusMessage = "You have already claimed this package.";
                            }
                        }
                        else
                        {
                            ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                            ReturnCode.StatusMessage = "You are not eligible for this compensation.";
                        }
                    }
                    else
                    {
                        ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                        ReturnCode.StatusMessage = "Target user not found.";
                    }
                }
                catch (Exception e)
                {
                    MyUtility.LogException(e);
                    ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                    ReturnCode.StatusMessage = e.Message;
                }
            }
            if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
                TempData["ErrorMessage"] = ReturnCode;
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 14
0
        //
        // GET: /Free/

        public ActionResult Compensation201411(string id)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty,
                info = "Compensation Claim",
                TransactionType = "CompensationClaimTransaction"
            };
            try
            {
                if (String.IsNullOrEmpty(id))
                {
                    ReturnCode.StatusMessage = "You are missing some required information.";
                    return RedirectToAction("Index", "Home");
                }

                int freeProductId = GlobalConfig.Compensation201411ProductId1Month;
                var categoryid = GlobalConfig.Compensation201411CategoryId1Month;
                int takeamount = 2;

                var subscriptionproductids = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds);
                var subscriptionProductIdsfor3days = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds1Month);
                var subscriptionProductIdsfor7days = MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds12Month).Union(MyUtility.StringToIntList(GlobalConfig.SubscriptionProductIds3Month));
                var context = new IPTV2Entities();
                DateTime registDt = DateTime.Now;
                var promo = context.Promos.FirstOrDefault(p => p.PromoId == GlobalConfig.Compensation2014PromoId && p.StatusId == GlobalConfig.Visible && registDt > p.StartDate && registDt < p.EndDate);
                if (promo != null)
                {
                    Guid userid;
                    Guid activationkey;
                    var uGuid = Guid.TryParse(id.Substring(0, 36), out userid);
                    var aGuid = Guid.TryParse(id.Substring(36, 36), out activationkey);
                    if (uGuid && aGuid)
                    {
                        var user = context.Users.FirstOrDefault(u => u.UserId == userid && u.ActivationKey == activationkey);
                        if (user != null)
                        {
                            var userpromo = context.UserPromos.FirstOrDefault(u => u.PromoId == GlobalConfig.Compensation2014PromoId && u.UserId == user.UserId);
                            if (userpromo != null)
                            {
                                if (userpromo.AuditTrail.UpdatedOn == null)
                                {
                                    var purchaseitem = context.PurchaseItems.OrderByDescending(p => p.PurchaseId).FirstOrDefault(p => p.RecipientUserId == userid && subscriptionproductids.Contains(p.ProductId));
                                    if (purchaseitem != null)
                                    {
                                        if ((subscriptionProductIdsfor7days.Contains(purchaseitem.ProductId)))
                                        {
                                            freeProductId = GlobalConfig.Compensation201411ProductId3and12Month;
                                            categoryid = GlobalConfig.Compensation201411CategoryId3and12Month;
                                            takeamount = 4;
                                        }

                                        ViewBag.targetUserId = userid.ToString();
                                        ViewBag.freeProductId = freeProductId;
                                        var offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);
                                        var service = offering.Services.FirstOrDefault(s => s.PackageId == GlobalConfig.serviceId);

                                        Category category = (Category)context.CategoryClasses.FirstOrDefault(c => c.CategoryId == categoryid && c.StatusId == GlobalConfig.Visible);
                                        if (category != null)
                                        {
                                            SortedSet<int> showIds = service.GetAllOnlineShowIds(MyUtility.getCountry(Request.GetUserHostAddressFromCloudflare()).getCode(), category);
                                            if (showIds.Count() == 0)
                                            {
                                                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                                ReturnCode.StatusMessage = "Shows not available.";
                                                return RedirectToAction("Index", "Home");
                                            }

                                            int[] setofShows = showIds.ToArray();
                                            var list = context.CategoryClasses.Where(c => setofShows.Contains(c.CategoryId) && c.StartDate <= registDt && c.EndDate >= registDt && c.StatusId == GlobalConfig.Visible).OrderBy(c => c.CategoryName).ThenBy(c => c.StartDate).ToList().Take(takeamount);

                                            List<CategoryShowListDisplay> catList = new List<CategoryShowListDisplay>();

                                            foreach (var item in list)
                                            {
                                                string img = String.IsNullOrEmpty(item.ImagePoster) ? GlobalConfig.AssetsBaseUrl + GlobalConfig.BlankGif : String.Format("{0}{1}/{2}", GlobalConfig.ShowImgPath, item.CategoryId.ToString(), item.ImagePoster);
                                                catList.Add(new CategoryShowListDisplay
                                                {
                                                    CategoryId = item.CategoryId,
                                                    Description = item.Description,
                                                    ImagePoster = img,
                                                    AiredDate = item.StartDate,
                                                });
                                            }
                                            return View(catList);
                                        }
                                        else
                                        {
                                            ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                            ReturnCode.StatusMessage = "Package not found.";
                                        }
                                    }
                                    else
                                    {
                                        ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                        ReturnCode.StatusMessage = "User's last paid purchase not found.";
                                    }
                                }
                                else
                                {
                                    ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                    ReturnCode.StatusMessage = "You have already claimed this package.";
                                }
                            }
                            else
                            {
                                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                                ReturnCode.StatusMessage = "You are not eligible for this compensation.";
                            }
                        }
                        else
                        {
                            ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                            ReturnCode.StatusMessage = "Target user not found.";
                        }
                    }
                    else
                    {
                        ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                        ReturnCode.StatusMessage = "Invalid link.";
                    }
                }
                else
                {
                    ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                    ReturnCode.StatusMessage = "Compensation program is disabled.";
                }
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusHeader = "Oops! There seems to be a problem.";
                ReturnCode.StatusMessage = e.Message;
            }
            if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
                TempData["ErrorMessage"] = ReturnCode;
            return RedirectToAction("Index", "Home");
        }
Exemplo n.º 15
0
        public ActionResult _EWallet(FormCollection fc)
        {
            Response.ContentType = "application/json";
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError)
            };

            try
            {
                if (String.IsNullOrEmpty(fc["id"]))
                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);

                if (!Request.IsAjaxRequest())
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest;
                    ReturnCode.StatusMessage = "Your request is invalid.";
                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (!GlobalConfig.IsEWalletPaymentModeEnabled)
                {
                    ReturnCode.StatusCode = (int)PaymentError.EWALLET_PAYMENT_IS_DISABLED;
                    ReturnCode.StatusMessage = "E-Wallet payment is currenty disabled.";
                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (User.Identity.IsAuthenticated)
                {
                    int? id = Convert.ToInt32(fc["id"]); //Get ID

                    var registDt = DateTime.Now;
                    var context = new IPTV2Entities();
                    System.Guid userId = new System.Guid(User.Identity.Name);
                    User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                    Product product = context.Products.FirstOrDefault(p => p.ProductId == id);
                    if (product == null)
                    {
                        ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNull;
                        ReturnCode.StatusMessage = MyUtility.getErrorMessage(ErrorCodes.ProductIsNull);
                        return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                    }
                    if (product.StatusId != GlobalConfig.Visible)
                    {
                        ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNotPurchaseable;
                        ReturnCode.StatusMessage = MyUtility.getErrorMessage(ErrorCodes.ProductIsNotPurchaseable);
                        return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                    }
                    if (!product.IsForSale)
                    {
                        ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNotPurchaseable;
                        ReturnCode.StatusMessage = MyUtility.getErrorMessage(ErrorCodes.ProductIsNotPurchaseable);
                        return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                    }

                    SubscriptionProductType subscriptionType = ContextHelper.GetProductType(product);
                    string productName = product.Name;
                    Offering offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);

                    if (user != null)
                    {
                        if (offering != null)
                        {
                            if (user.HasPendingGomsChangeCountryTransaction(offering))
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.HasPendingChangeCountryTransaction;
                                ReturnCode.StatusMessage = "We are processing your recent change in location. Please try again after a few minutes.";
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }

                            if (user.HasExceededMaximumPaymentTransactionsForTheDay(GlobalConfig.paymentTransactionMaximumThreshold, registDt))
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.MaximumTransactionsExceeded;
                                ReturnCode.StatusMessage = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day. Please try again later.", GlobalConfig.paymentTransactionMaximumThreshold);
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }
                        }

                        if (GlobalConfig.IsRecurringBillingEnabled)
                        {
                            var checkIfEnrolled = CheckIfUserIsEnrolledToSameRecurringProductGroup(context, offering, user, product);
                            if (checkIfEnrolled.value)
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.IsCurrentlyEnrolledInRecurringBilling;
                                ReturnCode.StatusMessage = "You are currently automatically renewing a similar subscription product through credit card.";
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }
                        }

                        /**************** CHECK FOR WISHLISTING, PRODUCT RESTRICTION **********************/
                        User recipient = null;
                        //Get Recipient
                        string wid = fc["wid"];
                        if (!String.IsNullOrEmpty(wid))
                        {
                            GSArray gsarray = GigyaMethods.GetWishlistDetails(wid);
                            if (gsarray != null)
                            {
                                JObject o = JObject.Parse(gsarray.GetObject(0).ToJsonString());
                                System.Guid recipientUserId = new System.Guid(o["UID_s"].ToString());
                                recipient = context.Users.FirstOrDefault(u => u.UserId == recipientUserId);
                                //ViewBag.RecipientEmail = recipient.EMail;
                                if (recipient != null)
                                    ReturnCode.Recipient = String.Format("{0} {1}", recipient.FirstName, recipient.LastName);
                            }

                            if (subscriptionType == SubscriptionProductType.Package)
                            {
                                //Check if user has a current subscription
                                if (!IsProductGiftable(context, product, recipient == null ? user.UserId : recipient.UserId))
                                {
                                    string CurrentProductName = ContextHelper.GetCurrentSubscribeProduct(context, product, recipient == null ? user.UserId : recipient.UserId, offering);
                                    ReturnCode.StatusMessage = String.Format("Sorry! You are already subscribed to {0}. You can no longer purchase {1}.", CurrentProductName, productName);
                                    if (recipient != null)
                                    {
                                        if (recipient.UserId != user.UserId) // same user
                                            ReturnCode.StatusMessage = String.Format("Sorry! {0} {1} is already subscribed to {2}. You can no longer gift {3}.", recipient.FirstName, recipient.LastName, CurrentProductName, productName);
                                    }
                                    ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNotPurchaseable;
                                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                                }
                            }
                        }

                        if (subscriptionType == SubscriptionProductType.Package)
                        {
                            if (!IsProductRestricted(context, product, recipient == null ? user.UserId : recipient.UserId))
                            {
                                //string productName = ContextHelper.GetProductName(context, product);
                                ReturnCode.StatusMessage = String.Format("Sorry! The ({0}) subscription is not available in your country.", productName);
                                if (recipient != null)
                                {
                                    if (recipient.UserId != user.UserId) // same user
                                        ReturnCode.StatusMessage = String.Format("Sorry! The ({0}) subscription is not available in the country where {1} {2} is. You are not allowed to send this gift.", productName, recipient.FirstName, recipient.LastName);
                                }
                                ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNotAllowedInCountry;
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }
                            if (String.IsNullOrEmpty(wid))
                            {
                                if (!IsProductPurchaseable(context, product, recipient == null ? user.UserId : recipient.UserId))
                                {
                                    string CurrentProductName = ContextHelper.GetCurrentSubscribeProduct(context, product, recipient == null ? user.UserId : recipient.UserId, offering);
                                    ReturnCode.StatusMessage = String.Format("Sorry! You are already subscribed to {0}. You can no longer purchase {1}.", CurrentProductName, productName);
                                    if (recipient != null)
                                    {
                                        if (recipient.UserId != user.UserId) // same user
                                            ReturnCode.StatusMessage = String.Format("Sorry! {0} {1} is already subscribed to {2}. You can no longer gift {3}.", recipient.FirstName, recipient.LastName, CurrentProductName, productName);
                                    }
                                    ReturnCode.StatusCode = (int)ErrorCodes.ProductIsNotPurchaseable;
                                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                                }
                            }
                        }
                        /**************** END OF CHECK FOR WISHLISTING, PRODUCT RESTRICTION ***************/

                        int? cpid = null;
                        if (!String.IsNullOrEmpty(fc["cpid"]))
                            Convert.ToInt32(fc["cpid"]);

                        ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == MyUtility.GetCurrencyOrDefault(user.CountryCode));
                        UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == MyUtility.GetCurrencyOrDefault(user.CountryCode));
                        ErrorCodes StatusCode = ErrorCodes.UnknownError;
                        if (wallet.Balance >= priceOfProduct.Amount)
                        {
                            ErrorResponse response = PaymentHelper.PayViaWallet(context, userId, product.ProductId, subscriptionType, recipient == null ? userId : recipient.UserId, cpid);
                            StatusCode = (ErrorCodes)response.Code;
                            string CountryCode = MyUtility.GetCurrencyOrDefault(user.CountryCode);
                            Currency currency = context.Currencies.FirstOrDefault(c => c.Code == CountryCode);
                            ReturnCode.StatusCode = (int)StatusCode;
                            if (StatusCode == ErrorCodes.Success)
                            {
                                ProcessWishlist(wid, product, recipient, user);

                                string balance = String.Format("Your new wallet balance is {0} {1}.", currency.Code, wallet.Balance.ToString("F"));
                                ReturnCode.StatusMessage = balance;

                                //To be used in the Thank You page
                                //TempData["Product"] = product;
                                TempData["PaymentMode"] = "WALLET";
                                TempData["StatusMessage"] = balance;
                                //TempData["Transaction"] = user.Transactions.Last();

                                ReturnCode.WId = wid;
                                ReturnCode.HtmlUri = "/Payment/Confirmation";
                                if (!String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                                    ReturnCode.HtmlUri = String.Format("{0}{1}", ReturnCode.HtmlUri, String.Format("?ReturnUrl={0}", Request.QueryString["ReturnUrl"]));
                            }
                            else
                            {
                                ReturnCode.StatusCode = (int)StatusCode;
                                ReturnCode.StatusMessage = MyUtility.getErrorMessage(StatusCode);
                            }
                        }
                        else
                        {
                            ReturnCode.StatusCode = (int)ErrorCodes.InsufficientWalletLoad;
                            ReturnCode.StatusMessage = MyUtility.getErrorMessage(ErrorCodes.InsufficientWalletLoad);
                        }
                    }
                }
                else
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated;
                    ReturnCode.StatusMessage = "Your session has expired. Please login again.";
                }
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                ReturnCode.StatusMessage = e.Message;
            }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 16
0
        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);
        }
Exemplo n.º 17
0
        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);
        }
Exemplo n.º 18
0
        public JsonResult ConnectSNS(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError)
            };

            if (GlobalConfig.IsForceConnectToSNSEnabled)
            {
                if (String.IsNullOrEmpty(fc["UID"]) || String.IsNullOrEmpty(fc["provider"]))
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.IsMissingRequiredFields;
                    ReturnCode.StatusMessage = "Required fields missing.";
                    return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (!User.Identity.IsAuthenticated)
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated;
                    ReturnCode.StatusMessage = "User is not authenticated.";
                }
                else
                {
                    try
                    {
                        var context = new IPTV2Entities();
                        var user = context.Users.FirstOrDefault(u => u.UserId == new Guid(User.Identity.Name));
                        if (user != null)
                        {
                            Dictionary<string, object> collection = new Dictionary<string, object>();

                            string UID = fc["UID"];
                            string provider = fc["provider"];
                            collection.Add("siteUID", user.UserId.ToString());
                            collection.Add("uid", Uri.UnescapeDataString(UID));
                            collection.Add("cid", String.Format("{0} - New User", provider));
                            GSResponse notifyRegistration = GigyaHelpers.createAndSendRequest("socialize.notifyRegistration", GigyaHelpers.buildParameter(collection));
                            if (notifyRegistration.GetErrorCode() == 0)
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                ReturnCode.StatusMessage = "Successfully linked social network account.";
                            }
                            else
                                ReturnCode.StatusMessage = notifyRegistration.GetErrorMessage();
                        }
                    }
                    catch (Exception e) { ReturnCode.StatusMessage = e.Message; MyUtility.LogException(e); }
                }
            }
            return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
        public JsonResult LogPlayback(int type, int id, int playTypeId, int? fullDuration, bool isPreview, string positionDuration, string streamType, int? bufferCount, int? minBandwidth, int? maxBandwidth, int? avgBandwidth)
        {
            //Response.ContentType = "application/json";
            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
            {
                DateTime registDt = DateTime.Now;
                int positionDuration_Integer = 0; int sType = 0;
                try { positionDuration_Integer = Int32.Parse(positionDuration); }
                catch (Exception) { }
                try { sType = Int32.Parse(streamType); }
                catch (Exception) { }
                if (fullDuration == null)
                    fullDuration = -1000;

                var context = new IPTV2Entities();
                var userId = new Guid(User.Identity.Name);
                int categoryId = 0, assetId = 0;


                int[] fillDuration = { 2, 3, 4 };

                var returnCode = new SqlParameter()
                {
                    ParameterName = "returnCode",
                    DbType = System.Data.DbType.Int32,
                    Direction = System.Data.ParameterDirection.Output
                };

                string tableName = String.Format("EpisodePlay{0}", registDt.ToString("yyyyMM"));
                using (var videoContext = new VideoEngagementsEntities())
                {
                    switch (type)
                    {
                        case 4:
                        case 1: //EpisodePlay
                            {
                                var episode = context.Episodes.FirstOrDefault(e => e.EpisodeId == id);
                                if (episode != null)
                                {
                                    var excludedCategoryIds = MyUtility.StringToIntList(GlobalConfig.ExcludedCategoryIdsForDisplay);
                                    var episodeCategory = episode.EpisodeCategories.FirstOrDefault(e => !excludedCategoryIds.Contains(e.CategoryId));
                                    categoryId = episodeCategory.CategoryId;
                                    var asset = episode.PremiumAssets.FirstOrDefault();
                                    if (asset != null)
                                        assetId = asset.AssetId;
                                }

                                if (episode.IsLiveChannelActive == true)
                                {
                                    var sTypeParam = new SqlParameter()
                                    {
                                        ParameterName = "StreamType",
                                        DbType = System.Data.DbType.Int32,
                                        Value = 0
                                    };
                                    var result = videoContext.Database.ExecuteSqlCommand("EXEC LogMediaPlayback @table, @PlayTypeId, @EpisodeId, @AssetId, @UserId, @registDt, @duration, @length, @CategoryId, @StartPosition, @isPreview, @StreamType, @returnCode OUTPUT",
                                    new object[] {  
                                 new SqlParameter("table", tableName),
                                 new SqlParameter("PlayTypeId", playTypeId),
                                 new SqlParameter("EpisodeId", id),
                                 new SqlParameter("AssetId", assetId),
                                 new SqlParameter("UserId", userId),
                                 new SqlParameter("registDt", registDt),
                                 new SqlParameter("duration", fillDuration.Contains(playTypeId) ? positionDuration_Integer : 0),
                                 new SqlParameter("length", -1000),
                                 new SqlParameter("CategoryId", categoryId),
                                 new SqlParameter("StartPosition", -1000),
                                 new SqlParameter("isPreview", false),
                                 sTypeParam,
                                 returnCode
                                });
                                }
                                else
                                {
                                    var result = videoContext.Database.ExecuteSqlCommand("EXEC LogMediaPlayback @table, @PlayTypeId, @EpisodeId, @AssetId, @UserId, @registDt, @duration, @length, @CategoryId, @StartPosition, @isPreview, @StreamType, @returnCode OUTPUT",
                                    new object[] {  
                                 new SqlParameter("table", tableName),
                                 new SqlParameter("PlayTypeId", playTypeId),
                                 new SqlParameter("EpisodeId", id),
                                 new SqlParameter("AssetId", assetId),
                                 new SqlParameter("UserId", userId),
                                 new SqlParameter("registDt", registDt),
                                 new SqlParameter("duration", fillDuration.Contains(playTypeId) ? positionDuration_Integer : 0),
                                 new SqlParameter("length",(int)fullDuration),
                                 new SqlParameter("CategoryId", categoryId),
                                 new SqlParameter("StartPosition", fillDuration.Contains(playTypeId) ? 0 : positionDuration_Integer),
                                 new SqlParameter("isPreview", isPreview),
                                 new SqlParameter("StreamType", sType),
                                 returnCode
                                });
                                }


                                //Log onto TFCtvWebApi (Json)
                                try
                                {
                                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GlobalConfig.TFCtvApiVideoPlaybackUri);
                                    req.Method = "POST";
                                    req.ContentType = "application/json";
                                    using (var streamWriter = new StreamWriter(req.GetRequestStream()))
                                    {
                                        string jsonString = String.Empty;
                                        var obj = new TfcTvApiPlaybackObj()
                                        {
                                            PlayTypeId = playTypeId,
                                            UserId = userId.ToString(),
                                            DateTime = registDt.ToString("o"),
                                            EpisodeId = id,
                                            CategoryId = categoryId,
                                            Duration = fillDuration.Contains(playTypeId) ? positionDuration_Integer : 0,
                                            Length = episode.IsLiveChannelActive == true ? -1000 : (int)fullDuration,
                                            AssetId = assetId,
                                            StartPosition = episode.IsLiveChannelActive == true ? -1000 : fillDuration.Contains(playTypeId) ? 0 : positionDuration_Integer,
                                            LastPosition = fillDuration.Contains(playTypeId) ? positionDuration_Integer : 0,
                                            ClientIp = MyUtility.GetClientIpAddress(),
                                            IsPreview = isPreview,
                                            DeviceHeader = Request.UserAgent,
                                            BufferCount = bufferCount != null ? (int)bufferCount : -1,
                                            MaxBitrate = maxBandwidth != null ? (int)maxBandwidth : -1,
                                            MinBitrate = minBandwidth != null ? (int)minBandwidth : -1,
                                            AvgBitrate = avgBandwidth != null ? (int)avgBandwidth : -1

                                        };
                                        jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
                                        streamWriter.Write(jsonString);
                                    }

                                    WebResponse response = req.GetResponse();
                                    var statusDescription = ((HttpWebResponse)response).StatusDescription;
                                    Stream dataStream = response.GetResponseStream();
                                    StreamReader reader = new StreamReader(dataStream);
                                    string responseFromServer = reader.ReadToEnd();
                                    reader.Close();
                                    dataStream.Close();
                                    response.Close();
                                }
                                catch (Exception) { }

                                ////Log onto TFCtvWebApi
                                //try
                                //{
                                //    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(GlobalConfig.TFCtvApiVideoPlaybackUri);
                                //    req.Method = "POST";
                                //    req.ContentType = "application/x-www-form-urlencoded";
                                //    StringBuilder postData = new StringBuilder();
                                //    postData.Append(String.Format("PlayTypeId={0}&", playTypeId));
                                //    postData.Append(String.Format("UserId={0}&", userId));
                                //    postData.Append(String.Format("DateTime={0}&", registDt.ToString("o")));
                                //    postData.Append(String.Format("EpisodeId={0}&", id));
                                //    postData.Append(String.Format("CategoryId={0}&", categoryId));
                                //    postData.Append(String.Format("Duration={0}&", fillDuration.Contains(playTypeId) ? positionDuration_Integer : 0));
                                //    postData.Append(String.Format("Length={0}&", episode.IsLiveChannelActive == true ? -1000 : (int)fullDuration));
                                //    postData.Append(String.Format("AssetId={0}&", assetId));
                                //    postData.Append(String.Format("StartPosition={0}&", episode.IsLiveChannelActive == true ? -1000 : fillDuration.Contains(playTypeId) ? 0 : positionDuration_Integer));
                                //    postData.Append(String.Format("ClientIp={0}&", MyUtility.GetClientIpAddress()));
                                //    postData.Append(String.Format("IsPreview={0}&", isPreview));
                                //    postData.Append(String.Format("DeviceHeader={0}&", Request.UserAgent));

                                //    byte[] param = Encoding.UTF8.GetBytes(postData.ToString());
                                //    req.ContentLength = param.Length;

                                //    Stream dataStream = req.GetRequestStream();
                                //    dataStream.Write(param, 0, param.Length);
                                //    dataStream.Close();
                                //    WebResponse response = req.GetResponse();
                                //    var statusDescription = ((HttpWebResponse)response).StatusDescription;
                                //    dataStream = response.GetResponseStream();
                                //    StreamReader reader = new StreamReader(dataStream);
                                //    string responseFromServer = reader.ReadToEnd();
                                //    reader.Close();
                                //    dataStream.Close();
                                //    response.Close();
                                //}
                                //catch (Exception) { }
                                break;
                            }
                        case 2: //ChannelPlay
                            {
                                break;
                            }
                        case 3: //YoutubePlay
                            {
                                break;
                            }
                    }
                }
                if ((int)returnCode.Value > 0)
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                    ReturnCode.StatusMessage = "Playback logged.";
                }
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusMessage = e.Message;
            }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        public JsonResult CreateInteraction(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };
            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    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
                    {
                        int reactionId = Convert.ToInt32(fc["reactionId"]);
                        string type = fc["type"];
                        int id = Convert.ToInt32(fc["id"]);
                        var UserId = new Guid(User.Identity.Name);
                        var registDt = DateTime.Now;
                        using (var context = new EngagementsEntities())
                        {
                            switch (type)
                            {
                                case "show":
                                    if (reactionId == GlobalConfig.SOCIAL_LOVE) //12 Is Social_Love
                                    {
                                        int click = Convert.ToInt32(fc["click"]);
                                        var reaction = context.ShowReactions.FirstOrDefault(i => i.CategoryId == id && i.ReactionTypeId == reactionId && i.UserId == UserId);
                                        if (reaction != null || click == 0)
                                            context.ShowReactions.Remove(reaction);
                                        else
                                        {
                                            reaction = new ShowReaction()
                                            {
                                                UserId = UserId,
                                                CategoryId = id,
                                                ReactionTypeId = reactionId,
                                                DateTime = registDt
                                            };
                                            context.ShowReactions.Add(reaction);
                                        }
                                    }
                                    else
                                    {
                                        var reaction = new ShowReaction()
                                        {
                                            UserId = UserId,
                                            CategoryId = id,
                                            ReactionTypeId = reactionId,
                                            DateTime = registDt
                                        };
                                        context.ShowReactions.Add(reaction);
                                    }
                                    break;
                                case "episode":
                                    if (reactionId == GlobalConfig.SOCIAL_LOVE) //12 Is Social_Love
                                    {
                                        int click = Convert.ToInt32(fc["click"]);
                                        var reaction = context.EpisodeReactions.FirstOrDefault(i => i.EpisodeId == id && i.ReactionTypeId == reactionId && i.UserId == UserId);
                                        if (reaction != null || click == 0)
                                            context.EpisodeReactions.Remove(reaction);
                                        else
                                        {
                                            reaction = new EpisodeReaction()
                                            {
                                                UserId = UserId,
                                                EpisodeId = id,
                                                ReactionTypeId = reactionId,
                                                DateTime = registDt
                                            };
                                            context.EpisodeReactions.Add(reaction);
                                        }
                                    }
                                    else
                                    {
                                        var reaction = new EpisodeReaction()
                                        {
                                            UserId = UserId,
                                            EpisodeId = id,
                                            ReactionTypeId = reactionId,
                                            DateTime = registDt
                                        };
                                        context.EpisodeReactions.Add(reaction);
                                    }
                                    break;
                                case "celebrity":
                                    if (reactionId == GlobalConfig.SOCIAL_LOVE) //12 Is Social_Love
                                    {
                                        int click = Convert.ToInt32(fc["click"]);
                                        var reaction = context.CelebrityReactions.FirstOrDefault(i => i.CelebrityId == id && i.ReactionTypeId == reactionId && i.UserId == UserId);
                                        if (reaction != null || click == 0)
                                            context.CelebrityReactions.Remove(reaction);
                                        else
                                        {
                                            reaction = new CelebrityReaction()
                                            {
                                                UserId = UserId,
                                                CelebrityId = id,
                                                ReactionTypeId = reactionId,
                                                DateTime = registDt
                                            };
                                            context.CelebrityReactions.Add(reaction);
                                        }
                                    }
                                    else
                                    {
                                        var reaction = new CelebrityReaction()
                                        {
                                            UserId = UserId,
                                            CelebrityId = id,
                                            ReactionTypeId = reactionId,
                                            DateTime = registDt
                                        };
                                        context.CelebrityReactions.Add(reaction);
                                    }
                                    break;
                            }

                            context.SaveChanges();
                        }
                    }

                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 23
0
        public ActionResult ResendVerification(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = "The system encountered an unspecified error. Please contact Customer Support.",
                info = "Resend Verification"
            };

            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["resendverification_email"];

                    //RegexUtilities util = new RegexUtilities();
                    if (!MyUtility.isEmail(EmailAddress))
                    {
                        ReturnCode.StatusMessage = "Email address is invalid.";
                        TempData["ResendVerificationErrorMessage"] = ReturnCode.StatusMessage;
                        return Redirect(Request.UrlReferrer.AbsoluteUri);
                    }

                    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 = "Email address is not registered to TFC.tv";
                        TempData["ResendVerificationErrorMessage"] = ReturnCode.StatusMessage;
                        return Redirect(Request.UrlReferrer.AbsoluteUri);
                    }

                    if (user.StatusId == GlobalConfig.Visible)
                    {
                        ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                        ReturnCode.StatusMessage = "This email is already activated.";
                        TempData["ResendVerificationErrorMessage"] = ReturnCode.StatusMessage;
                        return Redirect(Request.UrlReferrer.AbsoluteUri);
                    }

                    string verification_email = String.Format("{0}/User/Verify?key={1}", GlobalConfig.baseUrl, user.ActivationKey.ToString());
                    string emailBody = String.Format(GlobalConfig.EmailVerificationBodyTextOnly, user.FirstName, user.EMail, verification_email);

                    MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, "Activate your TFC.tv account", emailBody, MailType.TextOnly, emailBody);
                    ReturnCode.StatusMessage = "The verification email has been sent.";
                    TempData["ResendVerificationErrorMessage"] = ReturnCode.StatusMessage;
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }

            if (!String.IsNullOrEmpty(ReturnCode.StatusMessage))
                TempData["ResendVerificationErrorMessage"] = ReturnCode.StatusMessage;
            url = Request.UrlReferrer.AbsoluteUri;
            return Redirect(url);
        }
Exemplo n.º 24
0
        public JsonResult GetReactionCount(int reactionId, string type, int id)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty,
            };

            try
            {
                int reactionCount = 0;
                using (var context = new EngagementsEntities())
                {
                    switch (type)
                    {
                        case "show":
                            reactionCount = context.ShowReactions.Count(i => i.CategoryId == id && i.ReactionTypeId == reactionId);
                            break;
                        case "episode":
                            reactionCount = context.EpisodeReactions.Count(i => i.EpisodeId == id && i.ReactionTypeId == reactionId);
                            break;
                        case "celebrity":
                            reactionCount = context.CelebrityReactions.Count(i => i.CelebrityId == id && i.ReactionTypeId == reactionId);
                            break;
                    }
                }
                ReturnCode.StatusCode = (int)ErrorCodes.Success;
                ReturnCode.StatusMessage = String.Format("{0}", reactionCount);
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 25
0
        public JsonResult ResendTVEActivationCode(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            string url = Url.Action("Index", "Home").ToString();
            try
            {
                if (String.IsNullOrEmpty(fc["smartCardNum"]) && String.IsNullOrEmpty(fc["cusAccount"]))
                {
                    ReturnCode.StatusMessage = "Please fill up the required fields.";
                }
                else
                {
                    if (!User.Identity.IsAuthenticated)
                    {
                        ReturnCode.StatusMessage = "Your session has expired. Please login again.";
                    }
                    else
                    {
                        var context = new IPTV2Entities();
                        var UserId = new Guid(User.Identity.Name);
                        User user = context.Users.FirstOrDefault(u => u.UserId == UserId);

                        if (user != null)
                        {
                            var gomsService = new GomsTfcTv();
                            var response = gomsService.ResendTVEActivationCode(user.EMail, fc["smartCardNum"], fc["cusAccount"], user.LastName);
                            if (response.IsSuccess)
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                ReturnCode.StatusMessage = response.StatusMessage;
                            }
                            else
                                ReturnCode.StatusMessage = response.StatusMessage;
                        }
                        else
                            ReturnCode.StatusMessage = "User does not exist.";
                    }
                }
            }
            catch (Exception e) { ReturnCode.StatusMessage = e.Message; }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 26
0
        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);
        }
Exemplo n.º 27
0
        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);
        }
Exemplo n.º 28
0
        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);
        }
Exemplo n.º 29
0
        public JsonResult SeshCh()
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };
            try
            {
                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)
                    {
                        if (MyUtility.IsDuplicateSession(user, Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]))
                        {
                            System.Web.Security.FormsAuthentication.SignOut();
                            ReturnCode.StatusCode = (int)ErrorCodes.MultipleLoginDetected;
                        }
                    }

                }
            }
            catch (Exception) { }
            return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 30
0
        //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");
            }
        }